Django Cache Distinguish Desktop Mobile | Django缓存区分桌面版和手机端

Django Cache Distinguish Desktop Mobile

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

Django-Mobile-Detector

Mobile Detector 请参考: https://github.com/Botir/Django-Mobile-Detector

使用Vary Header

Vary Header介绍: https://docs.djangoproject.com/zh-hans/4.0/topics/cache/#using-vary-headers

实现

为了能够让Django cache来区分desktop, mobile, 我们可以使用vary header 来区分当前请求是desktop模式,还是mobile模式。

  1. 首页添加mobile-detector middleware在最上面,检测当前请求模式
  2. 添加自定义middleware(HeaderMiddleware),添加is_mobile Header.
  3. 修改action, 使用vary_on_headers("is_mobile") 装饰器

1. Middleware 配置


MIDDLEWARE = [
    'mobiledetect.middleware.DetectMiddleware',
    'xxxx.middleware.HeaderMiddleware',
    'django.middleware.cache.UpdateCacheMiddleware',
    ....
    'django.middleware.cache.FetchFromCacheMiddleware'
]

2. HeaderMiddleware

添加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

3. 使用vary_on_headers装饰器

@vary_on_headers("is_mobile")
def SortBy(request, method):
     ....

总结

测试效果:Django cache会分别针对 desktop和mobile模式进行缓存,解决了不同模式显示错误视图的问题。

评论

还没有人评论,抢个沙发吧...

Viagle Blog

欢迎来到我的个人博客网站