问题描述
一般的网站在未登录访问某个页面时,会跳转到登录界面,登录完后会跳转回原来那个页面,方便用户使用。
实现过程
1、使用url_for()
向登录界面传递需要跳转回的地址(存放在next中)
###查看页面
@app.route('/view/<code>', methods=['POST', 'GET'])
def return(code):
# 判断是否登录
if 'username' in session:
return render_template("view.html", code=code)
else:
# 如果为登录,重定向并传递当前页面路径,方便跳回
return redirect(url_for('loginpage', next='/view/'+code))
2、处理表单提交方式
经过以上设置后,尝试在未登录时访问页面,将被重定向到/login
页面,观察地址栏中URL,后面也会带上?next=/view/xx
的参数(xx为后台的code)。
刚开始想着是使用JS获取URL的参数,但这样显得有点麻烦,还需要用到正则表达式。
印象中表单是可以直接提交到当前地址栏中的URL的,将<form>
中的action
去掉即可。
3、获得页面和提交表单使用同一个URL,接受表单提交时附带的参数
为什么要使用同一个URL呢,因为经过第二步的修改,当后端重定向获取登录界面后,地址栏的URL即为表单提交的地址,所以该URL需要具备同时处理GET请求和登录POST表单的能力。代码实现如下
###登录页面跳转
@app.route('/login',methods=['POST', 'GET'])
def loginpage():
# 如果是GET请求,则返回页面模板
if request.method == 'GET':
return render_template("login.html")
# 如果是POST请求,则处理登录表单
if request.method == 'POST':
# 获取表单信息
username = request.form.get("uname")
password = request.form.get("upwd")
# 获取URL中net参数
next=request.args.get('next')
if check_password(username, password) == "OK":
#登陆成功后检查是否需要回跳
if(next):
return redirect(next)
else:
# 如果不需要回跳则定向到主菜单
return redirect(url_for('mainpage'))
else:
#登陆失败
return redirect(url_for('loginpage'))
总结
怎么说呢这个方法有点绕,如果大家有问题提可以在评论区一起讨论哦。