flask的重定向(redirect)傳遞參數的方法

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
相關文章
相關標籤/搜索