如何在 Django Tastypie 中包装自定义端点?
How to wrap custom endpoints in Django Tastypie?
我想向某些资源添加一个调度方法,以便我可以在其上使用包装装饰器。
问题是它只适用于 CRUD 操作,不会进入 'original' 端点上的调度方法:
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.
如何将所有方法包装在资源中?
解决方法是添加中间件:
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
我想向某些资源添加一个调度方法,以便我可以在其上使用包装装饰器。 问题是它只适用于 CRUD 操作,不会进入 'original' 端点上的调度方法:
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.
如何将所有方法包装在资源中?
解决方法是添加中间件:
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