简体   繁体   中英

Python file.write within html tags

I'm just starting with Python, one of my first scripts is to be a very simple work log. I run it, when i finish work I press enter and it puts worktime into html file that I share with guy who hire me.

Here is the code, please do not facepalm too much, these are my first steps:

#!/usr/bin/python
import datetime
start = datetime.datetime.now()
startt = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print "Counting worktime started."
confirm = raw_input("Press enter when work finished ")
finish = datetime.datetime.now()
delta = finish - start
print datetime.datetime.now()
print delta.seconds
work_time=str(datetime.timedelta(seconds=delta.seconds))
finisht=str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
note = raw_input("What were you doing? ")
line1=['<span>','Work started: <b>', startt, '</b></span><br />']
line1f=' '.join(line1)
line2=['<span>','Work ended: <b>', finisht, '</b></span><br />']
line2f=' '.join(line2)
line3=['<span>','Work duration: <b>', work_time,'</b></span><br />']
line3f=' '.join(line3)
line4=['<span>','Note: <b>', note,'</b></span><br /><br />']
line4f=' '.join(line4)
with open("/srv/www/worklog.html","a") as worklog:
    worklog.write(line1f)
    worklog.write("\n")
    worklog.write(line2f)
    worklog.write("\n")
    worklog.write(line3f)
    worklog.write("\n")
    worklog.write(line4f)
    worklog.write("\n")
    worklog.write("<span> ========================= </span><br /><br />")
    worklog.write("\n")

and here is the worklog.html file:

<html>
<head></head>
<body style="background-color: #195B83;color:#FFF;margin: 0px;">
    <style>
        span {font-size: 12px;margin-left: 5px;}
        .logo {float: right;margin-right: 10px;margin-top:5px;}
        .first-div {background-color: #FFF; color:#195B83;width:100%;}
        .sec-div {margin-left: 5px;}
    </style>
    <div class="first-div">
        <img src="logo.png" class="logo" />
        <div class="sec-div">
            <h1>simple worklog 1.0</h2>
        </div>
    </div>
    <br />
    <span> ========================= </span><br /><br />
    <span> Work started: <b> 2014-09-11 13:40:26 </b></span> <br />
    <span> Work ended: <b> 2014-09-11 13:40:29 </b></span> <br />
    <span> Work duration: <b> 0:00:02 </b></span> <br />
    <span> Note: <b> Testing </b></span><br /><br />
    <span> ========================= </span><br /><br />

And it works!

My question is - how can I include

</body></html>

tags? I tried with .replace, but my experiments failed with whole file purged. Can you give me a hint on how to make this script to keep them at the end of worklog.html ?

EDIT:

Thanks to awesome hints below, I have rewritten the code and I think that now it has a lot more sense, you can find it here:

main_script (add log to csv and add data to the website): http://pastebin.com/ZbCqJ9p9

page_refresher (no worklog adding, just put the data on website): http://pastebin.com/3hi077RK

template (with bootstrap css): http://pastebin.com/xZ7VmE1U

data files format: http://pastebin.com/0KNAXuqh

and it looks like that: http://elysium.c-call.eu/sworklog/

It's surely not the highest class and has some issues, but it's a lot better than the piece of crap I came here with :)

Thank you very much.

I think a cleaner solution would be to slightly change your process.

Instead of logging directly to HTML file, you should consider storing your data (start time, and end time) into a CSV file (or a text file, or a SQLite database, or whatever you want). Python as a built-in library for working with CSV files .

Then, you can run another script that will grab the data, process it and produce a HTML page. Since you will be recreating the HTML page each time, you don't have to bother with inserting your new data at the right place in your HTML.

It's a good practice to separate data from presentation, because it makes it easier to reuse your data in various place. In this example, if you keep your data in a in a CSV file, you can also open it with a spreadsheet application and make fancy graphs and charts for your employer ;)

Do not reinvent the wheel by constructing HTML manually using string concatenation. This makes things less readable, explicit, more complicated, difficult to maintain, error-prone. There are specialized tools, that would make it so much easier and pleasant.

Consider using a template engine, like jinja2 or mako .

Basically, you would create an HTML template with placeholders, which would be filled with data while rendering.

Example using mako template engine.

  • consider you have a template named template.html with the following content:

     <!DOCTYPE html> <html> <head> <title>${title}</title> </head> <body> <span> Work started: ${work_time} </span> </body> </html> 
  • this is what your rendering code may look like:

     from datetime import date from mako.template import Template template = Template(filename='template.html') title = 'Test page' work_time = date.today() print template.render(title=title, work_time=work_time) 

It prints:

<!DOCTYPE html>
<html>
<head>
    <title>Test page</title>
</head>
<body>
    <span>
        Work started: 2014-09-11
    </span>
</body>
</html>

Or, alternatively, you can construct the HTML tag by tag inside the Python code.

Example using BeautifulSoup :

from bs4 import BeautifulSoup


soup = BeautifulSoup()
html = soup.new_tag(name='html')
body = soup.new_tag(name='body')

span = soup.new_tag(name="span")
span.append(soup.new_string('Work started:'))

body.append(span)
html.append(body)
soup.append(html)

print soup.prettify()

Prints:

<html>
 <body>
  <span>
   Work started:
  </span>
 </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM