zoukankan      html  css  js  c++  java
  • django-redis缓存

    1.安装django依赖包 pip install djange-redis==4.8.0

    2.配置文件settings  需要开启redis服务 sudo service redis start,否则连接被拒

    # 缓存配置
    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache", 
            "LOCATION": "redis://127.0.0.1:6379/2", # or 127.0.0.1 
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
            }
        }
    }

    3.1页面缓存

    view:

    class CachePage(View):
        """ 缓存页面 """
        def get(self, request):
            print "只打印一次则使用缓存"
            return render(request, "logok.html")

    通过配置url调用缓存

    from django.views.decorators.cache import cache_page
    urlpatterns = [
        url(r'auth_cache_page/$', cache_page(60)(views.CachePage.as_view()), name='auth_cache_page'),
    ] # 设置过期时间60s 注意格式  执行到cache_page,有缓存则不执行view,直接调用缓存
      时间单位为秒, 60*60*24*7 一周时间

    3.2访问缓存

     view:

    from django.core.cache import cache

    class CacheVisit(View):
        """
        访问数据库缓存
        from django.core.cache import cache
        """
        def get(self, request):
            users = cache.get("users") # 没users则返回None
            if not users:
                users = User.objects.all()
                cache.set("users", users, 60) # 设置缓存key及过期时间
           # cache.add("users", users, 60) # 更新缓存或相当于set
           # cache.set_many({"a": 1, "b": 3}) # 设置多个缓存
           # cache.get_or_set("a", "默认值", 60) # 存在key a则获取a的值,不存在则设置key a,值为默认值
           # cache.delete("a") # 删除
           # cache.delete_many(["a", "b"]) # 删除多个缓存
           # cache.clear() # 清除所有缓存
    print "只打印一次则使用缓存" return render(request, "users.html", locals())

    html

    <body>
    {% for user in users %}
        {{ user.username }}<br>
    {% endfor %}
    </body>
  • 相关阅读:
    java.net.BindException: Cannot assign requested address: bind
    Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name': was expecting ('true', 'false' or 'null')
    springMVC上传错误StandardMultipartHttpServletRequest
    常用软件
    虚拟机修改静态ip
    linux下脚本做成服务
    Unable to resolve persistence unit root URL
    MyBatis对不同数据库的主键生成策略
    MyBatis定义复合主键
    MongoDB安装,启动,注册为windows系统服务
  • 原文地址:https://www.cnblogs.com/tangpg/p/9075019.html
Copyright © 2011-2022 走看看