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

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

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

通用方式

直接導(dǎo)入即可使用,在哪個(gè)文件使用就在哪個(gè)文件導(dǎo)入POOL實(shí)例

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",
        }
    }
}

簡(jiǎn)單使用

from django_redis import get_redis_connection

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

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

當(dāng)導(dǎo)入了django-redis模塊,并且settings配置CACHES后,Django自帶的緩存機(jī)制便會(huì)自動(dòng)將數(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論