aboutsummaryrefslogtreecommitdiffstats
path: root/elvia2pgsql.py
diff options
context:
space:
mode:
Diffstat (limited to 'elvia2pgsql.py')
-rwxr-xr-xelvia2pgsql.py37
1 files changed, 5 insertions, 32 deletions
diff --git a/elvia2pgsql.py b/elvia2pgsql.py
index 4ed2430..be5eaae 100755
--- a/elvia2pgsql.py
+++ b/elvia2pgsql.py
@@ -1,26 +1,23 @@
-#!/bin/python3
+#!/usr/bin/env python3
+''' elvia2pgsql '''
import os
import sys
-import json
-import psycopg2
import requests
from datetime import datetime
from datetime import timedelta
from tzlocal import get_localzone
+from common import dbi
apiKey = os.environ['el_elvia_token']
apiUrl = "https://elvia.azure-api.net/customer/metervalues/api/v1/metervalues"
-pg_db = os.environ['el_pg_db']
-pg_host = os.environ['el_pg_host']
pg_table = "elvia"
startTime = datetime.now(get_localzone()) - timedelta(days = 2)
startTime = startTime.isoformat('T')
-
endTime = datetime.now(get_localzone()).isoformat('T')
@@ -55,30 +52,6 @@ for item in data['meteringpoints'][0]['metervalue']['timeSeries']:
if item['verified']:
values.append((data['meteringpoints'][0]['meteringPointId'], item['startTime'], item['endTime'], item['value'], item['uom'], item['production']))
-# connect to database
-conn = psycopg2.connect(database=pg_db, host=pg_host)
-cur = conn.cursor()
-
-# count rows before we start
-cur.execute("SELECT COUNT(*) FROM " + pg_table)
-before = cur.fetchone()
-
-# insert data
-try:
- cur.executemany("INSERT INTO " + pg_table + " VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT (startTime,endTime) DO NOTHING", values)
- conn.commit()
-except Exception as e:
- conn.rollback()
- raise e
-
-# count rows after we finnish
-cur.execute("SELECT COUNT(*) FROM " + pg_table)
-after = cur.fetchone()
-
-# count *new* rows
-newRows = after[0] - before[0]
-
-# close connection
-conn.close()
-print("Successfully inserted " + str(newRows) + " records into the database")
+# Count new rows and insert
+dbi("INSERT INTO " + pg_table + " VALUES(%s,%s,%s,%s,%s,%s) ON CONFLICT (startTime,endTime) DO NOTHING", values, verbose=True)