是否可以将django中的render_to_response模板保存到服务器?

use*_*078 1 python django caching mongodb

我用Python,Django框架创建了Web应用程序.Web应用程序从MongoDB数据库获取数据,从MongoDB数据库获取大约10000个文档,并且工作速度很慢.现在正在寻找加快我的网络应用程序的方法.那么,是否可以将方法的结果render_to_response作为HTML临时存储在服务器上?它看起来像这样:我有一个HTML表单; 当用户在表单中键入数据并单击"提交"按钮时,Web应用程序将执行从Mongo数据库获取数据的视图,并通过变量将该数据发送 mongo_datahome.html:

return render_to_response('home.html', {'mongo_data': mongo_data, 'request': request},
                          context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

home.html显示存储在变量中的数据mongo_data.在Web应用程序中,我有很多相同的查询,对于相同的查询,我得到相同的结果home.html.所以我想在服务器上存储home.html到文件夹temp,当用户在HTML表单中键入数据并单击提交按钮时,首先检查home.html他的数据是否在temp文件夹中; 如果是,则加载home.html,如果没有,则转到查看哪个将生成home.html特定的新mongo_data.如果这是可能的,它将加速我的网络应用程序..

Eri*_*lun 5

Django缓存框架完全是为了这个目的而制作的; 请参阅https://docs.djangoproject.com/en/dev/topics/cache/.

在您的情况下,您要么将整个视图缓存一段时间:

@cache_page(60 * 15)
def my_mongo_view(request):
    return render_to_response('home.html', ...)
Run Code Online (Sandbox Code Playgroud)

(来自https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache)

或者您使用低级缓存API(https://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api):

from django.core.cache import cache

def my_mongo_view(request):
    ret = cache.get('home-rendered')
    if ret is None:
        ret = render_to_response('home.html', ...)
        cache.set('home-rendered', ret)
    return ret
Run Code Online (Sandbox Code Playgroud)

如果你只是阅读文档,你会发现更多的缓存选项(例如在你的模板中).

PS你还可以通过变量或用户ID或其他东西来参数化你的缓存.