【发布时间】:2020-08-11 14:44:40
【问题描述】:
设置:
- Flask 网络应用程序。
- 用户导航到多个页面之一 [例如
gamepage (localhost:5000/game) 或playerspage (localhost:5000/players)] 通过在表单中带有GAME_ID的 post 请求。GAME_ID用于获取更多详细信息并呈现页面。
目标:
- 当未经身份验证的用户向
/game发出post 请求时,将他们重定向到/login页面,但在会话中保留端点(game)和GAME_ID,以便成功登录后,我可以将他们发送回他们正在访问的页面。我的方法是进行 307 重定向。
在 application.py 中
@login_manager.unauthorized_handler
def intercept_unauthorized():
<Set NEXT_PAGE_FOR_REDIRECT and GAME_ID_FOR_REDIRECT into the session>
return redirect(url_for('login'))
@application.route("/login", methods=['GET', 'POST'])
def login():
#User sees the login page
if request.method=='GET':
<show the login page>
#User has submitted username and password on the login page
elif request.method=='POST':
<authentication code here>
if validUser:
#Get the page the user was trying to access e.g. 'game'
nextPage = session.get('NEXT_PAGE_FOR_REDIRECT')
session.pop('NEXT_PAGE_FOR_REDIRECT')
gameID = session.get('GAME_ID_FOR_REDIRECT')
session.pop('GAME_ID_FOR_REDIRECT')
return redirect(url_for(next_page, gameID=gameID), code=307)
@application.route("/game", methods=['POST'])
@login_required
def game():
if 'gameID' in request.form:
render_template('game.html', gameID=request.form['gameID'])
问题:
- 我可以重定向到
/game,其中request.method是POST。但是request.form中的数据是login页面提交的数据,即用户名和密码。 - 我可以访问我在
url_for行中设置的gameID,但它是在request.args中发送的(并且在浏览器的地址栏中可见),而不是通过request.form。
问题:
- 我使用重定向的方法是否正确?
- 如何修改发送至
/game的表单,以便将gameID添加到其中?
【问题讨论】: