[英]How do i insert data into HTML from python script?
I have a html and python script. 我有一个HTML和python脚本。
I am calling html inside python script and e-mailing them. 我在python脚本中调用html并通过电子邮件发送它们。
This is my code: 这是我的代码:
# Build email message
import time
currentTime = time.ctime();
reportmessage = urllib.urlopen(Report.reportHTMLPath + "reporturl.html").read()
//Code to send e-mail
HTML code: HTML代码:
<div>
<b> Time is: <% currentTime %>
</div>
But that does not seem to be working. 但这似乎并没有奏效。
Can someone help me how I can insert time into HTML from python? 有人可以帮助我如何从python中将时间插入到HTML中吗? It's not just time, I have some other things to attach (href etc).
这不只是时间,我还有其他一些东西可以附加(href等)。
Thanks, 谢谢,
The simplest and not secure way is to use str.format
: 最简单且不安全的方法是使用
str.format
:
>>> import time
>>> currentTime = time.ctime()
>>>
>>> currentTime
'Fri Jul 1 06:50:37 2016'
>>> s = '''
<div>
<b> Time is {}</b>
</div>'''.format(currentTime)
>>>
>>> s
'\n<div>\n<b> Time is Fri Jul 1 06:50:37 2016</b>\n</div>'
But that's not the way I suggest to you, what I strongly recommend to you is to use jinja2 template rendering engine. 但这不是我建议你的方式,我强烈建议你使用jinja2模板渲染引擎。
Here is a simple code to work with it: 这是一个使用它的简单代码:
>>> import jinja2
>>> import os
>>>
>>> template_dir = os.path.join(os.path.dirname(__file__), 'templates')
>>> jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape=True)
>>> def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
So here you need to create a folder on your working directory called templates
, which will have your template, for example called CurrentTime.html
: 所以在这里你需要在工作目录中创建一个名为
templates
的文件夹,它将包含你的模板,例如名为CurrentTime.html
:
<div>
<b> Time is {{ currentTime }}</b>
Then simply: 那简单地说:
>>> import time
>>> currentTime = time.ctime()
>>>
>>> render_str('CurrentTime.html', currentTime=currentTime)
If you have large quantities of data to be inserted, template will be a good choice. 如果要插入大量数据,模板将是一个不错的选择。 If you really mind of using a template engine,
re
will be a lightweight solution. 如果你真的介意使用模板引擎,那么
re
将是一个轻量级的解决方案。
Here is a simple example: 这是一个简单的例子:
>>> import re
>>> html = '''
... <div>
... <b> Time is: <% currentTime %> </b>
... </div>
... '''
>>> result = re.sub(r'<% currentTime %>', '11:06', html)
>>> print(result)
<div>
<b> Time is: 11:06 </b>
</div>
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.