How do I run an action for all requests in Flask?

后端 未结 1 1778
甜味超标
甜味超标 2021-02-05 06:22

I have some code I want to run for every request that comes into Flask-- specifically adding some analytics information. I know I could do this with a decorator, but I\'d rather

1条回答
  •  再見小時候
    2021-02-05 06:50

    Flask has dedicated hooks called before and after requests. Surprisingly, they are called:

    • Flask.before_request()
    • Flask.after_request()

    Both are decorators:

    @app.before_request
    def do_something_whenever_a_request_comes_in():
        # request is available
    
    @app.after_request
    def do_something_whenever_a_request_has_been_handled(response):
        # we have a response to manipulate, always return one
        return response
    

    0 讨论(0)
提交回复
热议问题