flask-contacts/app.py
Andros Fenollosa 4745131d75 test
2018-05-01 14:18:23 +02:00

113 lines
2.9 KiB
Python

from flask import Flask, redirect, url_for, render_template, request, flash
from models import db, Contact
from forms import ContactForm
# Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'my secret'
app.config['DEBUG'] = False
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://bgcmtrdgusuwik:05060b67183fb8ba7ddb937aaec3f6a20617b3bbd547ce89a19eceb760f6fa4b@ec2-54-217-217-142.eu-west-1.compute.amazonaws.com:5432/d2po2asdglml7g'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
@app.route("/")
def index():
'''
Home page
'''
return redirect(url_for('contacts'))
@app.route("/new_contact", methods=('GET', 'POST'))
def new_contact():
'''
Create new contact
'''
form = ContactForm()
if form.validate_on_submit():
my_contact = Contact()
form.populate_obj(my_contact)
db.session.add(my_contact)
try:
db.session.commit()
# User info
flash('Contact created correctly', 'success')
return redirect(url_for('contacts'))
except:
db.session.rollback()
flash('Error generating contact.', 'danger')
return render_template('web/new_contact.html', form=form)
@app.route("/edit_contact/<id>", methods=('GET', 'POST'))
def edit_contact(id):
'''
Edit contact
:param id: Id from contact
'''
my_contact = Contact.query.filter_by(id=id).first()
form = ContactForm(obj=my_contact)
if form.validate_on_submit():
try:
# Update contact
form.populate_obj(my_contact)
db.session.add(my_contact)
db.session.commit()
# User info
flash('Saved successfully', 'success')
except:
db.session.rollback()
flash('Error update contact.', 'danger')
return render_template(
'web/edit_contact.html',
form=form)
@app.route("/contacts")
def contacts():
'''
Show alls contacts
'''
print(app.config['SQLALCHEMY_DATABASE_URI'])
contacts = Contact.query.order_by(Contact.name).all()
print(len(contacts))
return render_template('web/contacts.html', contacts=contacts)
@app.route("/search")
def search():
'''
Search
'''
name_search = request.args.get('name')
all_contacts = Contact.query.filter(
Contact.name.contains(name_search)
).order_by(Contact.name).all()
return render_template('web/contacts.html', contacts=all_contacts)
@app.route("/contacts/delete", methods=('POST',))
def contacts_delete():
'''
Delete contact
'''
try:
mi_contacto = Contact.query.filter_by(id=request.form['id']).first()
db.session.delete(mi_contacto)
db.session.commit()
flash('Delete successfully.', 'danger')
except:
db.session.rollback()
flash('Error delete contact.', 'danger')
return redirect(url_for('contacts'))
if __name__ == "__main__":
app.run(host="0.0.0.0")