Skip to content

Commit 5f11bf3

Browse files
committed
Externalized some database connection code into db.py.
1 parent c0fb7fe commit 5f11bf3

File tree

2 files changed

+37
-26
lines changed

2 files changed

+37
-26
lines changed

db.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import json
2+
import os
3+
import psycopg2
4+
import urlparse
5+
6+
# Open DB connection
7+
url = urlparse.urlparse(os.environ["DATABASE_URL"])
8+
conn = psycopg2.connect(
9+
database=url.path[1:],
10+
user=url.username,
11+
password=url.password,
12+
host=url.hostname,
13+
port=url.port
14+
)
15+
cur = conn.cursor()
16+
cur.execute("""CREATE TABLE IF NOT EXISTS obdreadings(vehicleid TEXT, unix_timestamp BIGINT, latitude DECIMAL(11,8), longitude DECIMAL(11,8), readings JSON);""")
17+
print('Database ready to go!')
18+
19+
20+
def put(json_data):
21+
cur.execute("""INSERT INTO obdreadings(vehicleid, unix_timestamp, latitude, longitude, readings)
22+
VALUES(%s, %s, %s, %s, %s);""",
23+
(json_data['vehicleid'], json_data['timestamp'], json_data['latitude'], json_data['longitude'],
24+
json.dumps(json_data['readings'])))
25+
conn.commit()
26+
27+
28+
def getCur():
29+
return cur

server.py

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,13 @@
11
import json
22
import os
3-
import psycopg2
4-
import urlparse
5-
from flask import Flask, request, Response
3+
from flask import Flask, request, Response, jsonify
64

5+
# Import the database
6+
import db
77

88
app = Flask(__name__)
99

1010

11-
# Open DB connection
12-
url = urlparse.urlparse(os.environ["DATABASE_URL"])
13-
conn = psycopg2.connect(
14-
database=url.path[1:],
15-
user=url.username,
16-
password=url.password,
17-
host=url.hostname,
18-
port=url.port
19-
)
20-
cur = conn.cursor()
21-
cur.execute("""CREATE TABLE IF NOT EXISTS obdreadings(vehicleid TEXT, unix_timestamp BIGINT, latitude DECIMAL(11,8), longitude DECIMAL(11,8), readings JSON);""")
22-
print('Database ready to go!')
23-
24-
2511
@app.route('/', methods=['GET', 'POST', 'PUT'])
2612
def home():
2713
# Handle GET
@@ -37,11 +23,7 @@ def home():
3723
print str(json_data)
3824

3925
# Store it in the DB
40-
cur.execute("""INSERT INTO obdreadings(vehicleid, unix_timestamp, latitude, longitude, readings)
41-
VALUES(%s, %s, %s, %s, %s);""",
42-
(json_data['vehicleid'], json_data['timestamp'], json_data['latitude'], json_data['longitude'],
43-
json.dumps(json_data['readings'])))
44-
conn.commit()
26+
db.put(json_data)
4527

4628
# Send okie-dokie response
4729
return Response(status=200)
@@ -50,17 +32,17 @@ def home():
5032
@app.route('/view')
5133
def view_ids():
5234
# Get a list of all stored vehicleids
53-
cur.execute("""SELECT DISTINCT vehicleid FROM obdreadings;""")
35+
db.getCur().execute("""SELECT DISTINCT vehicleid FROM obdreadings;""")
5436

5537
# Return vin list
56-
return 'Available VIN records: {}'.format(str(cur.fetchall()));
38+
return 'Available VIN records: {}'.format(str(db.getCur().fetchall()));
5739

5840

5941
@app.route('/view/<vehicleid>')
6042
def view_id(vehicleid):
6143
# Get the vehicleid records from the database
62-
cur.execute("""SELECT * FROM obdreadings WHERE vehicleid=%s""", (vehicleid,))
63-
return str(cur.fetchall());
44+
db.getCur().execute("""SELECT * FROM obdreadings WHERE vehicleid=%s;""", (vehicleid,))
45+
return str(db.getCur().fetchall());
6446

6547

6648
if __name__ == '__main__':

0 commit comments

Comments
 (0)