編寫自定義的Django模板加載器的簡單示例
Djangos 內(nèi)置的模板加載器(在先前的模板加載內(nèi)幕章節(jié)有敘述)通常會滿足你的所有的模板加載需求,但是如果你有特殊的加載需求的話,編寫自己的模板加載器也會相當簡單。 比如:你可以從數(shù)據(jù)庫中,或者利用Python的綁定直接從Subversion庫中,更或者從一個ZIP文檔中加載模板。
模板加載器,也就是 TEMPLATE_LOADERS 中的每一項,都要能被下面這個接口調(diào)用:
load_template_source(template_name, template_dirs=None)
參數(shù) template_name 是所加載模板的名稱 (和傳遞給 loader.get_template() 或者 loader.select_template() 一樣), 而 template_dirs 是一個可選的代替TEMPLATE_DIRS的搜索目錄列表。
如果加載器能夠成功加載一個模板, 它應當返回一個元組: (template_source, template_path) 。在這里的 template_source 就是將被模板引擎編譯的的模板字符串,而 template_path 是被加載的模板的路徑。 由于那個路徑可能會出于調(diào)試目的顯示給用戶,因此它應當很快的指明模板從哪里加載。
如果加載器加載模板失敗,那么就會觸發(fā) django.template.TemplateDoesNotExist 異常。
每個加載函數(shù)都應該有一個名為 is_usable 的函數(shù)屬性。 這個屬性是一個布爾值,用于告知模板引擎這個加載器是否在當前安裝的Python中可用。 例如,如果 pkg_resources 模塊沒有安裝的話,eggs加載器(它能夠從python eggs中加載模板)就應該把 is_usable 設為 False ,因為必須通過 pkg_resources 才能從eggs中讀取數(shù)據(jù)。
一個例子可以清晰地闡明一切。 這兒是一個模板加載函數(shù),它可以從ZIP文件中加載模板。 它使用了自定義的設置 TEMPLATE_ZIP_FILES 來取代了 TEMPLATE_DIRS 用作查找路徑,并且它假設在此路徑上的每一個文件都是包含模板的ZIP文件:
from django.conf import settings
from django.template import TemplateDoesNotExist
import zipfile
def load_template_source(template_name, template_dirs=None):
"Template loader that loads templates from a ZIP file."
template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
# Try each ZIP file in TEMPLATE_ZIP_FILES.
for fname in template_zipfiles:
try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
# We found a template, so return the source.
template_path = "%s:%s" % (fname, template_name)
return (source, template_path)
# If we reach here, the template couldn't be loaded
raise TemplateDoesNotExist(template_name)
# This loader is always usable (since zipfile is included with Python)
load_template_source.is_usable = True
我們要想使用它,還差最后一步,就是把它加入到 TEMPLATE_LOADERS 。 如果我們將這個代碼放入一個叫mysite.zip_loader的包中,那么我們要把mysite.zip_loader.load_template_source加到TEMPLATE_LOADERS中。
相關文章
Python Selenium網(wǎng)頁自動化利器使用詳解
這篇文章主要為大家介紹了使用Python Selenium實現(xiàn)網(wǎng)頁自動化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
python攻防-破解附近局域網(wǎng)WIFI密碼實現(xiàn)上網(wǎng)自由
本文將記錄學習如何通過 Python 腳本實破解附近局域網(wǎng) WIFI 密碼的暴力破解,隨時隨地免費蹭網(wǎng),再也不被WiFi密碼困擾,實現(xiàn)蹭網(wǎng)自由2021-08-08
一文搞懂Pandas數(shù)據(jù)透視的4個函數(shù)的使用
今天主要和大家分享Pandas中四種有關數(shù)據(jù)透視的通用函數(shù),在數(shù)據(jù)處理中遇到這類需求時,能夠很好地應對,快跟隨小編一起學習一下吧2022-06-06
在linux系統(tǒng)下安裝python librtmp包的實現(xiàn)方法
今天小編就為大家分享一篇在linux系統(tǒng)下安裝python librtmp包的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python 動態(tài)調(diào)用函數(shù)實例解析
這篇文章主要介紹了python 動態(tài)調(diào)用函數(shù)實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10

