如何在Flask应用程序中创建动态子域 [英] How to create dynamic subdomains in a Flask application

查看:79
本文介绍了如何在Flask应用程序中创建动态子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Flask应用程序中设置变量路由处理,例如此答案中所述: Web应用程序中的动态子域处理(Flask)

I am trying to setup variable route handling in a Flask application such as described in this answer: Dynamic Subdomain Handling in a Web App (Flask)

但是,我希望能够在被捕获之前识别出某些子域通过变量路由,这样我就可以使用flask-restful api扩展名(使用RESTful路由)。

However, I want to be able to recognize certain subdomains BEFORE they are caught by the variable route so I can use the flask-restful api extension (Routing with RESTful).

例如,我尝试了以下操作:

For example, I have tried the following:

@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 规则放在第二位,反之亦然,但是没有任何变化。

When I test this, all of URLs go to the variable route handler and call user_prof(). I tried putting the api route first and the standard @app.route rule second and vice versa but there was no change.

我是否还缺少其他参数或需要深入研究Flask才能做到这一点?

Am I missing some other parameter or need to go deeper in Flask to make this happen?

我要匹配的网址格式如下:

The URL patterns I am trying to match are like this:

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

This should work. Add your api version to the path if needed or that could be processed by your API class.

这篇关于如何在Flask应用程序中创建动态子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆