Python实现的简单模板引擎功能示例

作者:m190481164 时间:2022-01-24 04:47:36 

本文实例讲述了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,模板引擎
0
投稿

猜你喜欢

  • python模拟点击网页按钮实现方法

    2021-06-18 21:13:09
  • 再谈Python中的字符串与字符编码(推荐)

    2023-06-15 23:25:08
  • Python 一篇文章看懂时间日期对象

    2022-12-23 04:29:14
  • 关于Pandas count()与values_count()的用法及区别

    2021-09-25 08:28:20
  • web版Photoshop来了

    2008-04-21 13:39:00
  • Python统计词频的几种方法小结

    2023-10-22 05:35:41
  • pytorch:model.train和model.eval用法及区别详解

    2022-07-13 19:22:51
  • Python聚类算法之基本K均值实例详解

    2023-07-14 12:49:08
  • Python参数解析模块sys、getopt、argparse使用与对比分析

    2021-12-19 17:39:58
  • Python采集股票数据并制作可视化柱状图

    2023-01-10 12:34:27
  • python DataFrame中loc与iloc取数据的基本方法实例

    2022-06-23 15:58:25
  • 解读python正则表达式括号问题

    2023-08-10 10:22:19
  • 内联格式化模式(line-height原理)

    2008-06-29 14:37:00
  • [教程]用代码让你了解网页与键盘

    2008-06-10 12:18:00
  • python静态方法实例

    2023-02-17 12:03:22
  • 五个常用MySQL图形化管理工具

    2012-01-05 18:49:16
  • Python里的dict和set的背后小秘密

    2023-11-20 01:01:11
  • 一文带你熟悉Go语言中函数的使用

    2023-07-13 08:22:23
  • Mysql5写中文乱码问题解决

    2007-09-17 12:38:00
  • Python+Flask编写一个简单的行人检测API

    2023-09-26 17:55:19
  • asp之家 网络编程 m.aspxhome.com