Does Django's render_to_response cache unrendered templates or load from disk every time?

久未见 提交于 2019-12-07 18:39:01

问题


Fetching a template from disk is significantly slower than pulling it out of something like memcached, so loading them from disk each time is wasteful.

Does Django cache unrendered templates in memory or in the CACHE_BACKEND or do I have to implement that myself?


回答1:


Django comes with a cached template loader as well.




回答2:


I can't seem to find anyplace where the filesystem loader might cache the templates. It sure does look like it loads them every time.

This probably isn't really a problem, though. For one thing, the filesystem loader does exactly what it says, it reads the templates from disk every time they are used. It will always pick up changes to the on disk template as soon as the changes are made.

If you don't want that behavior, you might want to use a different loader. In fact, that's pretty easy to do; just subclass from django.template.loader.filesystem.Loader, overload load_template, and enjoy.

I'm pretty suspicious of caching, though. If I were to implement such a solution, I'd make sure that cache evictions happen often. Like every 10 seconds.




回答3:


You have to enable cache yourself. By default, every time you render a template it is read from disk, parsed and rendered.

There are many ways to implement cache in Django. All of them described in the Django's cache framework help page.

Depending on what you're trying to achieve you can cache entire requests or only template blocks. Read the page above for details.




回答4:


I suspect that if the template is read every time, it will probably stay in the buffer cache of the kernel most of the time. You shouldn't invest any time in such optimization as long as you don't have a prove, that this is really something that drains don performance.



来源:https://stackoverflow.com/questions/5308996/does-djangos-render-to-response-cache-unrendered-templates-or-load-from-disk-ev

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!