Store cadence values in database

This commit is contained in:
Peter Stockings
2023-01-22 09:59:39 +11:00
parent dfc1988a88
commit 56069547c3
2 changed files with 40 additions and 0 deletions

36
db.py Normal file
View File

@@ -0,0 +1,36 @@
import os
import psycopg2
from psycopg2.extras import RealDictCursor
from urllib.parse import urlparse
class DataBase():
def __init__(self, app):
db_url = urlparse(os.environ['DATABASE_URL'])
self.conn = psycopg2.connect(
database=db_url.path[1:],
user=db_url.username,
password=db_url.password,
host=db_url.hostname,
port=db_url.port
)
def execute(self, query, args=(), one=False, commit=False):
cur = self.conn.cursor(cursor_factory=RealDictCursor)
cur.execute(query, args)
rv = None
if cur.description is not None:
rv = cur.fetchall()
if commit:
try:
self.conn.commit()
except:
self.conn.rollback()
cur.close()
return (rv[0] if rv else None) if one else rv
def insert_cadence(self, rpm, device_id):
self.execute('INSERT INTO cadence (rpm, device_id) VALUES (%s)',
[rpm, device_id], commit=True, one=True)