使用python操做redis及簡單應用

redis 鏈接實例是線程安全的,能夠直接將redis鏈接實例設置爲一個全局變量,直接使用.

pip install redispython

import redisredis

r = redis.Redis(host='localhost',port=6379,password='', db=0)
r.set('guo','shuai')
True
r.get('guo')
'shuai'
r['guo']
'shuai'
r.keys()
['guo']
r.dbsize() #當前數據庫包含多少條數據
1L
r.delete('guo')
1
r.save() #執行「檢查點」操做,將數據寫回磁盤。保存時阻塞
True
r.get('guo');
r.flushdb() #清空r中的全部數據
True

讓redis 運行在python的django程序中

準備安裝包
pip install django-redis-sessions數據庫

在setting的配置,增長session配置

SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_HOST = 'localhost'
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 4
SESSION_REDIS_PASSWORD = ''
SESSION_REDIS_PREFIX = 'session'django

url 配置:

url(r'^set_session/', views.set_session),
url(r'^get_session/', views.get_session),安全

views 配置代碼

def set_session(request):
""""保存session數據"""
request.session['username'] = 'Django'
request.session['password'] = '123456'
return HttpResponse('保存session數據成功')session

def get_session(request):
"""獲取session數據"""
username = request.session.get('username')
password = request.session.get('password')
text = 'username=%s, password=%s' % (username, password)
return HttpResponse(text)ide

相關文章
相關標籤/搜索