flask之重定向
重定向 redirect():
使用redirect(),需要从flask中导入redirect。
from flask import redirct
redirect()方法源码:
def redirect(location, code=302, Response=None):
"""Returns a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are
301, 302, 303, 305, 307, and 308. 300 is not supported because
it's not a real redirect and 304 because it's the answer for a
request with a request with defined If-Modified-Since headers.
.. versionadded:: 0.6
The location can now be a unicode string that is encoded using
the :func:`iri_to_uri` function.
.. versionadded:: 0.10
The class used for the Response object can now be passed in.
:param location: the location the response should redirect to.
:param code: the redirect status code. defaults to 302.
:param class Response: a Response class to use when instantiating a
response. The default is :class:`werkzeug.wrappers.Response` if
unspecified.
"""
if Response is None:
from .wrappers import Response
display_location = escape(location)
if isinstance(location, text_type):
# Safe conversion is necessary here as we might redirect
# to a broken URI scheme (for instance itms-services).
from .urls import iri_to_uri
location = iri_to_uri(location, safe_conversion=True)
response = Response(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
"<title>Redirecting...</title>\n"
"<h1>Redirecting...</h1>\n"
"<p>You should be redirected automatically to target URL: "
'<a href="%s">%s</a>. If not click the link.'
% (escape(location), display_location),
code,
mimetype="text/html",
)
response.headers["Location"] = location
return response
redirect()方法的参数:
1. location:重定向的地址
2. code:默认302,支持301,302, 303, 305,307,308
3. Response:返回对象,默认为None
示例:
from flask import Flask, request, redirect, url_for, render_template import settings app = Flask(__name__) app.config.from_object(settings) @app.route('/test') def test(): return redirect(url_for('login'), 301) @app.route('/login', endpoint='login') def test1(): return 'this is login page' if __name__ == '__main__': app.run()
若访问1270.0.1:5000/test时,则会跳转至127.0.0.1:5000/login页面
反向构建地址 url_for():
参数:
endpoint:端点
**values:动态关键字参数
浙公网安备 33010602011771号