Django如何使用redis作為緩存
已有Django項(xiàng)目,在其中設(shè)置以redis為緩存。
1、 安裝django-redis:
pip install django-redis
2、 在settings里面配置cache設(shè)置:
CACHES = { 'default':{ 'BACKEND':'django_redis.cache.RedisCache', 'LOCATION':'redis://127.0.0.1:6379/1', # DB設(shè)為1 'TIMEOUT':None, # 永久緩存,默認(rèn)300秒 'OPTIONS':{ 'CLIENT_CLASS':'django_redis.client.DefaultClient', # 'PASSWORD':'xxxxxx' # 可能需要密碼 } }}
3、 設(shè)置好后可以在shell中測試一下:
(1) 在終端中啟動shell:
python manage.py shell
(2) 在shell中輸入,并查看結(jié)果,驗(yàn)證可讀寫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文件來驗(yàn)證,注意要導(dǎo)入settings并執(zhí)行settings.configure():
from django.conf import settingssettings.configure()from django.core.cache import cachecache.set(’key1’,’good day!’)cache.set(’key2’,’other day!’)print(cache.get(’key1’))print(cache.get(’key2’))
能正常顯示如下即可:
good day!
other day!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android table布局開發(fā)實(shí)現(xiàn)簡單計算器2. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼3. 理解PHP5中static和const關(guān)鍵字4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. spring acegi security 1.0.0 發(fā)布7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備