python - 如何在 Flask 应用程序中创建动态子域

标签 python heroku routes flask url-routing

我正在尝试在 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/

相关文章:

python - 添加用户的 bash 脚本

python - Numba 比 numpy 慢 3 倍

ruby-on-rails - Rails 4 : EOFError: end of file reached following any email in DEVELOPMENT only

docker - 能够将我的 Docker 容器放到 Heroku 上,但我不知道如何访问端点

node.js - “超出最大调用堆栈大小”VueJS 路由

ruby-on-rails - Rails 路由上的命名空间和资源

c# - 在 .NET 7 中使用具有最少 API 的 MapGroup

python - 如何创建脚本以在我的 ARM conda 和 x86 conda 之间切换?

python - 试图将一个类的实例传递给另一个文件

swift - 尝试保存 PFUser 后解析已销毁的 session