我想做的是类似于回应。重定向作为在c# -即:重定向到一个特定的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)

当前回答

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

请查看文档中的示例。

其他回答

我认为这个问题值得更新。只要和其他方法比较一下。

以下是如何在Flask(0.12.2)中从一个url重定向到另一个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)

其他官方参考资料,请点击这里。

Flask包含用于重定向到任何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)

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

重定向方法默认接受代码302。http状态代码列表。

从Flask API文档(v. 2.0.x):

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.

flask.redirect(location, code=302)

文档可以在这里找到。

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

另一个有用的技巧(因为你是flask的新手)是在初始化flask对象后添加app.debug = True,因为调试器输出在找出错误时很有帮助。