如何在Flask应用程序中创建动态子域
问题内容:
我正在尝试在Flask应用程序中设置变量路由处理,例如此答案中所述:Web应用程序中的动态子域处理(Flask)
但是,我希望能够在某些子域被变量路由捕获之前对其进行识别,因此我可以使用flask-restful
api扩展(RESTful路由)。
例如,我尝试了以下方法:
@app.route('/', subdomain="<user>", defaults={'path':''})
@app.route('/<path:path>', subdomain="<user>")
def user_profile(user,path):
pass
class Api(restful.Resource):
def get(self):
#Do Api things.
api.add_resource(Api, '/v1', subdomain="api")
当我对此进行测试时,所有URL都会进入变量route
handler并调用user_prof()
。我尝试将api路由放在首位,将标准@app.route
规则放在第二位,反之亦然,但没有任何变化。
我是否缺少其他参数,还是需要深入研究Flask才能做到这一点?
更新:
我尝试匹配的网址格式如下:
user1.mysite.com -> handled by user_profile()
user2.mysite.com -> handled by user_profile()
any_future_string.mysite.com -> handled by user_profile()
api.mysite.com/v1 -> handled by Api class
其他情况包括:
www.mysite.com -> handled by index_display()
mysite.com -> handled by index_display()
问题答案:
@app.before_request
def before_request():
if 'api' == request.host[:-len(app.config['SERVER_NAME'])].rstrip('.'):
redirect(url_for('api'))
@app.route('/', defaults={'path': ''}, subdomain='api')
@app.route('/<path:path>', subdomain='api')
def api(path):
return "hello"
这应该工作。如果需要,可以将您的api版本添加到路径中,或者可以由您的API类处理。