Flask中的域路由 [英] Domain routing in Flask
问题描述
我想将用户从test1.domain.com重定向到test2.domain.com。我尝试了url_map中的host_matching以及url_rule中的host。它似乎没有工作,显示404错误。例如,访问localhost.com:5000应该去'test.localhost.com:5000'。
来自瓶子导入Flask,url_for,重定向
app = Flask(__ name__)
app.url_map.host_matching = True
@ app.route(/)
def hello1():
#returnHello @ example1!
return redirect(url_for('hello2'))
@ app.route(/ test /,host =test.localhost.com:5000)
def hello2():
返回Hello @ test!
if __name__ ==__main__:
app.run()
有可能吗?有没有人试过?
在此先感谢您。
代码中的任何内容都不会重定向来自 localhost .com
到 test.localhost.com
。如果您希望发生这种情况,您需要使用http重定向来请求 localhost.com
。 当您将host_matching设置为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 ))#永久重定向你可以做重定向(url_for(hello2),301)
@ app.route(/,host =test.localhost.com:5000)
def hello2():
returnHello @ test!
if __name__ ==__main__:
app.run()
请注意,您还需要将 localhost.com
和 test.localhost.com
映射到您的hosts文件中包含127.0.0.1。
I wanted to redirect users from test1.domain.com to test2.domain.com. I tried 'host_matching' in url_map along with 'host' in url_rule. It doesn't seem to work, shows 404 error.For example, on visiting 'localhost.com:5000' it should go to '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()
Is it possible? Has anyone tried? Thanks in advance..
Nothing in your code is redirecting a request from localhost.com
to test.localhost.com
. You would need to respond with an http redirect to requests for localhost.com
if you wanted this to happen. 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()
Bear in mind that you will also need to map localhost.com
and test.localhost.com
to 127.0.0.1 in your hosts file.
这篇关于Flask中的域路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!