【问题标题】:Domain routing in FlaskFlask 中的域路由
【发布时间】:2013-09-01 22:38:48
【问题描述】:

我想将用户从 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()

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

【问题讨论】:

标签: python flask werkzeug


【解决方案1】:

您的代码中没有将请求从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()

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

【讨论】:

  • 是的..我尝试了重定向。更新了我的问题。您的解决方案也不起作用。你试过了吗?子域路由正常工作,但不是这个。
  • 刚刚测试并更新了它,它现在可以工作了。您还需要指定完整的主机,包括端口号。并且重定向需要包含架构 http:// 才能起作用。
  • 它只会重定向到“test.localhost.com:5000”,这很正常吧?我们只是重定向到另一个站点。
  • 好的。我将 'return redirect("test.localhost.com:5000")' 替换为 redirect(url_for('hello2')) 它工作正常。我错过的一件事是第一条路线中的 'host' 。谢谢。
  • 在您的问题中,您说“在访问 'localhost.com:5000' 时,它应该转到 'test.localhost.com:5000'。”为此,您向浏览器发送重定向。然后它发出另一个请求。您还期望它如何工作?
猜你喜欢
  • 2012-04-16
  • 2011-11-22
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 2017-09-02
  • 2018-05-07
  • 2015-08-17
  • 1970-01-01
相关资源
最近更新 更多