如何在html中显示python变量的值(在这种情况下,它是我的Entity类的键)?
from google.appengine.ext import db
class Entity(db.Expando):
pass
e = Entity()
e.put() # id is assigned
k = e.key() # key is complete
id = k.id() # system assigned id
html='''
Key: %(k)
'''
解决方法:
from google.appengine.ext import db
import cgi
class Entity(db.Expando):
pass
e = Entity()
e.put() # id is assigned
k = e.key() # key is complete
id = k.id() # system assigned id
html="""
Key: %s
""" % (cgi.escape(k))
我会认真地建议你使用模板虽然它让你的生活更轻松.
使用模板,您的解决方案将是这样的:
class Entity(db.Expando):
pass
e = Entity()
e.put() # id is assigned
k = e.key() # key is complete
id = k.id() # system assigned id
template = jinja_environment.get_template('templates/myTemplate')
self.response.write(template.render({'key_val':k}))
并且Mytemplate.html文件看起来像:
{{key_val}}
标签:html,python,google-app-engine
本文介绍了如何在HTML页面中正确显示来自Python的变量值,并通过示例展示了如何使用cgi.escape来转义变量值以防止HTML注入。此外还推荐了使用Jinja模板引擎来简化这一过程。

被折叠的 条评论
为什么被折叠?



