基于子域进行路由的Flask应用 [英] Flask app that routes based on subdomain
问题描述
我希望将我的顶级域作为与我网站的不同部分相对应的各种子域的门户. example.com
应该路由到welcome.html
模板. eggs.example.com
应该路由到该站点的鸡蛋"小节或应用程序.我将如何在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,以使子域与基本名称路由到同一主机,并配置Web服务器以将所有这些名称路由到应用程序.
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.Rule
的实例一个>.咨询 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屋!