您的位置:首页 > 编程语言 > Go语言

DJango内建模板转向jinja2的小脚本

2014-02-20 16:09 330 查看
import re,os

def org(path=os.getcwd(),fs=None,preview=True):
fs = fs or []
for root,dirs,files in os.walk(path):
for f in files:
if f[-4:]=='html':
fp=os.path.join(root,f)
s=open(fp,encoding='u8').read()
for func in fs:
s=func(s,preview)
if not preview:
open(fp,'w',encoding='u8').write(s)

url_kwargs_reg=re.compile(r"""
{%\s*url\s+
(?P<viewfunc>((?P<q1>['"]?)[\w:.]+(?P=q1)))
(?P<kwargs>(\s+\w+\s*=\s*(?P<q2>['"]?)[.\w]+(?P=q2))*)
\s*%}""",re.X)

nv_reg=re.compile(r"""\s+
(?P<name>\w+)
\s*=\s*
(?P<value>(?P<q2>[\'"]?)[.\w]+(?P=q2))
""",re.X)

def url_kwargs(text,preview=1):
for old,new in [
(m.group(),'{%% url(%s,kwargs=dict(%s)) %%}'%(
m.group('viewfunc'),
','.join(['%s=%s'%(n.group('name'),n.group('value')) for n in re.finditer(nv_reg,m.group('kwargs'))]),
)
)
for m in re.finditer(url_kwargs_reg,text)
]:
if preview:
print('%s--->\n    %s'%(old,new))
else:
text=text.replace(old,new,1)
return text

url_args_reg=re.compile(r"""
{%\s*url\s+
(?P<viewfunc>((?P<q1>['"]?)[\w:.]+(?P=q1)))
(?P<args>(\s+(?P<q2>['"]?)[.\w]+(?P=q2))*)
\s*%}""",re.X)

def url_args(text,preview=1):
for old,new in [
(m.group(),'{%% url(%s,args=(%s,)) %%}'%(
m.group('viewfunc'),
','.join( m.group('args').split()),
)
)
for m in re.finditer(url_args_reg,text)
]:
if preview:
print('%s--->\n    %s'%(old,new))
else:
text=text.replace(old,new,1)
return text

if __name__=='__main__':
text="""
{% url viewname  first =fir   third=   "thi"    %}
{% url "viewname"  first =    fir%}
{% url 'viewname'  first =fir    second = 'sec'    third   ='thi'    %}
{% url 'funcname'  first second     'third'    %}
{% url "funcname"  first   "third"   %}
{% url funcname  first%}
"""
fs=[url_args,url_kwargs]
org(fs=fs,preview=0)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: