python - 我想在我的简单 Django 项目中使用 Redis-Cache。我无法理解 Django 中的实现

标签 python django redis django-views

下面是我的观点。现在在这里,我无法获得实现Redis缓存的方法。

从 django.core.cache 导入缓存 类 UserListView(APIView):

def get(self, request):

    # userss = Cach.objects.values('cache_id', 'username', 'email')
    data = Cach.objects.values('cache_id', 'username', 'email')

    # cache.set('users',userss)

    # data = cache.get('users')

    return Response(data)

最佳答案

实现任何缓存的逻辑如下:

  1. 通过获取对象来检查缓存中是否存在对象。
  2. 如果不存在,则计算该对象(或生成它)并将其放入缓存中。
  3. 返回对象。

Django 为缓存提供了一个简单的类似字典的 API。一旦你有 correctly configured the cache ,您可以使用简单的缓存API:

from django.core.cache import cache

def get(request):
   value = cache.get('somekey')
   if not value:
      # The value in the cache for the key 'somekey' has expired
      # or doesn't exist, so we generate the value
      value = 42
      cache.set('somekey', value)

django 中的缓存还有很多内容,请务必阅读 the documentation其中描述了如何在模板中使用缓存、如何缓存整个 View 输出等等。

关于python - 我想在我的简单 Django 项目中使用 Redis-Cache。我无法理解 Django 中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377764/

相关文章:

redis - Spring Session,嵌入式Redis服务器错误

python - 我可以在python中获得没有回声的控制台输入吗?

python - Django 和线程安全

python - Django 表格 : how to display media (javascript) for a DateTimeInput widget?

Django 忽略模型字段

spring-boot - Redis 在使用 Spring Boot 时将对象设置为空 json "{}"

python - 从 python 脚本解锁 Windows 中的文件

python - 如何在python中以键值对的形式打印数组?

python - 如何将数据保存到文件而不是字典列表

php - 使用 Predis 使用 Laravel-5.4.32 配置 AWS ElasticCache redis Cluster-3.2.4