如果每次都要在shell中進行資料庫的操作,估計是一件十分不爽的活動,是以最好是在視圖函數中通過可視化的方式進行操作。
hello.py中index()視圖函數修改
@app.route('/',methods=['GET','POST'])
def index():
form = NameFome()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username = form.name.data)
db.session.add(user)
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data
form.name.data =''
return redirect(url_for('index'))
return render_template('index.html',form=form,name=session.get('name'), known=session.get('known',False))
變動說明:
- 采用查詢判斷送出的user是否存在資料庫中
- 增加了資料庫送出db.session.add(user)
- 在session中增加known用于傳遞給模闆
模闆修改
{% extends 'base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<div class='page_content'>
<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>
{{ wtf.quick_form(form) }}
{% endblock %}
增加一個條件語句用于針對不同使用者顯示不同内容