Flask:redirect()函数

Posted `三一三`

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask:redirect()函数相关的知识,希望对你有一定的参考价值。

Windows 10家庭中文版,Python 3.6.4,Flask 1.0.2

 

重定向,就是在客户端提交请求后,本来是访问A页面,结果,后台给了B页面,当然,B页面中才有需要的信息。

 

在Flask中,使用redirect()函数实现重定向功能,函数原型如下:
flask.redirect(location, code=302, Response=None)

 

参数说明:

location是一个链接地址,可以使用url_for()函数得到,也可以是静态文件地址,测试了模板文件的地址,失败——看来模板还是挺安全的;

code可以取值为301、302、303、305、307,默认302,300、304不可以;

Response是一个响应类,默认是werkzeug.wrappers.Response,而flask.Response是werkzeug.wrappers.Response的子类——在写文前测试了好多次使用Response这个参数,现在才知道,这是一位类,不是一个对象,就保持默认吧——为什么要更改呢?怎样的更改是好的?;

 

下面是我的测试代码及页面:

 1 # flask.redirect(location, code=302, Response=None) test
 2 @app.route(\'/rd0\')
 3 def rd0():
 4     return redirect(\'the value in rd0\')
 5 
 6 @app.route(\'/rd1\')
 7 def rd1():
 8     return redirect(Response(\'the value in rd1\'))
 9 
10 @app.route(\'/rd11\')
11 def rd11():
12     return redirect(\'rdtest\', 302, Response=Response(\'the value in rd11\'))
13     #return redirect(\'rdtest\', 302, Response) # 更改为此行代码了才可以正常
14 
15 @app.route(\'/rd2\')
16 def rd2():
17     return redirect(url_for(\'hello\'))
18 
19 @app.route(\'/rd3\')
20 def rd3():
21     return redirect(\'/static/static1.html\')
22 
23 @app.route(\'/rd31\')
24 def rd31():
25     return redirect(\'/templates/tmpt1.html\')
26 
27 @app.route(\'/rd4\')
28 def rd4():
29     return redirect(url_for(\'hello\'), 307)

 

各个链接的测试页面:

/rd0

 

 

/rd1

 

/rd11

 

将rd11()的12行代码注释掉、取消地13行代码注释,测试页面如下:这次传了正确的参数,没有发生服务器错误了!

 

/rd2

 

 

/rd3

 

 

/rd31

 

 

/rd4

 

絮叨:

初步掌握这个重定向函数了,花了近一个半小时啊!中间遇到的问题又让自己进步了,开心!尤其是看英文文档的功力——看着文档都把参数类型搞错了!

以上是关于Flask:redirect()函数的主要内容,如果未能解决你的问题,请参考以下文章

Flask 中的 Render Redirect HttpResponse

Flask 学习-11.redirect() 重定向

Flask最强攻略 - 跟DragonFire学Flask - 第二篇 Flask 中的 Render Redirect HttpResponse

Flask中的 Render Redirect HttpResponse

Flask post / redirect / get模式无法从错误中恢复

flask 钩子函数