· 7 years ago · Dec 01, 2018, 06:08 AM
1#!/bin/python
2
3 # dynamically inserting data into the database
4
5 # import libraries
6 import time
7 import datetime
8 import random
9 import sqlite3
10
11 from flask import Flask, g, render_template
12
13 # import python script that parses and saves uptime result
14 import parse_and_save
15 from parse_and_save import uptime
16
17 test = uptime()
18
19 # establish connection to sqlite db and save uptime to database
20 conn = sqlite3.connect('dynamicdata.db')
21 c = conn.cursor()
22
23 def create_table():
24 c.execute("CREATE TABLE IF NOT EXISTS mytesttable(uptime TEXT,
25 datestamp TEXT)")
26
27 def dynamic_data_entry():
28 uptime = test
29 unix = int(time.time())
30 date =
31 str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
32
33 c.execute("INSERT INTO mytesttable (uptime, datestamp) VALUES (?, ?)",
34 (uptime, date))
35
36 conn.commit()
37
38 # create the table - commented as executed only once
39 # create_table()
40 dynamic_data_entry()
41
42 # read from db and query the results
43 def read_from_db():
44 c.execute('SELECT * FROM mytesttable')
45 data = c.fetchall()
46 print(data)
47 for row in data:
48 print(row)
49
50 # run the read db function
51 read_from_db()
52
53 ####### FLASK ########
54 app = Flask(__name__)
55
56 @app.route('/')
57 def index():
58 c.execute('SELECT * FROM mytesttable')
59 return render_template('index.html')
60
61 if __name__ == '__main__':
62 app.run(debug=True)
63
64
65 # close db connections
66 c.close
67 conn.close()
68
69<!DOCTYPE html>
70<html>
71 <head>
72<title>Log Information</title>
73</head>
74 <body>
75 <h1>Log Information</h1>
76 <p style="color:blue;">information captured as of now</p>
77<table style="width:100%">
78 <tr>
79 <th style="text-align:left;">uptime</th>
80 <th style="text-align:left;">timestamp</th>
81 </tr>
82 <tr>
83 <td>16 days</td>
84 <td>2018-11-30 11:12:28</td>
85 </tr>
86 </table>
87 </body>
88 </html>