使用中间件或自定义模板标签来处理不经常更改的代码片段
我的侧边栏中有一个我想要的小片段。该代码片段将在每个页面上可见,虽然获取起来很便宜(在我的超慢上网本上大约需要 50 毫秒!),但很少会更改,因此我很想缓存它(部分原因是我还没有使用 Django 的缓存)框架,我想学习)。
我不确定最好的方法是什么 - 中间件还是自定义模板标签?我不确定使用这些方法实现缓存有多容易。这是一个非常标准的事情(即,对每个页面上可见的片段进行片段缓存),我确信有一种Djangonic方法可以做到这一点,但我找不到它是什么。
你怎么做?
I've got a small snippet that I want in my sidebar. The snippet will be visible on each page, and while cheap to fetch (about 50ms on my super-slow netbook!), will change so infrequently that I'd quite like to cache it (partly because I've yet to use Django's cache framework, and I'd like to learn).
I'm not sure what the best way to go here is - middleware or a custom template tag? I'm not sure how easy it would be to implement caching with these approaches. This is such a standard thing to want to do (that is, fragment caching of a fragment visible on each page) that I'm sure there's a Djangonic way to do it, but I can't find what it is.
How do you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这听起来非常适合模板片段缓存。
This sounds perfect for Template fragment caching.
我认为你不需要使用中间件。自定义模板标签可以解决这个问题。由于您正在执行类似状态消息之类的操作,因此它与当前视图无关,因此该标记绝对合适。
只需设置缓存后端(这很容易做到 ),您将可以访问
cache.set()
和cache.get()
方法,您可以使用它们来存储和检索状态消息。请务必在状态消息更新时清除缓存。I don't think you need to use middleware. A custom template tag would work for this. Since you're doing something like a status message, it would be unrelated to whatever the current view is, so the tag is definitely appropriate.
Just set up the cache back-end (this is very easy to do) and you will have access to
cache.set()
andcache.get()
methods which you can use to store, and retrieve your status message. Be sure to clear the cache whenever the status message is updated.