歡迎您光臨本站 註冊首頁

Django如何使用redis作為緩存

←手機掃碼閱讀     qp18502452 @ 2020-06-10 , reply:0

已有Django項目,在其中設置以redis為緩存。

1、 安裝django-redis:

pip install django-redis

2、 在settings裡面配置cache設置:

  CACHES = {    "default":{      "BACKEND":"django_redis.cache.RedisCache",      "LOCATION":"redis://127.0.0.1:6379/1",  # DB設為1      "TIMEOUT":None,  # 永久緩存,默認300秒      "OPTIONS":{        "CLIENT_CLASS":"django_redis.client.DefaultClient",        # "PASSWORD":"xxxxxx" # 可能需要密碼      }    }  }

 

3、 設置好後可以在shell中測試一下:

(1) 在終端中啟動shell:

python manage.py shell

(2) 在shell中輸入,並查看結果,驗證可讀寫Cache:

In [1]: from django.core.cache import cache

In [2]: cache.set('mykey','haha,I get it!')

Out[2]: True

In [3]: cache.get('mykey')

Out[3]: 'haha,I get it!'

(3) 如果不能正常啟動shell,可能是ipython版本過低,升級ipython即可:

pip install ipython --upgrade

4、 也可以新建test.py文件來驗證,注意要導入settings並執行settings.configure():

  from django.conf import settings  settings.configure()  from django.core.cache import cache  cache.set('key1','good day!')  cache.set('key2','other day!')  print(cache.get('key1'))  print(cache.get('key2'))

 

能正常顯示如下即可:

good day!

other day!

                                                       

   


[qp18502452 ] Django如何使用redis作為緩存已經有248次圍觀

http://coctec.com/docs/python/shhow-post-237852.html