gpt4 book ai didi

python - 是否可以将 render_to_response 模板从 django 保存到服务器?

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:20 27 4
gpt4 key购买 nike

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

return render_to_response('home.html', {'mongo_data': mongo_data, 'request': request},
context_instance=RequestContext(request))

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

最佳答案

Django 缓存框架正是为此而生;见https://docs.djangoproject.com/en/dev/topics/cache/ .

在您的情况下,您可以将整个 View 缓存一段时间:

@cache_page(60 * 15)
def my_mongo_view(request):
return render_to_response('home.html', ...)

(来自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

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

附言您还可以通过变量或用户 ID 或其他方式对缓存进行参数化。

关于python - 是否可以将 render_to_response 模板从 django 保存到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com