django_redis
首先在settings中
依赖于pip3 install django-redis
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTIO_POOL_KWARGS': {'max_connections': 100}
}
}
}
使用时, 只是个例子
from django_redis import get_redis_connection
class PaymentViewSet(APIView):
authentication_classes = [LuffyAuth, ]
conn = get_redis_connection("default")
def post(self, request, *args, **kwargs):
ret = BaseResponse()
try:
# luffy_payment_1_* luffy_payment_coupon_1
key_list = self.conn.keys(settings.PAYMENT_KEY % (request.auth.user_id, "*",))
key_list.append(settings.PAYMENT_COUPON_KEY % (request.auth.user_id,))
self.conn.delete(*key_list)
payment_dict = {}
# 获取用户要结算的课程id
global_coupon_dict = {
"coupon": {},
"default_coupon": 0,
}
course_id_list = request.data.get('courseids')
print(course_id_list)
大概就是这么用
插入个小问题
字典里有100w条数据, 怎么打印数据?
1) result = conn,hgetall('k4')
print(result) 易爆栈, 为下下策
2)ret = conn.hsacn_iter('k4', count=100, cursor=起始位置) # 第一次执行不取, for执行才开始取
for item in ret:
print(item)
djago 用 redis缓存
全站缓存
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware', # 要放在最前面
'django.middleware.cache.FetchFromCacheMiddleware' # 放在最后面
]
单视图缓存
不加中间价
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # 60s * 15 15分钟
def....
或者
urlpatterns = [url(r'^foo/([0-9]{1,2})/$', cache_page(60 * 15)(my_view)),]
局部网页缓存
{% load cache %}
{% cache 5000 缓存key的键 %}
缓存内容
{% endcache %}
python redis
import redis
conn = redis.Redis(host='', port=6379, password=)
conn.lpush('k1', 11)
conn.lpush('k1', 22)
conn.rpush('k1', 33)
conn.lrange('k1', 0, -1)
conn.lpop('k1')
conn.rpop('k1')
conn.blpop('k1') # 从左边拿走一个, 没有一直等待
conn.blpop('k1', timeout=10) # 设置超时时间
conn.brpop() # 从右边拿走一个
# 有的有scan_iter方法
可以
for item in conn.scan_iter('xx', count=10):
print(item)
# 没有的自己写迭代
def list_iter(key, count=100):
index = 0
while True:
data_list = conn.lrange('k1', index, index + count -1)
if not data_list:
return
index += count
for item in data_list:
yield item
# 使用时
for item in list_iter('k1', count=3):
print(item)
事务
pipe = conn.pipeline(transaction=True)
pipe = multi()
pipe.set('k2', '123')
pipe.hset('k3', 'n1', 666)
pipe.lpush('k4', 'xx')
pipe.excute()
其他的一些操作
import redis
conn = redis.Redis(host='', port=6379, password=)
conn.flushall() # 清空
conn.keys() # 拿走所有键
conn,delete('xx') # 删除指定键