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