I have a html and python script.
I am calling html inside python script and e-mailing them.
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:
<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? It's not just time, I have some other things to attach (href etc).
Thanks,
-
check a template injection like Cheetah [cheetahtemplate.org/]PepperoniPizza– PepperoniPizza2016年07月01日 00:21:14 +00:00Commented Jul 1, 2016 at 0:21
-
I'm quite new to python. I will check how to import cheetahtemplate thanks @PepperoniPizzaTechnoCorner– TechnoCorner2016年07月01日 00:23:42 +00:00Commented Jul 1, 2016 at 0:23
-
I don't have cheetah.. How do i install it? I'm quite confused here. Can you provide a sample exampleTechnoCorner– TechnoCorner2016年07月01日 00:30:03 +00:00Commented Jul 1, 2016 at 0:30
-
most of these things are not gonna be available in the built-in Python. Try: blog.infoentropy.com/….PepperoniPizza– PepperoniPizza2016年07月01日 00:32:33 +00:00Commented Jul 1, 2016 at 0:32
2 Answers 2
The simplest and not secure way is to use 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.
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:
<div>
<b> Time is {{ currentTime }}</b>
Then simply:
>>> import time
>>> currentTime = time.ctime()
>>>
>>> render_str('CurrentTime.html', currentTime=currentTime)
Comments
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.
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>
>>>