首先是模板类:
from_test
{% if name %}
{{ name }}
{% else %}
{% endif %}
处理程序:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test1.html')
@app.route('/login', methods=['post'])
def login():
name = request.form.get('name')
password = request.form.get('password')
if name == 'admin' and password == '123':
return render_template('test1.html', name=name)
return render_template('test1.html')
if __name__ == '__main__':
app.run(debug=True)
如果此时点击刷新按钮,那么会出现以下提示:
这不太友好,要解决这个问题可以使用重定向,Flask提供了redirect函数,用法如下:
@app.route('/login', methods=['get', 'post'])
def login():
name = request.form.get('name')
password = request.form.get('password')
if name == 'admin' and password == '123':
return redirect(url_for('login'))
return render_template('test1.html')
@app.route('/login', methods=['get', 'post'])
def login():
name = request.form.get('name')
password = request.form.get('password')
if name == 'admin' and password == '123':
session['name'] = name
return redirect(url_for('login'))
return render_template('test1.html', name=session.get('name'))
app.config['SECRET_KEY'] = 'myproject'
app.secret_key = 'myproject'
@app.route('/login', methods=['get', 'post'])
def login():
name = request.form.get('name')
password = request.form.get('password')
if name == 'admin' and password == '123':
session['name'] = name
return redirect(url_for('login'))
if name != 'admin':
flash('no this name')
return render_template('test1.html', name=session.get('name'))
页面模板中消息提示的代码:
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
import sys
reload(sys)
sys.setdefaultencoding('utf8')
大功告成!