缓存的配置: 在Django的setting中:
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://your_host_ip:6379',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# "PASSWORD": "yoursecret",
},
},
}
# REDIS_TIMEOUT=7*24*60*60
# CUBES_REDIS_TIMEOUT=60*60
# NEVER_REDIS_TIMEOUT=365*24*60*60
from django.core.cache import cache #引入缓存模块
cache.set('v', '555', 60*60) #写入key为v,值为555的缓存,有效期30分钟
cache.has_key('v') #判断key为v是否存在
cache.get('v') #获取key为v的缓存
一个小例子:
def api(func):
@functools.wraps(func)
# 为什么使用functools.wraps
# https://blog.csdn.net/tiwoo/article/details/50835337
def _deal_with(*args, **kwargs):
response_data = demjson.encode(func(*args, **kwargs))
response = HttpResponse(response_data, content_type="application/json")
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
return _deal_with
@api
def get_singers(request):
page = request.GET.get('page', '1')
page = int(page) if page.isdigit() else 1
size = 20
if not cache.has_key('singers.txt'):
url = "http://artistlistinfo.kuwo.cn/mb.slist?stype=artistlist&category=0&order=hot&pn=0&rn=100&encoding=utf8"
response = requests.get(url)
json_str = response.text
cache.set('singers.txt', json_str, 60 * 60)
else:
json_str = cache.get('singers.txt')
json_obj = demjson.decode(json_str)
artistlist = json_obj.get('artistlist', None)
for artist in artistlist:
artist['pic'] = 'http://img1.sycdn.kuwo.cn/star/starheads/' + artist.get("pic")
# 分页
artist_dict = {
"artistlist": artistlist[(page-1)*size: page*size]
}
return artist_dict