如何确定“响应后"中的端点.处理程序? [英] How to determine endpoint in "after response" handler?

查看:63
本文介绍了如何确定“响应后"中的端点.处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask开发REST API.处理响应后,某些端点需要执行其他职责,但是我想避免使用外部处理队列或线程.一个非常方便的解决方案似乎是使用WSGI Middleware和ClosingIterator,如此答案所述.但是,每个点的处理程序都需要知道哪个端点处理了该请求,以便执行其验尸职责.

I am developing a REST API in Flask. Some endpoints need to perform additional duties after the response is handled, but I would like to avoid using external processing queue or threads. One very convenient solution seems to be with WSGI Middleware and ClosingIterator, as outlined in this answer. However the handler of each point needs to know which endpoint handled the request, in order to perform their post-mortem duties.

一个想法是这样装饰我的端点:

One idea is to decorate my endpoints like this:

@app.route('/api/status/info', methods=['GET'])
def get_status_info():
    @app.after_this_response('get_status_info')
    def say_hi():
        print('hi, unknown endpoint!')

    return 'ok', 200

我想打印 get_status_info ,而不是未知端点.这可能吗?

Instead of unknown endpoint I would like to print get_status_info. Is this possible?

更好的是,如果我编写一个通用的 @ app.after_response 处理程序(如另一个答案由同一位作者),我可以确定其中使用了哪个端点来处理请求吗?

Even better, if I write a generic @app.after_response handler (as in another answer by the same author), can I determine in it which endpoint was used for handling the request?

编辑:尝试使用 flask.request.url_rule.endpoint 会引发异常:

Trying to use flask.request.url_rule.endpoint throws an exception:

RuntimeError: Working outside of request context.

推荐答案

要在 @ app.after_this_response 中获取原始请求的端点,可以执行以下操作:

To get the endpoint of the original request inside @app.after_this_response you can do the following:

@app.route('/api/status/info', methods=['GET'])
def get_status_info():

    @app.after_this_response('get_status_info')
    @flask.copy_current_request_context
    def say_hi():
        print('hi, %s', % (flask.request.url_rule.endpoint))

    return 'ok', 200

flask.request.url_rule.endpoint 为您提供了端点的名称,但是默认情况下,当它传递给 say_hi 函数时,您会丢失请求上下文,这就是为什么需要 @copy_current_request_context 装饰器传递上下文.对该装饰器的引用在这里: http://flask.pocoo.org/docs/1.0/api/#flask.copy_current_request_context

flask.request.url_rule.endpoint gives you the endpoint's name, however you lose the request context by default when it passes onto the say_hi function, which is why you need the @copy_current_request_context decorator to pass on the context. Reference to that decorator is here: http://flask.pocoo.org/docs/1.0/api/#flask.copy_current_request_context

这篇关于如何确定“响应后"中的端点.处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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