I'm new to Django, and I'm pretty sure I've read or heard about a way to do this, but I can't find it anywhere.
我是Django的新手,我很确定我已经阅读或听说过这样做的方法,但我无法在任何地方找到它。
Rather than sending the rendered output from a template to a browser, I want to create an html file that can then be served without the need to go through the rendering process every time. I'm developing on a system that's separate from our main website's server, and I need to make periodic snapshots of my data available to our users without giving them access to the development system.
我不想将渲染的输出从模板发送到浏览器,而是创建一个html文件,然后可以在不需要每次都完成渲染过程的情况下进行服务。我正在开发一个独立于我们主网站服务器的系统,我需要定期为我们的用户提供我的数据快照,而无需他们访问开发系统。
My intuition says that I should be able to somehow redirect the response to a file, but I'm not seeing it in the docs or in other posts here.
我的直觉说我应该能够以某种方式将响应重定向到文件,但我没有在文档或其他帖子中看到它。
2 个解决方案
#1
17
You can leverage Django's template loader to render your template, including whatever context you pass to it, as a string and then save that out to the filesystem. If you need to save that file on an external system, such as Amazon S3, you can use the Boto library.
您可以利用Django的模板加载器将模板(包括传递给它的任何上下文)呈现为字符串,然后将其保存到文件系统中。如果需要将该文件保存在外部系统(如Amazon S3)上,则可以使用Boto库。
Here's an example of how to render a view to a file, using an optional querystring parameter as the trigger...
这是一个如何使用可选的querystring参数作为触发器来呈现文件视图的示例...
from django.shortcuts import render
from django.template.loader import render_to_string
def my_view(request):
as_file = request.GET.get('as_file')
context = {'some_key': 'some_value'}
if as_file:
content = render_to_string('your-template.html', context)
with open('path/to/your-template-static.html', 'w') as static_file:
static_file.write(content)
return render('your-template.html', context)
#2
3
django-bakery is a well-developed "set of helpers for baking your Django site out as flat files".
django-bakery是一个发展良好的“帮助你将Django网站作为平面文件烘焙的帮助”。
#1
17
You can leverage Django's template loader to render your template, including whatever context you pass to it, as a string and then save that out to the filesystem. If you need to save that file on an external system, such as Amazon S3, you can use the Boto library.
您可以利用Django的模板加载器将模板(包括传递给它的任何上下文)呈现为字符串,然后将其保存到文件系统中。如果需要将该文件保存在外部系统(如Amazon S3)上,则可以使用Boto库。
Here's an example of how to render a view to a file, using an optional querystring parameter as the trigger...
这是一个如何使用可选的querystring参数作为触发器来呈现文件视图的示例...
from django.shortcuts import render
from django.template.loader import render_to_string
def my_view(request):
as_file = request.GET.get('as_file')
context = {'some_key': 'some_value'}
if as_file:
content = render_to_string('your-template.html', context)
with open('path/to/your-template-static.html', 'w') as static_file:
static_file.write(content)
return render('your-template.html', context)
#2
3
django-bakery is a well-developed "set of helpers for baking your Django site out as flat files".
django-bakery是一个发展良好的“帮助你将Django网站作为平面文件烘焙的帮助”。