Python实现的简单模板引擎功能示例
作者:m190481164 发布时间:2022-01-24 04:47:36
标签:Python,模板引擎
本文实例讲述了Python实现的简单模板引擎功能。分享给大家供大家参考,具体如下:
#coding:utf- 8
__author__="sdm"
__author_email='sdmzhu3@gmail.com'
__date__ ="$2009-8-25 21:04:13$"
'' '
pytpl 类似 php的模板类
'' '
import sys
import StringIO
import os.path
import os
#模 板的缓存
_tpl_cache={}
class Pytpl:
def __init__(self,tpl_path='./' ):
self.tpl_path=tpl_path
self.data={}
self.output = StringIO.StringIO()
pass
def set(self,name,value):
'' '
设 置模板变量
'' '
self.data[name]=value;
pass
def get(self,name):
'' '
得 到模板变量
'' '
t={}
return t.get(name, '' )
pass
def tpl(self,tplname):
'' '
渲 染模板
'' '
f=self.tpl_path+tplname
if not os.path.exists(f):
raise Exception('tpl:[%s] is not exists' % f)
mtime=os.stat(f).st_mtime
if not _tpl_cache.has_key(f) or _tpl_cache[f][ 'time' ]<mtime:
src_code=self.__compile__(open(f).read())
try :
t=open(f+'.py' , 'w' )
t.write(src_code)
t.close()
except:
pass
py_code=compile(src_code, f+'.py' , 'exec' )
_tpl_cache[f]={'code' :py_code, 'time' :mtime}
else :
py_code= _tpl_cache[f]['code' ]
exec(py_code, {'self' :self}, self.data)
return self.output.getvalue()
def execute(self,code,data,tplname):
'' '
执 行这个模板
'' '
py_file_name=tplname+'.py'
f=open(py_file_name,'w' )
f.write(code)
f.close()
execfile(py_file_name, {'self' :self}, data)
def __compile__ (self,code):
'' '
编 译模板
查找 <?标记
'' '
tlen=len(code);
flag_start='<?'
flag_end='?>'
# 默认普通标记
status=0
i=0
#分块 标记
pos_end=0
pos_start=0
#缩 进
global indent
indent=0
py_code=[]
def place_t_code(c,t_indent):
'' '
基 本的代码处理
'' '
global indent
if (c[ 0 ]== '=' ):
return ( ' ' * 4 *indent) + 'echo ( /'%s/' % (' +c[ 1 :]+ '))'
lines=c.split("/n" )
t=[]
for i in lines:
indent2=indent
tmp=i.strip(" /n/r" )
c=tmp[len(tmp)-1 :len(tmp)]
# 判定最后一个字符
if (c== '{' ):
indent+=1
tmp=tmp[0 :len(tmp)- 1 ]+ ":"
elif(c=='}' ):
indent-=1
tmp=tmp[0 :len(tmp)- 1 ]
t.append((' ' * 4 *indent2) +tmp )
return "/n" .join(t)
while 1 :
if i>=tlen: break
c=code[i];
if status== 0 :
# 编译加速
pos_start=code.find(flag_start,pos_end);
if (pos_start>- 1 ):
s=code[pos_end:pos_start]
t_code= 'echo ( ' +repr(s)+ ')'
t_code=' ' *indent* 4 +t_code
if s:
py_code.append(t_code)
i=pos_start
last_pos=i
# 进入代码状态
status=1
continue
else :
# 没有没有找到
pos_start=tlen
t_code='echo ( ' +repr(code[pos_end:pos_start])+ ' ) '
t_code=' ' *indent* 4 +t_code
py_code.append(t_code)
break
if status== 1 :
# 查找结束标记
pos_end=code.find(flag_end,i)
if (pos_end>- 1 ):
# 需要跳过<? 这个标记
t_code=place_t_code(code[pos_start+2 :pos_end],indent)
# 跳过?>结束标记
pos_end+=2
py_code.append(t_code)
else :
# 没查找到直接结束
pos_end=tlen
# 需要跳过<? 这个标记
t_code=place_t_code(code[pos_start+2 :pos_end],indent)
py_code.append(t_code)
break
status=0
i=pos_end
pass
i+=1
py_code_str="#coding:utf-8/nimport sys;global echo;echo=self.output.write/n"
py_code_str+="/n" .join(py_code)
py_code_str=py_code_str.replace("/t" , " " )
return py_code_str
def test():
tpl=Pytpl('./' );
tpl.set('title' , '标题3' )
print tpl.tpl('test.html' )
pass
if __name__ == "__main__" :
test()
希望本文所述对大家Python程序设计有所帮助。
来源:http://blog.csdn.net/m190481164/article/details/5611713


猜你喜欢
- 本文实例讲述了Python实现将16进制字符串转化为ascii字符的方法。分享给大家供大家参考,具体如下:字符串456e633064316e
- 1.INSERT INTO SELECT语句 语句形式为:Insert into Table2(field1,field2,...) sel
- 今天来说一下如何判断字典中是否存在某个key,一般有两种通用做法,下面为大家来分别讲解一下:第一种方法:使用自带函数实现。在python的字
- 在读取https://github.com/Embedding/Chinese-Word-Vectors中的中文词向量时,选择了一个有3G多
- 一、random模块简介Python标准库中的random函数,可以生成随机浮点数、整数、字符串,甚至帮助你随机选择列表序列中的一个元素,打
- 观看本文前最好有一定的Linux命令基础,具体为centos7.3环境中清除使用yum安装的Mysql卸载前请先关闭Mysql服务servi
- 程序图标主要作用是为了使该程序更加具象及更容易理解,除了上述的作用外,有更好视觉效果的图标可以提高产品的整体体验和品牌,可引起用户的关注和下
- sql server中如何判断表或者数据库的存在,但在实际使用中,需判断Status状态位:其中某些状态位可由用户使用 sp_dboptio
- 举一个例子,我现在有一些新闻信息,它包括这些字段;新闻ID,新闻Name,新闻ShortIntro,新闻Detail,新闻PublishTi
- 1. interface{}初探Go是强类型语言,各个实例变量的类型信息正是存放在interface{}中的,Go中的反射也与其底层结构有关
- 一.图像金字塔图像金字塔是指由一组图像且不同分别率的子图集合,它是图像多尺度表达的一种,以多分辨率来解释图像的结构,主要用于图像的分割或压缩
- 前言要将图片转换为字符图其实很简单,我们首先将图片转换为灰度图像,这样图片的每个像素点的颜色值都是0到255,然后我们选用一些在文字矩形框内
- 一、Django密码存储和加密方式#算法+迭代+盐+加密<algorithm>$<iterations>$<s
- Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AM Select
- 偶第一次发主题, 这个是在一个项目中的做...写的一般般, 有什么bug之类的是在所难免, 望见谅功能说明:1. 即时控制用户输入2. 将输
- php读写二进制文件可以使用pack和unpack函数。今天要处理一个二进制文件的问题,所以需要用一下,特意了解一下pack的用法,unpa
- 写在前面这两种方式的配置基本相同,都是配一下node地址,Eslint执行文件的地址,Eslint的配置文件(就是.eslintrc)等,而
- 习惯于使用数据库之前都必须创建一个连接池,即使是单线程的应用,只要有多个方法中需用到数据库连接,建立一两个连接的也会考虑先池化他们。连接池的
- 常用配置以下配置能使用File -> New Projects Settings -> Settings for New Pro
- 1、并双击新建工程窗口中ActiveX DLL图标,VB将自动为项目添加一个类模块,并将该项目类型设置为ActiveX DLL。2、在属性窗