我正在尝试在 Flask 应用程序中设置可变路由处理,如本答案中所述:Dynamic Subdomain Handling in a Web App (Flask)
但是,我希望能够在某些子域被变量路由捕获之前识别它们,这样我就可以使用 Flask-restful api 扩展 ( Routing with 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 都会转到变量路由处理程序并调用 user_prof()
。我尝试将 api 路由放在第一位,然后将标准 @app.route
规则放在第二位,反之亦然,但没有任何变化。
我是否缺少其他一些参数或者需要深入 Flask 才能实现这一点?
更新:
我尝试匹配的 URL 模式如下:
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 版本添加到路径中。
关于python - 如何在 Flask 应用程序中创建动态子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16803176/