【问题标题】:Flask app that routes based on subdomain基于子域路由的 Flask 应用程序
【发布时间】:2011-11-22 16:26:08
【问题描述】:

我想让我的顶级域作为对应于我网站不同部分的各种子域的门户。 example.com 应该路由到 welcome.html 模板。 eggs.example.com 应该路由到站点的“eggs”子部分或应用程序。我将如何在 Flask 中实现这一点?

【问题讨论】:

    标签: python google-app-engine flask url-routing werkzeug


    【解决方案1】:

    @app.route() 采用subdomain 参数来指定路由匹配的子域。 Blueprint 还采用 subdomain 参数来设置蓝图中所有路由的子域匹配。

    您必须将app.config['SERVER_NAME'] 设置为基本域,以便 Flask 知道要匹配什么。您还需要指定端口,除非您的应用在端口 80 或 443 上运行(即在生产中)。

    从 Flask 1.0 开始,您还必须在创建应用对象时设置 subdomain_matching=True

    from flask import Flask
    
    app = Flask(__name__, subdomain_matching=True)
    app.config['SERVER_NAME'] = "example.com:5000"
    
    @app.route("/")
    def index():
        return "example.com"
    
    @app.route("/", subdomain="eggs")
    def egg_index():
        return "eggs.example.com"
    
    ham = Blueprint("ham", __name__, subdomain="ham")
    
    @ham.route("/")
    def index():
        return "ham.example.com"
    
    app.register_blueprint(ham)
    

    在本地运行时,您需要编辑计算机的主机文件(Unix 上为/etc/hosts),以便它知道如何路由子域,因为域实际上并不存在于本地。

    127.0.0.1 localhost example.com eggs.example.com ham.example.com
    

    记得还是要在浏览器中指定端口,http://example.com:5000http://eggs.example.com:5000

    同样,在部署到生产环境时,您需要配置 DNS 以便子域路由到与基本名称相同的主机,并配置 Web 服务器以将所有这些名称路由到应用程序。

    请记住,所有 Flask 路由实际上都是 werkzeug.routing.Rule 的实例。咨询Werkzeug's documentation for Rule 将向您展示路由可以做的很多事情,Flask 的文档掩盖了(因为 Werkzeug 已经很好地记录了它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2021-12-11
      • 2015-03-10
      • 2019-07-14
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多