码迷,mamicode.com
首页 > 其他好文 > 详细

Flask:redirect()函数

时间:2018-05-20 14:11:54      阅读:409      评论:0      收藏:0      [点我收藏+]

标签:test   app   多次   one   参数   现在   nbsp   服务器错误   _for   

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()函数

标签:test   app   多次   one   参数   现在   nbsp   服务器错误   _for   

原文地址:https://www.cnblogs.com/luo630/p/9063105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!