From d86413ad81135454df7ef1c7d7faeb52eb51efa8 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Wed, 1 Feb 2023 12:24:22 +0100 Subject: adding some common stuff, less code replica --- elvia_gridtariff2pgsql.py | 38 ++++++-------------------------------- 1 file changed, 6 insertions(+), 32 deletions(-) (limited to 'elvia_gridtariff2pgsql.py') diff --git a/elvia_gridtariff2pgsql.py b/elvia_gridtariff2pgsql.py index b6b423b..bcf4bd7 100755 --- a/elvia_gridtariff2pgsql.py +++ b/elvia_gridtariff2pgsql.py @@ -1,15 +1,15 @@ -#!/bin/python3 +#!/usr/bin/python3 +''' get grid tariffs''' import os import sys -import json -import psycopg2 -import requests - from datetime import datetime from datetime import timedelta +import requests from tzlocal import get_localzone +from common import dbi + # API documentation: https://elvia.portal.azure-api.net/docs/services/gridtariffapi/operations/post-digin-api-v-tariffquery-meteringpointsgridtariffs? apiKey = os.environ['el_elvia_grid_api_key'] @@ -66,30 +66,4 @@ values = [] for item in data['gridTariffCollections'][0]['gridTariff']['tariffPrice']['hours']: values.append((meteringPointId, item['startTime'], item['expiredAt'], item['shortName'], item['isPublicHoliday'], item['energyPrice']['total'], item['energyPrice']['totalExVat'])) -# 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,%s) ON CONFLICT (meteringPointId,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") +dbi("INSERT INTO " + pg_table + " VALUES(%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (meteringPointId,startTime,endTime) DO NOTHING", values, verbose=True) -- cgit v1.2.3