diff --git a/14_apiwrite/poznamky.md b/14_apiwrite/poznamky.md new file mode 100644 index 0000000..b7eb0b1 --- /dev/null +++ b/14_apiwrite/poznamky.md @@ -0,0 +1,9 @@ +# příprava projektu + +Příkazy pro přípravu a instalaci základní knihovny pro API server + +`python -m venv .venv` + +`.venv\Scripts\activate` + +`pip install flask` \ No newline at end of file diff --git a/14_apiwrite/server.py b/14_apiwrite/server.py new file mode 100644 index 0000000..73bc092 --- /dev/null +++ b/14_apiwrite/server.py @@ -0,0 +1,60 @@ +from flask import Flask, render_template, request, abort +import os +from datetime import datetime + +app = Flask(__name__) + +TEPLOTA_FILE = "teplota.txt" +VLHKOST_FILE = "vlhkost.txt" + +def appendToFile(file,value): + try: + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + with open(file,"a") as f: + f.write(f"{timestamp},{value}") + return True + except Exception as e: + print(f"Chyba při zápisu do souboru {file}:{e}") + return False + +def readLastLine(filename): + try: + with open(filename,"r") as f: + lines = f.readlines() + for line in reversed(lines): + stripped_line = line.strip() + if stripped_line: + parts = stripped_line.split(",") + if len(parts) == 2: + return parts[1] + else: + return stripped_line + return "žádná data" + except FileNotFoundError: + return "Soubor nenalezen" + except Exception as e: + print(f"Chyba při čtení souboru {filename}:{e}") + return "Chyba čtení" + +@app.route("/") +def index(): + last_temp = readLastLine(TEPLOTA_FILE) + last_hum = readLastLine(VLHKOST_FILE) + return render_template("index.html",last_t = last_temp,last_h=last_hum) + +@app.route("/api/teplota/", methods=["GET","POST"]) +def record_t(value): + if appendToFile(TEPLOTA_FILE,value): + return f"Teplota {value}°C uložena",200 + else: + return "Chyba při ukládání teploty", 500 + +@app.route("/api/vlhkost/", methods=["GET","POST"]) +def record_h(value): + if appendToFile(VLHKOST_FILE,value): + return f"vlhkost {value}°C uložena",200 + else: + return "Chyba při ukládání teploty", 500 + +if __name__ == "__main__": + app.run(debug=True, host="0.0.0.0", port=5000) \ No newline at end of file diff --git a/14_apiwrite/templates/index.html b/14_apiwrite/templates/index.html new file mode 100644 index 0000000..1976043 --- /dev/null +++ b/14_apiwrite/templates/index.html @@ -0,0 +1,17 @@ + + + + + + Document + + +

Test API zapisovače

+ +
+

poslední naměřený data

+

Teplota: {{last_t}}°C

+

Vhkost: {{last_h}}%

+
+ + \ No newline at end of file diff --git a/14_apiwrite/teplota.txt b/14_apiwrite/teplota.txt new file mode 100644 index 0000000..c501302 --- /dev/null +++ b/14_apiwrite/teplota.txt @@ -0,0 +1 @@ +2025-04-10 11:38:17,23 \ No newline at end of file diff --git a/14_apiwrite/vlhkost.txt b/14_apiwrite/vlhkost.txt new file mode 100644 index 0000000..beae6a9 --- /dev/null +++ b/14_apiwrite/vlhkost.txt @@ -0,0 +1 @@ +2025-04-10 11:38:30,80 \ No newline at end of file