Domain routing in Flask

半城伤御伤魂 提交于 2019-12-06 13:01:43

问题


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..


回答1:


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.



来源:https://stackoverflow.com/questions/18511906/domain-routing-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!