如何从django模板生成静态html文件?

Bev*_*ock 25 html django django-templates static-html static-site

我是Django的新手,我很确定我已经阅读或听说过这样做的方法,但我无法在任何地方找到它.

我不想将渲染的输出从模板发送到浏览器,而是创建一个html文件,然后可以在不需要每次都进行渲染过程的情况下进行提供.我正在开发一个独立于我们主网站服务器的系统,我需要定期为我们的用户提供我的数据快照,而无需他们访问开发系统.

我的直觉说我应该能够以某种方式将响应重定向到文件,但我没有在文档或其他帖子中看到它.

Bra*_*don 24

您可以利用Django的模板加载器将模板(包括传递给它的上下文)呈现为字符串,然后将其保存到文件系统中.如果需要将该文件保存在外部系统(如Amazon S3)上,则可以使用Boto库.

这是一个如何使用可选的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)
Run Code Online (Sandbox Code Playgroud)

  • 不是'open`而是`codecs.open`指定`utf-8` (2认同)

fif*_*nce 6

django-bakery是一套完善的“用于将 Django 站点烘焙为平面文件的助手集”。