Browse Source

Chapter 5: Database use in the application (5b)

master
T. Meissner 6 years ago
parent
commit
59c7e489a4
2 changed files with 18 additions and 6 deletions
  1. +13
    -6
      hello.py
  2. +5
    -0
      templates/index.html

+ 13
- 6
hello.py View File

@ -1,5 +1,5 @@
import os import os
from flask import Flask, render_template, session, redirect, url_for, flash
from flask import Flask, render_template, session, redirect, url_for
from flask_bootstrap import Bootstrap from flask_bootstrap import Bootstrap
from flask_moment import Moment from flask_moment import Moment
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
@ -25,7 +25,7 @@ class Role(db.Model):
__tablename__ = 'roles' __tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True) name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self): def __repr__(self):
return '<Role %r>' % self.name return '<Role %r>' % self.name
@ -60,9 +60,16 @@ def internal_server_error(e):
def index(): def index():
form = NameForm() form = NameForm()
if form.validate_on_submit(): if form.validate_on_submit():
old_name = session.get('name')
if old_name is not None and old_name != form.name.data:
flash('Loks like you have changed your name!')
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
db.session.commit()
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('index')) return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
return render_template('index.html', form=form, name=session.get('name'),
known=session.get('known', False))

+ 5
- 0
templates/index.html View File

@ -6,6 +6,11 @@
{% block page_content %} {% block page_content %}
<div class="page-header"> <div class="page-header">
<h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
{% if not known %}
<p>Pleased to meet you!</p>
{% else %}
<p>Happy to see you again!</p>
{% endif %}
</div> </div>
{{ wtf.quick_form(form) }} {{ wtf.quick_form(form) }}
{% endblock %} {% endblock %}

Loading…
Cancel
Save