Python 在 Flask 中重定向到 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14343812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:08:19  来源:igfitidea点击:

Redirecting to URL in Flask

pythonredirectflask

提问by iJade

I'm new to Python and Flask and I'm trying to do the equivalent of Response.redirectas in C# - ie: redirect to a specific URL - how do I go about this?

我是 Python 和 Flask 的新手,我正在尝试执行与Response.redirectC# 中相同的操作 - 即:重定向到特定 URL - 我该怎么做?

Here is my code:

这是我的代码:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

采纳答案by Xavier Combelle

You have to return a redirect:

您必须返回重定向:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

See the documentation on flask docs.The default value for code is 302 so code=302can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

请参阅烧瓶文档上的文档。code 的默认值是 302,因此code=302可以省略或替换为其他重定向代码(301、302、303、305 和 307 中的一个)。

回答by ford

From the Flask API Documentation(v. 0.10):

来自Flask API 文档(v. 0.10):

flask.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, and 307. 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.

New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.

Parameters:

  • location– the location the response should redirect to.
  • code– the redirect status code. defaults to 302.
  • Response(class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.

烧瓶。重定向( location, code=302, Response=None)

返回一个响应对象(一个 WSGI 应用程序),如果被调用,它将客户端重定向到目标位置。支持的代码是 301、302、303、305 和 307。不支持 300,因为它不是真正的重定向,而 304 是因为它是对具有已定义 If-Modified-Since 标头的请求的响应。

0.6 版中的新功能:位置现在可以是使用 iri_to_uri() 函数编码的 unicode 字符串。

参数:

  • location– 响应应该重定向到的位置。
  • code– 重定向状态代码。默认为 302。
  • Response(class) – 实例化响应时使用的响应类。如果未指定,则默认为 werkzeug.wrappers.Response。

回答by der_fenix

flask.redirect(location, code=302)

Docs can be found here.

文档可以在这里找到。

回答by soerface

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('foo'))

@app.route('/foo')
def foo():
    return 'Hello Foo!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Take a look at the example in the documentation.

查看文档中的示例

回答by ivanleoncz

I believe that this question deserves an updated: just take a look on the other approaches and make the comparisons.

我相信这个问题值得更新:看看其他方法并进行比较。

Here is how you do redirection (3xx) from one url to another in Flask (0.12.2):

以下是在 Flask (0.12.2) 中从一个 URL 重定向 (3xx) 到另一个 URL 的方法:

#!/usr/bin/env python

from flask import Flask, redirect

app = Flask(__name__)

@app.route("/")
def index():
    return redirect('/you_were_redirected')

@app.route("/you_were_redirected")
def redirected():
    return "You were redirected. Congrats :)!"

if __name__ == "__main__":
    app.run(host="0.0.0.0",port=8000,debug=True)

For other official references, here.

有关其他官方参考资料,请点击此处

回答by Manan Gouhari

For this you can simply use the redirectfunction that is included in flask

为此,您可以简单地使用redirect包含在flask

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("www.exampleURL.com", code = 302)

if __name__ == "__main__":
    app.run()

Another useful tip(as you're new to flask), is to add app.debug = Trueafter initializing the flask object as the debugger output helps a lot while figuring out what's wrong.

另一个有用的提示(因为您是flask 的新手)是app.debug = True在初始化flask 对象之后添加,因为调试器输出在找出问题时有很大帮助。

回答by yoelvis

Flask includes the redirectfunction for redirecting to any url. Futhermore, you can abort a request early with an error code with abort:

Flask 包括redirect重定向到任何 url的功能。此外,您可以使用以下错误代码提前中止请求abort

from flask import abort, Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('hello'))

@app.route('/hello'):
def world:
    abort(401)

By default a black and white error page is shown for each error code.

默认情况下,每个错误代码都会显示一个黑白错误页面。

The redirectmethod takes by default the code 302. A list for http status codes here.

redirect方法默认采用代码 302。http 状态代码列表在这里

回答by RAJAHMAD MULANI

You can use like this:

你可以这样使用:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
     # Redirect from here, replace your custom site url "www.google.com"
    return redirect("www.google.com", code=200)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Here is the referenced link to this code.

这是此代码的引用链接。