如何在Flask after_request中访问请求上下文?

时间:2019-10-18 06:54:09

标签: python flask

因此,有3个概念:

  • 应用上下文-存储在g
  • 会话上下文-存储在session中(存储请求中的数据,可能使用cookie)
  • 请求上下文-???

在Flask的文档中找不到。

我还查看了指​​南:https://pythonise.com/feed/flask/python-before-after-request-他们似乎将请求上下文与会话上下文混淆了。

我的代码(其模式):

def handle_path1(event, request_context):
    return gen_response(event, request_context)

app = Flask(__name__)
app.add_url_rule('/path1', '/path1', handle_path1)

@app.after_request
def after_request_response_audit(response):
    request_context = ???SOMEHOW_GET_REQUEST_CONTEXT???()
    logging.info('%s %s' % (
        request_context['response_measure1'], 
        request_context['response_measure2']
    ))

@app.after_request
def after_request_response_measure2(response):
    request_context = ???SOMEHOW_GET_REQUEST_CONTEXT???()
    request_context['response_measure2'] = measure_response2(response)

@app.after_request
def after_request_response_measure1(response):
    request_context = ???SOMEHOW_GET_REQUEST_CONTEXT???()
    request_context['response_measure1'] = measure_response1(response)

问题是如何做???SOMEHOW_GET_REQUEST_CONTEXT???()

1 个答案:

答案 0 :(得分:0)

试试看!这是线程安全的

from flask import request
@app.after_request
def after_request_response_measure1(response):
    request_context = SOMEHOW_GET_REQUEST_CONTEXT(request)
    request_context['response_measure1'] = measure_response1(response)