flask中的重定向redirect方法常常被用來跳轉頁面,那redirect在跳轉頁面的同時能不能傳遞我們下一個頁面需要的參數呢?
帶着這個問題我看了redirect()的源碼,如下:
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就是一個響應,它總共有三個參數,這三個參數都是用來實例化響應的.
第一個參數:location是響應應該重定向到的位置。第二個參數code是重定向狀態代碼,,最后一個參數是實例化響應時要使用的響應類.
所以說redirect本身是不能像render_template那樣來傳遞參數的.
但是!!
如果你要傳遞的參數只是像string,int這樣的數據,你可以用url_for來作為location參數,而url_for是可以做到傳遞這些簡單數據的.
redirect(url_for())傳遞參數的方法如下:
@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
