【问题标题】:How to wrap custom endpoints in Django Tastypie?如何在 Django Tastypie 中包装自定义端点?
【发布时间】:2021-12-27 10:37:03
【问题描述】:

我想为某个资源添加一个调度方法,这样我就可以在它上面使用一个包装装饰器。 问题是它只适用于 CRUD 操作,不会进入“原始”端点上的调度方法:

class SomeResource(SomeBaseResource):
    class Meta(...): ...
    
    def get_something_extra(self, request, **kwargs):
        ...

    def patch_detail(self, request, **kwargs):
        ...

和基础资源:

class SomeBaseResource(ModelResource):
    class Meta(...): ...
    
    # the wrapper
    @decorator_to_wrap_all_methods_with(...)
    def dispatch(self, request_type, request, **kwargs):
         logger.info('Enter')
         response = super(SomeBaseResource, self).dispatch(request_type, request, **kwargs)
         logger.info('Exit')
         return response

所以当我使用补丁请求时,它按预期工作,但不会调用 get_something_extra api。

如何将所有方法包装在资源中?

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    一种解决方法是添加中间件:

    MIDDLEWARE = (
    'my.basic.BaseMiddleware',
    ...
    )
    
    class BaseMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        @decorator_to_wrap_all_methods_with(...)
        def __call__(self, request):
            response = self.get_response(request)
            return response
    

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 1970-01-01
      • 2013-04-18
      • 2012-05-06
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多