简体   繁体   English

如何为特定视图创建Flask before_request视图?

[英]How create Flask before_request view for specific views?

I'm building a system using Flask which contains both a website and an api for an app. 我正在使用Flask构建一个系统,它包含一个应用程序的网站和api。 I've got a before_request defined for the webviews as follows: 我为webview定义了一个before_request,如下所示:

@app.before_request
def before_request():
    g.user = current_user
    # And I do some more stuff here..

I've got my views in a folder based structure like this: 我在基于文件夹的结构中得到了我的观点,如下所示:

views (folder)
---------------
  - __init__.py
  - apiviews.py
  - webviews.py

Because I'm using a token based login system for the api I now want to define a different before_request for all the apiviews. 因为我正在为api使用基于令牌的登录系统,我现在想要为所有apiviews定义不同的before_request。 Is there a way that I can do this? 有没有办法可以做到这一点? Maybe I need to define a decorator or something? 也许我需要定义装饰器或什么? All tips are welcome! 欢迎所有提示!

You cannot use a before_request hook for specific views, not in the same app. 您不能对特定视图使用before_request挂钩,而不能在同一个应用中使用。

Your options are to: 您的选择是:

  • Use a separate Blueprint for your API and website; 为您的API和网站使用单独的Blueprint ; you can register a before_request per blueprint and it'll be applied to the views for that blueprint only. 可以为每个蓝图注册一个before_request ,它将仅应用于该蓝图的视图。
  • Use per-view decorators rather than before_request . 使用每视图装饰器而不是before_request
  • filter on the request path in the before_request handler; 过滤before_request处理程序中的请求路径; if request.path.startswith(...) style testing. if request.path.startswith(...)样式测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM