update enever API url
This commit is contained in:
65
dynamic.py
65
dynamic.py
@@ -3,22 +3,23 @@ import mysql.connector
|
|||||||
from mysql.connector import Error
|
from mysql.connector import Error
|
||||||
|
|
||||||
def insert_dynamic_price_data():
|
def insert_dynamic_price_data():
|
||||||
connection = None # Connection buiten de try initialiseren
|
connection = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
url = "https://enever.nl/api/stroomprijs_vandaag.php?token=5a7d9b371fe147cfc8100bcf6d9ebd55"
|
# 1. Data ophalen van de API
|
||||||
|
url = "https://enever.nl/apiv3/stroomprijs_vandaag.php?token=5a7d9b371fe147cfc8100bcf6d9ebd55"
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
raise Exception('Fout bij het ophalen van de data.')
|
raise Exception(f"Fout bij het ophalen van de data. Statuscode: {response.status_code}")
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
|
|
||||||
if data is None:
|
if not data or 'data' not in data:
|
||||||
raise Exception('Fout bij het decoderen van de JSON-data.')
|
raise Exception('Geen geldige data gevonden in de JSON-respons.')
|
||||||
|
|
||||||
|
# 2. Verbinding maken met MySQL
|
||||||
connection = mysql.connector.connect(
|
connection = mysql.connector.connect(
|
||||||
host='127.0.0.1', # Gebruik 127.0.0.1 ipv localhost
|
host='127.0.0.1',
|
||||||
database='alfen',
|
database='alfen',
|
||||||
user='alfen_user',
|
user='alfen_user',
|
||||||
password='5uVgr%f%s2P5GR@3q!',
|
password='5uVgr%f%s2P5GR@3q!',
|
||||||
@@ -28,53 +29,53 @@ def insert_dynamic_price_data():
|
|||||||
if connection.is_connected():
|
if connection.is_connected():
|
||||||
cursor = connection.cursor()
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
# Query met ON DUPLICATE KEY UPDATE
|
||||||
query = """
|
query = """
|
||||||
INSERT INTO dynamic_price_data (datetime, provider_code, price)
|
INSERT INTO dynamic_price_data (datetime, provider_code, price)
|
||||||
VALUES (%s, %s, %s)
|
VALUES (%s, %s, %s)
|
||||||
ON DUPLICATE KEY UPDATE price = %s
|
ON DUPLICATE KEY UPDATE price = VALUES(price)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Mapping van Provider Code (DB) naar Veldnaam (API)
|
||||||
providers = {
|
providers = {
|
||||||
'AA': 'prijsAA',
|
'AA': 'prijsAA', 'AIP': 'prijsAIP', 'ANWB': 'prijsANWB',
|
||||||
'AIP': 'prijsAIP',
|
'BE': 'prijsBE', 'EE': 'prijsEE', 'EN': 'prijsEN',
|
||||||
'ANWB': 'prijsANWB',
|
'EVO': 'prijsEVO', 'EZ': 'prijsEZ', 'FR': 'prijsFR',
|
||||||
'BE': 'prijsBE',
|
'GSL': 'prijsGSL', 'MDE': 'prijsMDE', 'NE': 'prijsNE',
|
||||||
'EE': 'prijsEE',
|
'TI': 'prijsTI', 'VDB': 'prijsVDB', 'VON': 'prijsVON',
|
||||||
'EN': 'prijsEN',
|
'WE': 'prijsWE', 'ZG': 'prijsZG', 'ZP': 'prijsZP'
|
||||||
'EVO': 'prijsEVO',
|
|
||||||
'EZ': 'prijsEZ',
|
|
||||||
'FR': 'prijsFR',
|
|
||||||
'GSL': 'prijsGSL',
|
|
||||||
'MDE': 'prijsMDE',
|
|
||||||
'NE': 'prijsNE',
|
|
||||||
'TI': 'prijsTI',
|
|
||||||
'VDB': 'prijsVDB',
|
|
||||||
'VON': 'prijsVON',
|
|
||||||
'WE': 'prijsWE',
|
|
||||||
'ZG': 'prijsZG',
|
|
||||||
'ZP': 'prijsZP'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
count = 0
|
||||||
for entry in data['data']:
|
for entry in data['data']:
|
||||||
datetime = entry['datum']
|
# FIX: Verwijder de 'T' en de tijdzone (+02:00) voor MySQL compatibiliteit
|
||||||
|
# Voorbeeld: '2026-03-30T00:00:00+02:00' -> '2026-03-30 00:00:00'
|
||||||
|
raw_dt = entry['datum']
|
||||||
|
clean_dt = raw_dt.replace('T', ' ').split('+')[0]
|
||||||
|
|
||||||
for code, price_field in providers.items():
|
for code, price_field in providers.items():
|
||||||
if price_field in entry:
|
if price_field in entry:
|
||||||
price = entry[price_field]
|
price = entry[price_field]
|
||||||
try:
|
try:
|
||||||
cursor.execute(query, (datetime, code, price, price))
|
cursor.execute(query, (clean_dt, code, price))
|
||||||
connection.commit()
|
count += 1
|
||||||
except Error as e:
|
except Error as e:
|
||||||
print(f"Fout bij invoeren van data voor provider {code}: {e}")
|
print(f"Fout bij klaarzetten data voor {code} op {clean_dt}: {e}")
|
||||||
continue
|
|
||||||
|
# 3. Alles in één keer committen voor betere performance
|
||||||
|
connection.commit()
|
||||||
|
print(f"Succesvol {count} records verwerkt/bijgewerkt.")
|
||||||
|
|
||||||
except Error as e:
|
except Error as e:
|
||||||
print(f"Fout bij databaseverbinding: {e}")
|
print(f"Databasefout: {e}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Algemene fout: {e}")
|
print(f"Algemene fout: {e}")
|
||||||
finally:
|
finally:
|
||||||
|
# Netjes afsluiten
|
||||||
if connection is not None and connection.is_connected():
|
if connection is not None and connection.is_connected():
|
||||||
cursor.close()
|
cursor.close()
|
||||||
connection.close()
|
connection.close()
|
||||||
|
print("Databaseverbinding gesloten.")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
insert_dynamic_price_data()
|
insert_dynamic_price_data()
|
||||||
|
|||||||
80
dynamic.py.prev
Normal file
80
dynamic.py.prev
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import requests
|
||||||
|
import mysql.connector
|
||||||
|
from mysql.connector import Error
|
||||||
|
|
||||||
|
def insert_dynamic_price_data():
|
||||||
|
connection = None # Connection buiten de try initialiseren
|
||||||
|
|
||||||
|
try:
|
||||||
|
url = "https://enever.nl/apiv3/stroomprijs_vandaag.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:
|
||||||
|
raise Exception('Fout bij het decoderen van de JSON-data.')
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
query = """
|
||||||
|
INSERT INTO dynamic_price_data (datetime, provider_code, price)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON DUPLICATE KEY UPDATE price = %s
|
||||||
|
"""
|
||||||
|
|
||||||
|
providers = {
|
||||||
|
'AA': 'prijsAA',
|
||||||
|
'AIP': 'prijsAIP',
|
||||||
|
'ANWB': 'prijsANWB',
|
||||||
|
'BE': 'prijsBE',
|
||||||
|
'EE': 'prijsEE',
|
||||||
|
'EN': 'prijsEN',
|
||||||
|
'EVO': 'prijsEVO',
|
||||||
|
'EZ': 'prijsEZ',
|
||||||
|
'FR': 'prijsFR',
|
||||||
|
'GSL': 'prijsGSL',
|
||||||
|
'MDE': 'prijsMDE',
|
||||||
|
'NE': 'prijsNE',
|
||||||
|
'TI': 'prijsTI',
|
||||||
|
'VDB': 'prijsVDB',
|
||||||
|
'VON': 'prijsVON',
|
||||||
|
'WE': 'prijsWE',
|
||||||
|
'ZG': 'prijsZG',
|
||||||
|
'ZP': 'prijsZP'
|
||||||
|
}
|
||||||
|
|
||||||
|
for entry in data['data']:
|
||||||
|
datetime = entry['datum']
|
||||||
|
for code, price_field in providers.items():
|
||||||
|
if price_field in entry:
|
||||||
|
price = entry[price_field]
|
||||||
|
try:
|
||||||
|
cursor.execute(query, (datetime, code, price, price))
|
||||||
|
connection.commit()
|
||||||
|
except Error as e:
|
||||||
|
print(f"Fout bij invoeren van data voor provider {code}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
except Error as e:
|
||||||
|
print(f"Fout bij databaseverbinding: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Algemene fout: {e}")
|
||||||
|
finally:
|
||||||
|
if connection is not None and connection.is_connected():
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
insert_dynamic_price_data()
|
||||||
30
tommorow.py
30
tommorow.py
@@ -7,15 +7,16 @@ def insert_dynamic_price_data_tomorrow():
|
|||||||
connection = None
|
connection = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Bepaal de datum van morgen (bijv. '2026-01-25')
|
# 1. Bepaal de datum van morgen (bijv. '2026-03-31')
|
||||||
tomorrow_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
|
tomorrow_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
|
||||||
print(f"Filteren op data voor: {tomorrow_date}")
|
print(f"Filteren op data voor: {tomorrow_date}")
|
||||||
|
|
||||||
# 2. Data ophalen
|
# 2. Data ophalen
|
||||||
url = "https://enever.nl/api/stroomprijs_morgen.php?token=5a7d9b371fe147cfc8100bcf6d9ebd55"
|
url = "https://enever.nl/apiv3/stroomprijs_morgen.php?token=5a7d9b371fe147cfc8100bcf6d9ebd55"
|
||||||
|
# Let op: De API voor morgen geeft vaak pas na 15:00 uur resultaat
|
||||||
response = requests.get(url)
|
response = requests.get(url)
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
raise Exception('Fout bij het ophalen van de data.')
|
raise Exception(f'Fout bij het ophalen van de data. Status: {response.status_code}')
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if not data or 'data' not in data:
|
if not data or 'data' not in data:
|
||||||
@@ -46,25 +47,35 @@ def insert_dynamic_price_data_tomorrow():
|
|||||||
for entry in data['data']:
|
for entry in data['data']:
|
||||||
# Controleer of de datum in de API begint met de datum van morgen
|
# Controleer of de datum in de API begint met de datum van morgen
|
||||||
if entry['datum'].startswith(tomorrow_date):
|
if entry['datum'].startswith(tomorrow_date):
|
||||||
prices = [float(entry[f]) for f in price_fields if f in entry and entry[f] != '']
|
# FIX: Maak de datum string schoon voor MySQL (T en tijdzone verwijderen)
|
||||||
|
clean_dt = entry['datum'].replace('T', ' ').split('+')[0]
|
||||||
|
|
||||||
|
# Verzamel prijzen en zet ze om naar floats
|
||||||
|
prices = []
|
||||||
|
for f in price_fields:
|
||||||
|
if f in entry and entry[f] is not None and entry[f] != '':
|
||||||
|
try:
|
||||||
|
prices.append(float(entry[f]))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
if prices:
|
if prices:
|
||||||
avg_price = sum(prices) / len(prices)
|
avg_price = sum(prices) / len(prices)
|
||||||
rows_to_insert.append((entry['datum'], avg_price))
|
rows_to_insert.append((clean_dt, avg_price))
|
||||||
|
|
||||||
# 5. Database bijwerken
|
# 5. Database bijwerken
|
||||||
if rows_to_insert:
|
if rows_to_insert:
|
||||||
# Wis de tabel
|
# Wis de tabel voor morgen (zodat je altijd de meest recente data hebt)
|
||||||
cursor.execute("DELETE FROM dynamic_price_data_tommorow")
|
cursor.execute("DELETE FROM dynamic_price_data_tommorow")
|
||||||
|
|
||||||
# Voeg alleen de gefilterde rijen toe
|
# Gebruik executemany voor snelheid
|
||||||
query = "INSERT INTO dynamic_price_data_tommorow (datetime, price) VALUES (%s, %s)"
|
query = "INSERT INTO dynamic_price_data_tommorow (datetime, price) VALUES (%s, %s)"
|
||||||
cursor.executemany(query, rows_to_insert)
|
cursor.executemany(query, rows_to_insert)
|
||||||
|
|
||||||
connection.commit()
|
connection.commit()
|
||||||
print(f"Succes! {len(rows_to_insert)} rijen toegevoegd voor {tomorrow_date}.")
|
print(f"Succes! {len(rows_to_insert)} rijen toegevoegd voor {tomorrow_date}.")
|
||||||
else:
|
else:
|
||||||
print(f"Geen data gevonden voor {tomorrow_date} in de API-respons.")
|
print(f"Geen data gevonden voor {tomorrow_date} in de API-respons. (Dit is normaal voor 15:00u)")
|
||||||
|
|
||||||
except Error as e:
|
except Error as e:
|
||||||
print(f"Database fout: {e}")
|
print(f"Database fout: {e}")
|
||||||
@@ -74,6 +85,7 @@ def insert_dynamic_price_data_tomorrow():
|
|||||||
if connection and connection.is_connected():
|
if connection and connection.is_connected():
|
||||||
cursor.close()
|
cursor.close()
|
||||||
connection.close()
|
connection.close()
|
||||||
|
print("Verbinding gesloten.")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
insert_dynamic_price_data_tomorrow()
|
insert_dynamic_price_data_tomorrow()
|
||||||
|
|||||||
79
tommorow.py.prev
Normal file
79
tommorow.py.prev
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import requests
|
||||||
|
import mysql.connector
|
||||||
|
from mysql.connector import Error
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
def insert_dynamic_price_data_tomorrow():
|
||||||
|
connection = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Bepaal de datum van morgen (bijv. '2026-01-25')
|
||||||
|
tomorrow_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
|
||||||
|
print(f"Filteren op data voor: {tomorrow_date}")
|
||||||
|
|
||||||
|
# 2. Data ophalen
|
||||||
|
url = "https://enever.nl/apiv3/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 not data or 'data' not in data:
|
||||||
|
raise Exception('Geen data gevonden in API respons.')
|
||||||
|
|
||||||
|
# 3. Verbinden met MySQL
|
||||||
|
connection = mysql.connector.connect(
|
||||||
|
host='127.0.0.1',
|
||||||
|
database='alfen',
|
||||||
|
user='alfen_user',
|
||||||
|
password='5uVgr%f%s2P5GR@3q!',
|
||||||
|
port=3307
|
||||||
|
)
|
||||||
|
|
||||||
|
if connection.is_connected():
|
||||||
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
price_fields = [
|
||||||
|
'prijsAA', 'prijsAIP', 'prijsANWB', 'prijsBE', 'prijsEE',
|
||||||
|
'prijsEN', 'prijsEVO', 'prijsEZ', 'prijsFR', 'prijsGSL',
|
||||||
|
'prijsMDE', 'prijsNE', 'prijsTI', 'prijsVDB', 'prijsVON',
|
||||||
|
'prijsWE', 'prijsZG', 'prijsZP'
|
||||||
|
]
|
||||||
|
|
||||||
|
rows_to_insert = []
|
||||||
|
|
||||||
|
# 4. Loop door de data en filter op morgen
|
||||||
|
for entry in data['data']:
|
||||||
|
# Controleer of de datum in de API begint met de datum van morgen
|
||||||
|
if entry['datum'].startswith(tomorrow_date):
|
||||||
|
prices = [float(entry[f]) for f in price_fields if f in entry and entry[f] != '']
|
||||||
|
|
||||||
|
if prices:
|
||||||
|
avg_price = sum(prices) / len(prices)
|
||||||
|
rows_to_insert.append((entry['datum'], avg_price))
|
||||||
|
|
||||||
|
# 5. Database bijwerken
|
||||||
|
if rows_to_insert:
|
||||||
|
# Wis de tabel
|
||||||
|
cursor.execute("DELETE FROM dynamic_price_data_tommorow")
|
||||||
|
|
||||||
|
# Voeg alleen de gefilterde rijen toe
|
||||||
|
query = "INSERT INTO dynamic_price_data_tommorow (datetime, price) VALUES (%s, %s)"
|
||||||
|
cursor.executemany(query, rows_to_insert)
|
||||||
|
|
||||||
|
connection.commit()
|
||||||
|
print(f"Succes! {len(rows_to_insert)} rijen toegevoegd voor {tomorrow_date}.")
|
||||||
|
else:
|
||||||
|
print(f"Geen data gevonden voor {tomorrow_date} in de API-respons.")
|
||||||
|
|
||||||
|
except Error as e:
|
||||||
|
print(f"Database fout: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Fout: {e}")
|
||||||
|
finally:
|
||||||
|
if connection and connection.is_connected():
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
insert_dynamic_price_data_tomorrow()
|
||||||
Reference in New Issue
Block a user