52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
from http.server import BaseHTTPRequestHandler
|
|
from datetime import datetime
|
|
import socketserver
|
|
import requests
|
|
import hashlib
|
|
|
|
|
|
PORT = 8808
|
|
TOKEN = 'kUp26@Zg4fv$9Pm'
|
|
ZONE = 'FR'
|
|
ENDPOINT = f'/v7/details/hourly/{ZONE}'
|
|
URL = f'https://app-backend.electricitymap.org{ENDPOINT}'
|
|
|
|
|
|
def create_headers():
|
|
timestamp = str(int(datetime.now().timestamp() * 1000))
|
|
concat = f'{TOKEN}{ENDPOINT}{timestamp}'
|
|
signature = hashlib.sha256()
|
|
signature.update(concat.encode('utf-8'))
|
|
signature = signature.hexdigest()
|
|
|
|
headers = {
|
|
"electricitymap-token": TOKEN,
|
|
"x-request-timestamp": timestamp,
|
|
"x-signature": signature,
|
|
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0"
|
|
}
|
|
return headers
|
|
|
|
def fetch_intensity():
|
|
headers = create_headers()
|
|
electricityMap = requests.get(URL, headers=headers)
|
|
jsonElectricityMap = electricityMap.json()
|
|
last_key = list(jsonElectricityMap["data"]["zoneStates"])[-1]
|
|
|
|
return jsonElectricityMap["data"]["zoneStates"][last_key]['co2intensity']
|
|
|
|
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
|
|
|
|
def do_GET(self):
|
|
data = fetch_intensity()
|
|
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
response_string = f'electricitymap_carbon_intensity{{zone="{ZONE}"}} ' + str(data)
|
|
self.wfile.write(response_string.encode('utf-8'))
|
|
|
|
with socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler) as httpd:
|
|
print("serving at port", PORT)
|
|
httpd.serve_forever()
|
|
|