基于子域路由的 Flask 应用
我希望将我的顶级域作为与我网站的不同部分相对应的各种子域的门户。 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@app.route()
需要subdomain
参数指定路由匹配的子域。Blueprint
还需要一个子域< /code> 参数为蓝图中的所有路由设置子域匹配。
您必须将
app.config['SERVER_NAME']
设置为基本域,以便 Flask 知道要匹配的内容。您还需要指定端口,除非您的应用程序在端口 80 或 443 上运行(即在生产中)。从 Flask 1.0 开始,您还必须在创建应用程序对象时设置
subdomain_matching=True
。在本地运行时,您需要编辑计算机的主机文件(Unix 上的
/etc/hosts
),以便它知道如何路由子域,因为域实际上并不存在于本地。请记住仍然在浏览器中指定端口,
http://example.com:5000
、http://eggs.example.com:5000
等。同样,部署到生产环境时,您需要配置 DNS,以便子域路由到与基本名称相同的主机,并配置 Web 服务器将所有这些名称路由到应用程序。
请记住,所有 Flask 路由实际上都是
werkzeug.routing.Rule< 的实例/代码>
。咨询 Werkzeug 的
Rule
文档将显示路由可以做的很多事情 Flask 的文档都掩盖了(因为 Werkzeug 已经详细记录了它)。@app.route()
takes asubdomain
argument to specify what subdomain the route is matched on.Blueprint
also takes asubdomain
argument to set subdomain matching for all routes in a blueprint.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).As of Flask 1.0 you must also set
subdomain_matching=True
when creating the app object.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.Remember to still specify the port in the browser,
http://example.com:5000
,http://eggs.example.com:5000
, etc.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.
Remember, all Flask routes are really instances of
werkzeug.routing.Rule
. Consulting Werkzeug's documentation forRule
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).