@cache_page decorator
很棒。但是对于我的博客,我希望将页面保留在缓存中,直到有人发表评论。这听起来像是个好主意,因为人们很少评论,因此将页面保留在内存缓存中,而没人评论会很好。我在想某个人之前一定有这个问题吗?这与每个URL的缓存不同。
因此,我正在考虑的解决方案是:
@cache_page( 60 * 15, "blog" );
def blog( request ) ...
然后,我将保留用于博客视图的所有缓存键的列表,然后使“博客”缓存空间过期。但是我对Django并没有超级的经验,所以我想知道是否有人知道更好的方法?
参考方案
此解决方案适用于1.7之前的Django版本
这是我写的一种解决方案,用于完成您在我自己的一些项目中正在谈论的事情:
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
args: any arguments passed to the view function
namepace: optioal, if an application namespace is needed
key prefix: for the @cache_page decorator for the function (if any)
"""
from django.core.urlresolvers import reverse
from django.http import HttpRequest
from django.utils.cache import get_cache_key
from django.core.cache import cache
# create a fake request object
request = HttpRequest()
# Loookup the request path:
if namespace:
view_name = namespace + ":" + view_name
request.path = reverse(view_name, args=args)
# get cache key, expire if the cached item exists:
key = get_cache_key(request, key_prefix=key_prefix)
if key:
if cache.get(key):
# Delete the cache entry.
#
# Note that there is a possible race condition here, as another
# process / thread may have refreshed the cache between
# the call to cache.get() above, and the cache.set(key, None)
# below. This may lead to unexpected performance problems under
# severe load.
cache.set(key, None, 0)
return True
return False
Django会为视图请求的这些缓存设置密钥,因此该操作是为缓存的视图创建一个伪造的请求对象,使用该对象来获取缓存密钥,然后使其过期。
要以您正在谈论的方式使用它,请尝试以下操作:
from django.db.models.signals import post_save
from blog.models import Entry
def invalidate_blog_index(sender, **kwargs):
expire_view_cache("blog")
post_save.connect(invalidate_portfolio_index, sender=Entry)
因此,基本上,只要保存了Blog Entry对象,就会调用invalidate_blog_index,并且缓存的视图也会过期。注意:尚未对此进行广泛测试,但到目前为止对我来说还不错。
Django BigInteger自动递增字段作为主键? - python我目前正在建立一个涉及大量集体智慧的项目。每个访问该网站的用户都将创建一个唯一的配置文件,然后将他们的数据用于为自己和其他用户计算最佳匹配。默认情况下,Django创建一个INT(11)id字段来处理模型的主键。我担心这会很快溢出(即,大约2.4b个设备在未事先设置Cookie的情况下访问了该页面)。如何在MySQL中将其更改为BIGINT并在Django自…
Python GPU资源利用 - python我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…
Python:图像处理可产生皱纹纸效果 - python也许很难描述我的问题。我正在寻找Python中的算法,以在带有某些文本的白色图像上创建皱纹纸效果。我的第一个尝试是在带有文字的图像上添加一些真实的皱纹纸图像(具有透明度)。看起来不错,但副作用是文本没有真正起皱。所以我正在寻找更好的解决方案,有什么想法吗?谢谢 参考方案 除了使用透明性之外,假设您有两张相同尺寸的图像,一张在皱纹纸上明亮,一张在白色背景上有深…
Django Python日期时间设置为午夜 - python我有django对象的日期时间,但可以是一天中的任何时间。它可以是一天中的任何时间,但我需要将时间设置为00:00:00(另一个日期设置为23:59:59,但原理是相同的)end_date = lastItem.pub_date 当前的结束日期是2002-01-11 12:34:56我需要怎么做才能将其更改为00:00:00?我试过了:end_date.ho…
Python uuid4,如何限制唯一字符的长度 - python在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…