基于子域路由的 Flask 应用程序 [英] Flask app that routes based on subdomain
问题描述
我希望将我的顶级域作为对应于我网站不同部分的各种子域的门户.example.com
应该路由到 welcome.html
模板.eggs.example.com
应该路由到站点的eggs"子部分或应用程序.我将如何在 Flask 中实现这一目标?
I want to have my top-level domain as a portal for various subdomains that correspond to different sections of my site. example.com
should route to a welcome.html
template. eggs.example.com
should route to an "eggs" subsection or application of the site. How would I achieve this in Flask?
推荐答案
@app.route()
使用 subdomain
参数来指定路由匹配的子域.Blueprint
也需要一个 subdomain
参数,用于为蓝图中的所有路由设置子域匹配.
@app.route()
takes a subdomain
argument to specify what subdomain the route is matched on. Blueprint
also takes a subdomain
argument to set subdomain matching for all routes in a blueprint.
您必须将 app.config['SERVER_NAME']
设置为基本域,以便 Flask 知道要匹配的内容.您还需要指定端口,除非您的应用在端口 80 或 443 上运行(即在生产中).
You must set app.config['SERVER_NAME']
to the base domain so Flask knows what to match against. You will also need to specify the port, unless your app is running on port 80 or 443 (i.e in production).
从 Flask 1.0 开始,您还必须在创建应用对象时设置 subdomain_matching=True
.
As of Flask 1.0 you must also set subdomain_matching=True
when creating the app object.
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
),以便它知道如何路由子域,因为域实际上并不本地存在.
When running locally, you'll need to edit your computer's hosts file (/etc/hosts
on Unix) so that it will know how to route the subdomains, since the domains don't actually exist locally.
127.0.0.1 localhost example.com eggs.example.com ham.example.com
记得还是在浏览器中指定端口,http://example.com:5000
、http://eggs.example.com:5000
等.
Remember to still specify the port in the browser, http://example.com:5000
, http://eggs.example.com:5000
, etc.
同样,在部署到生产环境时,您需要配置 DNS,以便子域路由到与基本名称相同的主机,并配置网络服务器以将所有这些名称路由到应用程序.
Similarly, when deploying to production, you'll need to configure DNS so that the subdomains route to the same host as the base name, and configure the web server to route all those names to the app.
请记住,所有 Flask 路由实际上都是 werkzeug.routing 的实例.规则
.咨询 Werkzeug 的 Rule
文档将显示你有很多路由可以做的事情,但 Flask 的文档掩盖了(因为 Werkzeug 已经很好地记录了它).
Remember, all Flask routes are really instances of werkzeug.routing.Rule
. Consulting Werkzeug's documentation for Rule
will show you quite a few things that routes can do that Flask's documentation glosses over (since it is already well documented by Werkzeug).
这篇关于基于子域路由的 Flask 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!