在 Flask 中重定向到 URL [英] Redirecting to URL in Flask
本文介绍了在 Flask 中重定向到 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Python 和 Flask 的新手,我正在尝试执行与 C# 中的 Response.redirect
等效的操作 - 即:重定向到特定 URL - 我该如何处理?
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?
这是我的代码:
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)
推荐答案
你必须返回一个重定向:
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)
请参阅 有关flask 文档的文档. code 的默认值为 302 所以code=302
可以省略或替换为其他重定向代码(301、302、303、305 和 307 中的一个).
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).
这篇关于在 Flask 中重定向到 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文