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

 

絮叨:

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

posted @ 2018-05-20 12:31  快乐的凡人721  阅读(18499)  评论(0编辑  收藏  举报