from django.shortcuts import render
from django.template.loader import render_to_string
import os
def my_view(request):
context = {'some_key': 'some_value'}
static_html = '/path/to/static.html'
if not os.path.exists(static_html):
content = render_to_string('template.html', context)
with open(static_html, 'w') as static_file:
static_file.write(content)
return render(request, static_html)
當(dāng)用戶訪問時,如果判斷沒有靜態(tài)頁面就自動生成靜態(tài)頁面辐赞,然后返回靜態(tài)文件钾埂,當(dāng)文件存在的時候就不再次生成。
也可以用一個文件夾断楷,比如在project下建一個 static_html 文件夾锨匆,把生成的靜態(tài)文件都放里面,讓用戶像訪問靜態(tài)文件那樣訪問頁面冬筒。
更佳辦法
但是一般情況下都不需要生成靜態(tài)頁面恐锣,因為Django 有緩存功能,使用 Django Cache(緩存)就相當(dāng)于把生成生成靜態(tài)頁面舞痰,而且還有自動更新的功能土榴,比如30分鐘刷新一下頁面內(nèi)容