這篇文章主要介紹了在Python的Django框架中調用方法和處理無效變量的方法,是Django編程中的基礎操作,需要的朋友可以參考下
方法調用行為
方法調用比其他類型的查找略為復雜一點。 以下是一些注意事項:
在方法查找過程中,如果某方法拋出一個異常,除非該異常有一個 silent_variable_failure 屬性并且值為 True ,否則的話它將被傳播。如果異常被傳播,模板里的指定變量會被置為空字符串,比如:
- >>> t = Template("My name is {{ person.first_name }}.")
- >>> class PersonClass3:
- ... def first_name(self):
- ... raise AssertionError, "foo"
- >>> p = PersonClass3()
- >>> t.render(Context({"person": p}))
- Traceback (most recent call last):
- ...
- AssertionError: foo
- >>> class SilentAssertionError(AssertionError):
- ... silent_variable_failure = True
- >>> class PersonClass4:
- ... def first_name(self):
- ... raise SilentAssertionError
- >>> p = PersonClass4()
- >>> t.render(Context({"person": p}))
- u'My name is .'
僅在方法無需傳入參數時,其調用才有效。 否則,系統將會轉移到下一個查找類型(列表索引查找)。
顯然,有些方法是有副作用的,好的情況下允許模板系統訪問它們可能只是干件蠢事,壞的情況下甚至會引發安全漏洞。
例如,你的一個 BankAccount 對象有一個 delete() 方法。 如果某個模板中包含了像 {{ account.delete }}這樣的標簽,其中`` account`` 又是BankAccount 的一個實例,請注意在這個模板載入時,account對象將被刪除。
要防止這樣的事情發生,必須設置該方法的 alters_data 函數屬性:
- def delete(self):
- # Delete the account
- delete.alters_data = True
模板系統不會執行任何以該方式進行標記的方法。 接上面的例子,如果模板文件里包含了 {{ account.delete }} ,對象又具有 delete()方法,而且delete() 有alters_data=True這個屬性,那么在模板載入時, delete()方法將不會被執行。 它將靜靜地錯誤退出。
如何處理無效變量
默認情況下,如果一個變量不存在,模板系統會把它展示為空字符串,不做任何事情來表示失敗。 例如:
- >>> from django.template import Template, Context
- >>> t = Template('Your name is {{ name }}.')
- >>> t.render(Context())
- u'Your name is .'
- >>> t.render(Context({'var': 'hello'}))
- u'Your name is .'
- >>> t.render(Context({'NAME': 'hello'}))
- u'Your name is .'
- >>> t.render(Context({'Name': 'hello'}))
- u'Your name is .'
系統靜悄悄地表示失敗,而不是引發一個異常,因為這通常是人為錯誤造成的。 這種情況下,因為變量名有錯誤的狀況或名稱, 所有的查詢都會失敗。 現實世界中,對于一個web站點來說,如果僅僅因為一個小的模板語法錯誤而造成無法訪問,這是不可接受的。
新聞熱點
疑難解答