Files
E-Manager/server/main.py

123 lines
3.8 KiB
Python

from flask import Flask, request, jsonify
import os
import json
from datetime import datetime
app = Flask(__name__)
# Route to get configuration
@app.route('/getconfig', methods=['POST'])
def get_config():
try:
token_id = request.headers.get('ID')
if not token_id:
return jsonify({'error': 'Token ID is missing'}), 400
config_file = os.path.join('config', f'{token_id}.json')
data_file = os.path.join('data', f'{token_id}.json') # angenommen, die Daten befinden sich im Ordner 'data'
if not os.path.exists(config_file):
return jsonify({'error': 'Config not found for the specified token'}), 404
with open(config_file, 'r') as file:
config = json.load(file)
# Extract and include last timestamp in the response
if os.path.exists(data_file):
with open(data_file, 'r') as file:
data = json.load(file)
try:
last_timestamp = max(data.keys()) # Den neuesten Zeitstempel aus den Schlüsseln der Daten extrahieren
print(last_timestamp)
config['last_timestamp'] = last_timestamp
except ValueError:
config['last_timestamp'] = 0
else:
config['last_timestamp'] = 0
return jsonify(config), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
# Route to set new data
@app.route('/setdata', methods=['POST'])
def set_data():
# Token-ID aus den Request-Headern extrahieren
token_id = request.headers.get('ID')
# Neue Daten aus den Request-Headern laden
new_data = request.headers.get('JSON')
try:
# Versuche, das JSON zu laden
new_data = json.loads(new_data)
except json.JSONDecodeError:
# Wenn das JSON nicht korrekt formatiert ist, schreibe das neue JSON in die Datei und beende die Funktion
write_json_file(token_id, new_data)
return 'Invalid JSON format. New JSON data has been written to the file and overwritten existing data.'
# Pfad zum Datenordner und Datei für die Token-ID erstellen
data_folder = 'data'
file_path = os.path.join(data_folder, f'{token_id}.json')
# Überprüfen, ob die Datei existiert und Daten enthält
if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
# Bestehende Daten aus der Datei laden
with open(file_path, 'r') as file:
existing_data = json.load(file)
# Merge der beiden JSON-Objekte
merged_data = merge_json(existing_data, new_data)
else:
# Wenn die Datei nicht existiert oder leer ist, neue Daten verwenden
merged_data = new_data
# Daten in die Datei schreiben
with open(file_path, 'w') as file:
json.dump(merged_data, file)
return 'Data successfully set!'
def write_json_file(token_id, new_data):
"""
Funktion zum Schreiben von JSON-Daten in eine Datei.
"""
# Pfad zum Datenordner und Datei für die Token-ID erstellen
data_folder = 'data'
file_path = os.path.join(data_folder, f'{token_id}.json')
# Neue Daten in die Datei schreiben
with open(file_path, 'w') as file:
json.dump(new_data, file)
def merge_json(json1, json2):
# Wenn ein JSON leer ist, gib einfach das andere zurück
if not json1:
return json2
if not json2:
return json1
# Erstelle eine Kopie des ersten JSON
merged_data = json1.copy()
# Füge die Timestamps aus dem zweiten JSON ein, falls sie nicht bereits im ersten JSON vorhanden sind
for timestamp, values in json2.items():
if timestamp not in merged_data:
merged_data[timestamp] = values
return merged_data
if __name__ == '__main__':
app.run(debug=False)