如何在Flask中使用子域名?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'This is the main domain.'
@app.route('/', subdomain='<subdomain>')
def subdomain(subdomain):
return f'This is the subdomain: {subdomain}'
if __name__ == '__main__':
app.run(debug=True)
我在本地运行这个程序,但访问 localhost:5000 时显示的是主页面,而访问 sub.localhost:5000 时也只显示主页面,而不是子页面。为了解决这个问题,我在 hosts 文件里加了这一行:
127.0.0.1 sub.localhost
可是这样还是不行,访问 sub.localhost:5000 还是显示主页面。我还尝试了像 render 这样的托管服务,但也出现了错误,使用 ngrok 从本地创建隧道时也出错。我该怎么才能让子域名正常工作呢?
所以,我想知道如何在本地让它工作,以及如何使用像 ngrok 这样的隧道服务和像 render 这样的托管服务。
1 个回答
0
你需要先设置 SERVER_NAME
这个变量。
在正确设置好你的 website_url
之后,试试这个:
app = Flask(__name__)
website_url = 'example.com:8000'
app.config['SERVER_NAME'] = website_url
@app.route('/')
def index():
return 'This is the main domain.'
@app.route('/', subdomain='<subdomain>')
def subdomain(subdomain):
return f'This is the subdomain: {subdomain}'
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8000)
更新:
如何进行测试:
假设我们使用的域名是 "example.com",子域名是 "subdomain.example.com",在你的 hosts
文件中定义这两个主机:
127.0.0.1 example.com subdomain.example.com
然后可以请求: