Django Cache 默认并不区分Desktop和Mobile, 但是如果Desktop 视图和mobile视图不同,这时Django Cache就会有问题,
如果某个页面先被desktop模式访问之后,页面会被缓存,但手机端再访问这个页面时,发布页面已经被缓存,所以直接返回,
但是被缓存的内容是Desktop模式,在手机端显示会有些奇怪。
https://docs.djangoproject.com/zh-hans/4.0/topics/cache/
https://docs.djangoproject.com/zh-hans/4.0/topics/cache/#using-vary-headers
https://github.com/django/django/blob/main/django/utils/cache.py
https://github.com/Botir/Django-Mobile-Detector
Mobile Detector 请参考: https://github.com/Botir/Django-Mobile-Detector
Vary Header介绍: https://docs.djangoproject.com/zh-hans/4.0/topics/cache/#using-vary-headers
为了能够让Django cache来区分desktop, mobile, 我们可以使用vary header 来区分当前请求是desktop模式,还是mobile模式。
MIDDLEWARE = [
'mobiledetect.middleware.DetectMiddleware',
'xxxx.middleware.HeaderMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
....
'django.middleware.cache.FetchFromCacheMiddleware'
]
添加is_mobile Header, 必须大写并以HTTP_开头,详细请查看django源码
class HeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
# Code to be executed for each request/response after
# the view is called.
# vary header is UPPER and start with HTTP_
# https://github.com/django/django/blob/36cd4259438f98e74e472e232307a1909f164e56/django/utils/cache.py#L427
request.META["HTTP_IS_MOBILE"] = str(request.device["is_mobile"]) if request.device and "is_mobile" in request.device else "None"
response = self.get_response(request)
return response
@vary_on_headers("is_mobile")
def SortBy(request, method):
....
测试效果:Django cache会分别针对 desktop和mobile模式进行缓存,解决了不同模式显示错误视图的问题。
还没有人评论,抢个沙发吧...