initial commit
This commit is contained in:
84
tommorow.py
Normal file
84
tommorow.py
Normal file
@@ -0,0 +1,84 @@
|
||||
import requests
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
|
||||
def insert_dynamic_price_data_tomorrow():
|
||||
connection = None # Connection buiten de try initialiseren
|
||||
|
||||
try:
|
||||
# URL van de API
|
||||
url = "https://enever.nl/api/stroomprijs_morgen.php?token=5a7d9b371fe147cfc8100bcf6d9ebd55"
|
||||
response = requests.get(url)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception('Fout bij het ophalen van de data.')
|
||||
|
||||
data = response.json()
|
||||
|
||||
if data is None or 'data' not in data:
|
||||
raise Exception('Fout bij het decoderen van de JSON-data.')
|
||||
|
||||
# Verbinden met de MySQL-database
|
||||
connection = mysql.connector.connect(
|
||||
host='127.0.0.1', # Gebruik 127.0.0.1 ipv localhost
|
||||
database='alfen',
|
||||
user='alfen_user',
|
||||
password='5uVgr%f%s2P5GR@3q!',
|
||||
port=3307
|
||||
)
|
||||
|
||||
if connection.is_connected():
|
||||
cursor = connection.cursor()
|
||||
|
||||
# Verwijder bestaande records uit de tabel
|
||||
cursor.execute("DELETE FROM dynamic_price_data_tommorow")
|
||||
connection.commit()
|
||||
|
||||
# Voorbereiding van de query
|
||||
query = """
|
||||
INSERT INTO dynamic_price_data_tommorow (datetime, price)
|
||||
VALUES (%s, %s)
|
||||
"""
|
||||
|
||||
# Sleutelwoorden voor prijsvelden
|
||||
price_fields = [
|
||||
'prijsAA', 'prijsAIP', 'prijsANWB', 'prijsBE', 'prijsEE',
|
||||
'prijsEN', 'prijsEVO', 'prijsEZ', 'prijsFR', 'prijsGSL',
|
||||
'prijsMDE', 'prijsNE', 'prijsTI', 'prijsVDB', 'prijsVON',
|
||||
'prijsWE', 'prijsZG', 'prijsZP'
|
||||
]
|
||||
|
||||
# Data invoegen
|
||||
for entry in data['data']:
|
||||
datetime = entry['datum']
|
||||
|
||||
# Gemiddelde prijs berekenen (exclusief het veld 'prijs')
|
||||
prices = [
|
||||
float(entry[field]) for field in price_fields if field in entry and entry[field] != ''
|
||||
]
|
||||
if prices:
|
||||
avg_price = sum(prices) / len(prices)
|
||||
else:
|
||||
avg_price = None # Geen prijzen beschikbaar
|
||||
|
||||
# Data invoegen in de tabel
|
||||
if avg_price is not None:
|
||||
try:
|
||||
cursor.execute(query, (datetime, avg_price))
|
||||
connection.commit()
|
||||
except Error as e:
|
||||
print(f"Fout bij invoeren van data voor datetime {datetime}: {e}")
|
||||
continue
|
||||
|
||||
except Error as e:
|
||||
print(f"Fout bij databaseverbinding: {e}")
|
||||
except Exception as e:
|
||||
print(f"Algemene fout: {e}")
|
||||
finally:
|
||||
# Sluit de verbinding
|
||||
if connection is not None and connection.is_connected():
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
insert_dynamic_price_data_tomorrow()
|
||||
Reference in New Issue
Block a user