2

我正在尝试在 Flask 应用程序中设置可变路由处理,例如此答案中所述:Web App (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 都会转到变量路由处理程序并调用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()
4

2 回答 2

2
@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 版本添加到路径中。

于 2013-05-30T15:27:41.200 回答
0

为了简单起见,我将应用程序的逻辑重新设计为两个不同的部分。

这样 Flask 应用程序只处理 API 端点逻辑。用户配置文件逻辑由另一个应用程序处理。我现在可以向 API 应用程序添加多个资源,而不必担心破坏路由。

于 2013-10-09T11:43:46.817 回答