我将Django用作移动前端的API。我只是来回发送JSON。我已经为家庭供稿创建了一个端点。每个用户都有一个独特的家庭供稿,具体取决于他们关注的人。用户发布一张照片,然后将该照片推送到其所有关注者的家庭供稿中。到目前为止非常简单直接。
我的几个同事建议我应该实现某种缓存层,但是问题是,这不仅仅是一个静态的常规站点。每个视图都是基于访问它的用户而动态的。
因此,例如,家庭供稿是按DESC时间顺序(从近到晚)在平台上发布的照片列表。
主页提要视图非常基本。每个用户在Redis中都有一个“ homefeed:user_id:%s”列表,其中包含照片对象的主键。我通过Redis拨打电话并获取request.user的家庭供稿列表,然后使用该列表查询数据库中的对象,如下所示:
homefeed_pk_list = redis_server.lrange('homefeed:user_id:%s' % request.user.pk, 0, 100)
# Home feed queryset
queryset = Photo.objects.filter(pk__in = homefeed_pk_list)
response_data= []
for photo in queryset:
# Code to return back JSON data
return HttpResponse(json.dumps(response_data), content_type="application/json")
很简单 现在我的问题是,在这种情况下,缓存的最佳实践应该是什么?我可以分别缓存每个序列化的照片对象,并设置24小时的到期时间,因为某些照片对象位于多个供稿中(用户。如果该对象在缓存中不存在,我将打入数据库。您如何看待这种方法?
为了获得最佳性能,您可以实施类似于Russian Doll Caching的方法,其摘要如下:缓存对象,缓存这些对象的列表,缓存包含该列表的生成页面(即,不仅缓存完成的结果,一直向下缓存)。
但是,以您的示例为例,我可能会从以下内容开始:
import hashlib
from django.core.cache import cache
from django.http import HttpResponse
from whereever import redis_server
def feed(request):
"""
Returns a JSON response containing Photo data.
"""
# Get the list of PKs from Redis
photo_pks = redis_server.lrange(
'homefeed:user_id:%d' % request.user.pk,
0,
100
)
# Make a SHA1 hash of the PKs (cache key)
cach_key = hashlib.sha1(unicode(photo_pks)).hexdigest()
# Get the existing cache
content = cache.get(cach_key)
if content is None:
# Make a queryset of Photos using the PK list
queryset = Photo.objects.filter(pk__in=photo_pks)
# Use .values() to get a list of dicts (the response data)
content = json.dumps(
queryset.values('pk', 'url', 'spam', 'eggs')
)
# Cache the response string for 24 hours
cache.set(cach_key, content, 60 * 60 * 24)
return HttpResponse(content, content_type='application/json')
结果将是响应内容将被缓存24小时,或者直到Redis中的PK列表(大概在其他地方设置并在添加新照片等时更新)为止,因为缓存键是使用哈希值PK列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句