欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django中使用Redis配置緩存的方法步驟

 更新時間:2024年05月16日 10:33:43   作者:Az_plus  
本文主要介紹了Django中使用Redis配置緩存的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

通用方式

直接導入即可使用,在哪個文件使用就在哪個文件導入POOL實例

import redis

POOL = redis.ConnectionPool(max_connections=10, host='127.0.0.1', port=6379, decode_responses=True)
conn = redis.Redis(connection_pool=POOL)

django-redis模塊

安裝

pip install django-redis

settings配置文件

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "None",
        }
    }
}

簡單使用

from django_redis import get_redis_connection

class RedisView(ViewSet):
    def list(self, request):
        conn = get_redis_connection() # 從池中獲取一個鏈接
        conn.incrby('count')
        count = conn.get('count')
        return APIResponse(msg='您是第%s個訪問的' % count)

Django的緩存機制(配置緩存)

當導入了django-redis模塊,并且settings配置CACHES后,Django自帶的緩存機制便會自動將數(shù)據(jù)存入Redis緩存中,并且不用判斷數(shù)據(jù)類型,非常方便

  • 必須安裝django-redis且配置如下
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "123",
        }
    }
}
  • 其他文件中存入緩存
from django.core.cache import cache

conn.set('key1',{'name':'123'})
name = conn.get('key1')
print(name)
# {'name': '123'}

 到此這篇關(guān)于Django中使用Redis配置緩存的方法步驟的文章就介紹到這了,更多相關(guān)Django Redis緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論