【问题标题】:Tastypie - Counting failed and succeeded requestsTastypie - 计算失败和成功的请求
【发布时间】:2015-08-27 17:23:34
【问题描述】:

假设我有以下资源(来自美味派食谱http://django-tastypie.readthedocs.org/en/latest/cookbook.html#creating-per-user-resources 的示例):

class EnvironmentResource(ModelResource):
    class Meta:
        queryset = Environment.objects.all()
        resource_name = 'environment'
        list_allowed_methods = ['get', 'post']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()
        # maybe even some validation
        validation = FormValidation(form_class=forms.EnvironmentResourceForm)

    def obj_create(self, bundle, **kwargs):
       return super(EnvironmentResource, self).obj_create(bundle, user=bundle.request.user)

现在我想使用 statsd 客户端 (https://github.com/jsocol/pystatsd) 来计算 http 状态代码的出现次数(或者只是分别计算 2XX 和 4XX/5XX)。但我不知道我应该把我的代码放在哪里,statsd.incr('success')statsd.incr('failure')。你有什么建议吗?

或者,也许您知道计算 http 状态码的其他方法? (我不想分析访问日志)。

提前致谢!

编辑:

也许我应该定义一个新的中间件(像这样:https://docs.djangoproject.com/en/1.8/_modules/django/contrib/messages/middleware/),它将作为最后一个解决。计数器将在process_response 方法中增加。

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    您可以覆盖dispatch() 方法。比如:

    def dispatch(self, request_type, request, **kwargs):
        # do something with request_type and request.status_code
        return super(EnvironmentResource, self).dispatch(self, request_type, request, **kwargs):
    

    【讨论】:

    • 谢谢,它会工作的 :) 但是,中间件可以处理更广泛的请求。事实上,如果在 django 中间件的顶部声明了一个中间件,它也会处理被其他中间件拒绝的消息(例如授权中间件)。
    • 其实我认为授权是在派发后处理的,但我可能错了。您也可以使用中间件来解决它。我猜你可以使用request.status_coderequest.META['REQUEST_TYPE']。您还可以过滤掉不属于 API 的 url
    猜你喜欢
    • 2020-08-28
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多