Python file.write in html tags

I'm just getting started with Python, one of my first scripts is a very simple work log. I run it, when I finish, I press enter and it puts the workspace in an html file that I share with the guy who hires me.

Here is the code, please don't go too hard on facepalm, 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 to enable

</body></html>

      

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

EDIT:

Thanks to the awesome hints below, I rewrote the code and I think it makes a lot more sense now, you can find it here:

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

page_refresher (no additional stuff added, just put the data on the website): http://pastebin.com/3hi077RK

(with css loaded): http://pastebin.com/xZ7VmE1U

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

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

This is certainly not the highest grade and has some problems, but it is much better than the piece of crap I came in here :)

Many thanks.

+3


source to share


2 answers


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

Instead of writing directly to an HTML file, you should consider storing your data (start and end times) in a CSV file (or text file or SQLite database or whatever). 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 create an HTML page. Since you will be re-creating the HTML page every time, you don't have to worry about inserting new data at the right place in your HTML.

It is good practice to separate data from presentation as it makes it easier to reuse your data in different places. In this example, if you save your data to a CSV file, you can also open it with a spreadsheet application and make graphical charts and charts for your employer;)

+4


source


Don't reinvent the wheel by creating by HTML

hand using string concatenation. This makes things less readable, explicit, more complex, more difficult to maintain, and error prone. There are specialized tools that would make it much easier and more enjoyable.

Consider using a templating engine like jinja2

or mako

.

Basically, you should create an HTML template with placeholders that will be populated with data when rendered.

An example using the template engine mako

.

  • Consider that 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 looks 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 create an HTML tag from a tag inside Python code.

Usage example 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()

      

Printing

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

      

+2


source







All Articles