侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   161

本文实例讲述了Python实现的简单模板引擎功能。分享给大家供大家参考,具体如下:

#coding:utf- 8__author__="sdm"__author_email='[email protected]'__date__ ="$2009-8-25 21:04:13$"'' 'pytpl 类似 php的模板类'' 'import sysimport StringIOimport os.pathimport 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_strdef test():  tpl=Pytpl('./' );  tpl.set('title' , '标题3' )  print tpl.tpl('test.html' )  passif __name__ == "__main__" :  test()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    基于python 字符编码的理解
    下一条:
    Python实现Logger打印功能的方法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客