在Pyramid中,如何从视图返回原始HTML?
我刚接触Pyramid框架(其实我对网页框架都不太熟悉)。
我想做到的是从一个视图中返回原始的HTML,这样我就可以把从我的MongoDB数据库中获取的数据进行标记。
我的Pyramid项目中的__init__.py
文件是标准的:
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(root_factory = Root, settings = settings)
config.add_view('hermesweb.views.my_view',
context = 'hermesweb:resources.Root',
renderer = 'hermesweb:templates/mytemplate.pt')
config.add_static_view('static', 'hermesweb:static', cache_max_age = 3600)
views.myDB = connect() # connect to my mongoDB
我的templates/mytemplate.pt
文件看起来是这样的:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal">
<head><title>My test title. . . </title></head>
<body>
<div>
<h2>Perform a search</h2>
<form method="GET" action="">
<div>
<input type="text" name="id"/>
</div>
<input type="submit" value="Submit"/>
</form>
<h2>Results</h2>
${results}
</div>
</body
<html>
最后,我的views.py
文件是这样的:
myDB = "" # ref to the database is assigned on startup.
def my_view(request):
key = request.GET.get('id', None)
results = ""
if key:
db_res = myDB.call_some_find_function(key)
for data in db_res:
results = "%s <li> %s </li>" % (results, data)
results = "<ul> %s </ul>" % results
return {'results': results}
当我在表单中输入一个词,然后调用my_view
函数时,数据库会被查询并且正确的结果会被提取出来。不过,返回的字符串在网页上并没有变成HTML,而是直接以字符串的形式显示在网页上。
我怀疑这可能和内容类型有关?但我对Pyramid还不够了解。有没有人能解释一下,怎么才能让这个返回的内容被浏览器识别为HTML,而不是仅仅作为字符串显示?
额外的问题 - 我是否应该在views.py
中处理这种数据库调用?我对整个Root对象的作用还是有点困惑。我正在使用MongoDB作为数据库后端……
2 个回答
这个字符串正在被转义,这是为了防止恶意代码被插入到你的网站中,默认情况下,模板中插入的字符串都会这样处理。如果你想把这个字符串标记为安全的,就需要把它标记为字面量,这样它就不会被转义了。我记得Pyramid(就像Pylons一样)自带了webhelpers模块,所以你可以导入literal函数:
from webhelpers.html import literal
然后把你最后的结果赋值替换成:
results = literal("<ul> %s </ul>" %results)
如果literal函数没有随Pyramid一起提供,正如我猜测的那样,可以看看这篇帖子: Python Pyramid & Chameleon模板语言转义html
补充:注意,为了安全起见,你应该在把数据库中的数据输入到html之前先对其进行转义。你可以使用cgi.escape
来做到这一点。
为了防止Chameleon把${result}
这个变量搞错,你需要使用${structure: result}
。具体的说明可以参考这份文档:http://chameleon.readthedocs.org/en/latest/reference.html#structure