gpt4 book ai didi

python - Flask 中的域路由

转载 作者:太空宇宙 更新时间:2023-11-03 18:50:20 25 4
gpt4 key购买 nike

我想将用户从 test1.domain.com 重定向到 test2.domain.com。我尝试了 url_map 中的“host_matching”以及 url_rule 中的“host”。它似乎不起作用,显示 404 错误。例如,在访问 'localhost.com:5000' 时,它应该转到 'test.localhost.com:5000'。

from flask import Flask, url_for, redirect
app = Flask(__name__)
app.url_map.host_matching = True

@app.route("/")
def hello1():
#return "Hello @ example1!"
return redirect(url_for('hello2'))

@app.route("/test/", host="test.localhost.com:5000")
def hello2():
return "Hello @ test!"

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

这可能吗?有人尝试过吗?提前致谢..

最佳答案

您的代码中没有任何内容将请求从 localhost.com 重定向到 test.localhost.com。如果您希望发生这种情况,您需要使用 http 重定向来响应 localhost.com 的请求。 You also need to specify the host for all routes when you set host_matching to true

from flask import Flask, redirect, url_for
app = Flask(__name__)
app.url_map.host_matching = True

@app.route("/", host="localhost.com:5000")
def hello1():
return redirect(url_for("hello2")) # for permanent redirect you can do redirect(url_for("hello2"), 301)

@app.route("/", host="test.localhost.com:5000")
def hello2():
return "Hello @ test!"

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

请记住,您还需要在主机文件中将 localhost.comtest.localhost.com 映射到 127.0.0.1。

关于python - Flask 中的域路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18511906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com