如何解决Python中的CL-WHO:聪明还是愚蠢?
| 我不知道这是聪明还是愚蠢。我喜欢CL-WHO,也喜欢Python,所以我一直在想办法将两者融合在一起。我要说的是:tag(\"html\",lst(
tag(\"head\"),tag(\"body\",lst(
tag(\"h1\",\"This is the headline\"),tag(\"p\",\"This is the article\"),tag(\"a\",\"Click here for more\",[\"href\",\"http://Nowhere.com\"]))))))
并对此进行评估:
<html>
<head>
</head>
<body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p>
<a href=\"http://Nowhere.com\">Click here for more</a>
</p>
</body>
</html>
看起来就像CL-WHO,但带有功能符号而不是s表达式。所以我从这个标签生成功能开始:
def tag(name,inner=\"\",attribs=[],close=True):
ret = []
ret.append(\'<\' + name)
while attribs.__len__() > 0:
ret.append(\' %s=\"%s\"\' % (attribs.pop(0),attribs.pop(0)))
ret.append(\">\")
if type(inner).__name__ == \'list\':
ret.extend(inner)
else:
ret.append(inner)
if close:
ret.append(\'</%s>\' % name)
return \"\".join(ret)
内部可以是一个列表,而在所有的Lispy代码中,列表的方括号都很难看,所以我想要一个函数,该函数可以根据其参数创建一个列表:
def lst(*args):
return [x for x in args]
为了促进条件代码的生成,您需要一个if语句,该语句是一个求值为两个结果之一的函数,如Lisp所示,因此可以对其进行嵌套。强制性的流控制风格将无法实现。
def fif(cond,a,b):
if cond:
return a
else:
return b
维奥拉现在,您可以生成一个示例页面,如下所示:
def gen(x):
\"\"\"Sample function demonstratine conditional HTML generation. Looks just like CL-WHO!\"\"\"
return tag(\"html\",lst(
fif(x == 1,tag(\"h1\",\"No,THIS is the headline\")),\"http://Nowhere.com\"]))))))
print gen(1)
这开始崩溃的地方是循环。循环的任何内容都必须提取到单独的函数中。那你觉得呢?有趣还是愚蠢?试试看,告诉我您的想法。
解决方法
您应该对每个文本节点,属性值等进行html转义,否则html注入会被XSS咬住。
除了功能齐全的模板系统(mako,genhi,chameleon,jinja等)之外,与您做的工作更相似的库可能是lxml
>>> from lxml.html.builder import HTML,HEAD,BODY,H1,P,A
>>> from lxml.html import tostring
>>>
>>> h = HTML(
... HEAD(
... BODY(
... H1(\'This is the headline\'),... P(\'This is the article\'),... P(
... A(\'Click here for more\',href=\'http://nowhere.com\')))))
>>> print tostring(h,pretty_print=True)
<html><head><body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p><a href=\"http://nowhere.com\">Click here for more</a></p>
</body></head></html>
您可以使用三元运算符
H1(\"This is the headline\" if x==1 else \"No,THIS is the headline\")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。