簡體   English   中英

如何在redis中獲取保存的值並再次使用它(django)

[英]how to get a saved value in redis and use it again (django)

我是redis的新手。

開發一個django項目,我想知道如何在我的views.py中的一個函數中設置redis值,並在另一個函數中獲取它並再次使用它。

有誰可以幫我一個實際的例子?

非常感謝你

你想使用redis作為緩存后端嗎?這很簡單。首先在settings.py中安裝django-redis-cache

CACHES = {
    'default': {
        'BACKEND': 'redis_cache.RedisCache',
        'LOCATION': 'server:6379',
    },
}


from django.core.cache import cache

>>> cache.set('my_key', 'hello, world!', 30)
>>> cache.get('my_key')
'hello, world!

如果你想查看Redis服務器而不是你有一個命令

➜  ~ redis-cli
127.0.0.1:6379> keys *
1) "key1"
127.0.0.1:6379> get "key1"
hello
127.0.0.1:6379> 

https://redis.io/topics/rediscli

對於Django代碼示例將是這樣的

from django.core.cache import cache



def view_cached_books(request):
    if 'product' in cache:
        # get results from cache
        products = cache.get('product')
        return Response(products, status=status.HTTP_201_CREATED)

    else:
        products = Product.objects.all()
        results = [product.to_json() for product in products]
        # store data in cache
        cache.set(product, results, timeout=CACHE_TTL)
        return Response(results, status=status.HTTP_201_CREATED)

對於Django shell

https://stackoverflow.com/a/41520967/6839331

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM