我不确定,一旦输入用户名,为什么页面会重定向到/ index路由
from flask import Flask, session, redirect, url_for, request
from markupsafe import escape
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/index')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
代码来自flask的快速入门文档
答案 0 :(得分:0)
实际上,@ monsieuralfonse64已经给出了答案,所以我只作总结。
由于您的表单设置了method="post"
属性:
@app.route('/login', methods=['GET', 'POST'])
def login():
# ...
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
提交表单时,浏览器将以POST方法发送数据,这就是为什么它触发if request.method == 'POST':
语句,然后执行return redirect(url_for('index'))
的原因,最后页面重定向到/index。