33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
"""
|
||
异步友好的 never_cache 类装饰器
|
||
================================
|
||
替代 `@method_decorator(never_cache, name='dispatch')`。
|
||
|
||
背景:@method_decorator 生成同步包装器,在 adrf 的 async dispatch 返回的协程上
|
||
调用 add_never_cache_headers 会抛 AttributeError('coroutine' object has no
|
||
attribute 'has_header')。本装饰器兼容同步/异步 dispatch,语义与 never_cache 一致。
|
||
|
||
用法(作为类装饰器):
|
||
@async_never_cache_dispatch
|
||
class WalletBalanceAPIView(APIView):
|
||
...
|
||
"""
|
||
import asyncio
|
||
|
||
from django.utils.cache import add_never_cache_headers
|
||
|
||
|
||
def async_never_cache_dispatch(cls):
|
||
orig_dispatch = cls.dispatch
|
||
|
||
async def dispatch(self, request, *args, **kwargs):
|
||
response = orig_dispatch(self, request, *args, **kwargs)
|
||
if asyncio.iscoroutine(response):
|
||
response = await response
|
||
if response is not None and hasattr(response, "has_header"):
|
||
add_never_cache_headers(response)
|
||
return response
|
||
|
||
cls.dispatch = dispatch
|
||
return cls
|