设为首页 收藏本站
查看: 381|回复: 0

[经验分享] 分享一个简单的python模板引擎

[复制链接]

尚未签到

发表于 2017-5-2 10:06:09 | 显示全部楼层 |阅读模式
python模板引擎也很多,但是希望可以使用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;
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()

test.py

import pytpl
tpl=pytpl.Pytpl('./')
tpl.set('title', 'test title')
print tpl.tpl('test.html')

执行结果

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>test title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
small3
11
</body>
</html>

模板test.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><?=title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?
def add(a,b){
if(a+b<10){
echo('small');
}
return a+b;
}
echo(add(1,2));
echo("\n");
echo(add(10,1));
?>
</body>
</html>

---
编译的中间模板

#coding:utf-8
import sys;global echo;echo=self.output.write
echo ( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n<html>\n  <head>\n    <title>')
echo ( '%s' % (title))
echo ( '</title>\n    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n  </head>\n  <body>\n\n')

def add(a,b):
if(a+b<10):
echo('small');
return a+b;
echo(add(1,2));
echo("\n");
echo(add(10,1));
echo ( '\n    \n  </body>\n</html>\n\n' )


项目已经加入 googlecode
http://code.google.com/p/pythontpl/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-371968-1-1.html 上篇帖子: Python网络编程的一般步骤 下篇帖子: Python Interview Questions And Answers Set
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表