flask中的重定向redirect方法经常被用来跳转页面,那redirect在跳转页面的同时能不能传递咱们下一个页面须要的参数呢?html
带着这个问题我看了redirect()的源码,以下:python
1 def redirect(location, code=302, Response=None): 2 """Returns a response object (a WSGI application) that, if called, 3 redirects the client to the target location. Supported codes are 301, 4 302, 303, 305, and 307. 300 is not supported because it's not a real 5 redirect and 304 because it's the answer for a request with a request 6 with defined If-Modified-Since headers. 7 8 .. versionadded:: 0.6 9 The location can now be a unicode string that is encoded using 10 the :func:`iri_to_uri` function. 11 12 .. versionadded:: 0.10 13 The class used for the Response object can now be passed in. 14 15 :param location: the location the response should redirect to. 16 :param code: the redirect status code. defaults to 302. 17 :param class Response: a Response class to use when instantiating a 18 response. The default is :class:`werkzeug.wrappers.Response` if 19 unspecified. 20 """ 21 if Response is None: 22 from werkzeug.wrappers import Response 23 24 display_location = escape(location) 25 if isinstance(location, text_type): 26 # Safe conversion is necessary here as we might redirect 27 # to a broken URI scheme (for instance itms-services). 28 from werkzeug.urls import iri_to_uri 29 location = iri_to_uri(location, safe_conversion=True) 30 response = Response( 31 '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' 32 '<title>Redirecting...</title>\n' 33 '<h1>Redirecting...</h1>\n' 34 '<p>You should be redirected automatically to target URL: ' 35 '<a href="%s">%s</a>. If not click the link.' % 36 (escape(location), display_location), code, mimetype='text/html') 37 response.headers['Location'] = location 38 return response
源码的解释很清楚,redirect就是一个响应,它总共有三个参数,这三个参数都是用来实例化响应的.flask
第一个参数:location是响应应该重定向到的位置。第二个参数code是重定向状态代码,,最后一个参数是实例化响应时要使用的响应类.app
因此说redirect自己是不能像render_template那样来传递参数的.url
可是!!spa
若是你要传递的参数只是像string,int这样的数据,你能够用url_for来做为location参数,而url_for是能够作到传递这些简单数据的.code
redirect(url_for())传递参数的方法以下:htm
@app.route('/login/',methods=['GET','POST']) def user_login(): username = 'unsprint' return redirect(url_for('index',username=username)) #url_for在index的路由和username之间加一个?进行拼接,使得username成为一个可接受的参数
#经过路由接收参数 @app.route('/index/?<string:username>') #这里指定了接收的username的类型,若是不符合会报错, def index(username): #能够将string改为path, 这样username就会被当成路径来接收,也就是说username能够是任意可键入路由的值了
return username