问题:在Flask中重定向到URL

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

这是我的代码:

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)

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

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)

回答 0

您必须返回重定向:

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)

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

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=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).


回答 1

#!/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)

看一下文档中的示例

#!/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.


回答 2

Flask API文档(v。0.10):

烧瓶。重定向locationcode=302Response=None

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

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

参数:

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

From the Flask API Documentation (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.

回答 3

我认为这个问题值得更新:只需看看其他方法并进行比较即可。

这是在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)

如需其他官方参考,请点击此处

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):

#!/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.


回答 4

flask.redirect(location, code=302)

可以在这里找到文档。

flask.redirect(location, code=302)

Docs can be found here.


回答 5

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)

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

redirect方法默认情况下采用代码302。此处是http状态代码的列表。

Flask includes the redirect function for redirecting to any url. Futhermore, you can abort a request early with an error code with 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 redirect method takes by default the code 302. A list for http status codes here.


回答 6

为此,您可以简单地使用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()

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

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

from flask import Flask, redirect

app = Flask(__name__)

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

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

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


回答 7

您可以这样使用:

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)

这是此代码的引用链接。

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("https://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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。