Browse Source

add apiwriter

master
Jakub Škrabánek 4 weeks ago
parent
commit
ab7aed1356
  1. 9
      14_apiwrite/poznamky.md
  2. 60
      14_apiwrite/server.py
  3. 17
      14_apiwrite/templates/index.html
  4. 1
      14_apiwrite/teplota.txt
  5. 1
      14_apiwrite/vlhkost.txt

9
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`

60
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/<int:value>", 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/<int:value>", 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)

17
14_apiwrite/templates/index.html

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Test API zapisovače</h1>
<div class="current-data">
<h2>poslední naměřený data</h2>
<p>Teplota: {{last_t}}°C</p>
<p>Vhkost: {{last_h}}%</p>
</div>
</body>
</html>

1
14_apiwrite/teplota.txt

@ -0,0 +1 @@
2025-04-10 11:38:17,23

1
14_apiwrite/vlhkost.txt

@ -0,0 +1 @@
2025-04-10 11:38:30,80
Loading…
Cancel
Save