TechnoCorner
TechnoCorner

Reputation: 5165

How do i insert data into HTML from python script?

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,

Upvotes: 0

Views: 5284

Answers (2)

Karlind E
Karlind E

Reputation: 11

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>

>>> 

Upvotes: 1

Iron Fist
Iron Fist

Reputation: 10961

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)

Upvotes: 2

Related Questions