生成靜態(tài)很簡單,下面是一個例子:
只要在views.py中這樣寫就行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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)容。
如果服務(wù)器上不支持Django環(huán)境,你可以在本地上搭建一個Django環(huán)境,然后生成靜態(tài)頁面,把這些頁面放到不支持 Django 的服務(wù)器上去,在本地更新,然后上傳到服務(wù)器,用Django來管理和更新網(wǎng)站的內(nèi)容,也是一個不錯的做法,還可以更安全,聽說有很多黑客都是這么做的。