Files
cardio/db.py
2023-01-22 09:59:39 +11:00

37 lines
1.1 KiB
Python

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)