幾個用於除錯Django模板的標籤

2021-08-30 16:56:20 字數 3034 閱讀 9922

django模板有諸多限制,例如不能呼叫方法,不能執行任意的python表示式。它的設計者表示這樣做是故意的,我不去爭論這樣到底是好是壞,但在除錯時我們確實需要想執行任意的python表示式。django提供了自定義標籤的機制,再加上python的eval函式,使得在django模板中也能執行任意的python表示式。

我寫了三個標籤,分別是set, print和import。set的語法為:

它會執行python_expression的值,並把它新增到的模板上下文,而後可以用varname引用。

python_expression可以為任意的python表示式,可以使用模板上下文中的變數。

views.py

return render_to_response('test.html' )

test.html

length of list: }

now num value: }

輸出:

length of list: 3

now num value: 28

print標籤就更簡單了,它的語法為:

它直接輸出python_expression的值。上面的test.html可以寫成:

length of list:

now num value:

import標籤,顧名思義,是用來匯入python模組,它的語法為:

test.html

它們的實現很簡單,直接附在這裡:

from django import template

import re

register = template.library()

set_regex = re.compile(r'^\s*set\s+(\w+)\s*=\s*(.*)$')

def do_set(parser, token):

m = re.match(set_regex, token.contents)

if m:

name, exp = m.group(1), m.group(2)

return setnode(name, exp)

else:

raise template.templatesyntaxerror('')

class setnode(template.node):

def __init__(self, varname, expression):

self.varname = varname

self.expression = expression

def render(self, context):

context[self.varname] = eval(self.expression, {}, context)

return ''

register.tag('set', do_set)

print_regex = re.compile(r'^\s*print\s+(.*)$')

def do_print(parser, token):

m = re.match(print_regex, token.contents)

if m:

exp = m.group(1)

return printnode(exp)

else:

raise template.templatesyntaxerror('')

class printnode(template.node):

def __init__(self, expression):

self.expression = expression

def render(self, context):

obj = eval(self.expression, {}, context)

return str(obj)

register.tag('print', do_print)

import_regex = re.compile(r'^\s*import\s+(\s+)(?:\s+as\s+(\w+))?$')

def do_import(parser, token):

m = re.match(import_regex, token.contents)

if m:

exp = m.group(1)

try:

alias = m.group(2)

except:

alias = none

return importnode(exp, alias)

else:

raise template.templatesyntaxerror('')

class importnode(template.node):

def __init__(self, expression, alias=none):

if not alias: alias = expression

self.expression = expression

self.alias = alias

def render(self, context):

module = __import__(self.expression, {}, context)

context[self.alias] = module

return ''

register.tag('import', do_import)

用於除錯的巨集

在linux程式設計中,gdb是個不錯的除錯工具。但是當檔案數量上百,甚至上千之後,使用gdb除錯就是一場災難。因此在程式中加入合理的列印資訊,能更高效的定位到問題的所在。下面就是定義的巨集。分別是warning,info,error。利用了,file function line 變數。cpp vi...

VC中用於除錯程式的幾個巨集的使用技巧

一 trace巨集 當選擇了debug目標,並且afxtraceenabled變數被置為true時,trace巨集也就隨之被啟用了。但在程式的release版本中,它們是被完全禁止的。下面是乙個典型的trace語句 int ncount 9 cstring strdesc total trace c...

Oceanbase除錯 用於除錯的單機集群的搭建

涉及到多個角色 服務 mergeserver,updateserver,chunkserver,rootserver 的oceanbase除錯需要將整個集群啟動起來後進行,為了方便,可以在同一臺計算機上啟動這些服務,只要占用的埠不同即可。下面簡要記錄如何在同一臺計算機上啟動oceanbase的四個服...