Jakub Škrabánek 1 month ago
parent
commit
6dda657013
  1. 61
      17_owm_multicity/main.py

61
17_owm_multicity/main.py

@ -0,0 +1,61 @@
from flask import Flask, jsonify
import requests
app = Flask(__name__)
API_KEY = "f70d944f638a7ae77de89435d4d23c01"
mesta = ["Praha","Štětí","Hněvice","Ústí nad Labem"]
url1 = f"http://api.openweathermap.org/data/2.5/weather?"
url2 = f"appid={API_KEY}&units=metric&lang=cz&q="
url_base = url1+url2
def nacti_pocasi(mesto):
try:
response = requests.get(url_base+mesto)
if response.status_code == 200:
data = response.json()
return {
"name": data["name"],
"temp": data["main"]["temp"],
"hum": data["main"]["humidity"],
"desc": data["weather"][0]["description"]
}
else:
return {
"name": mesto,
"error":f"API Chyba: {response.status_code}"
}
except Exception as e:
return {
"name": mesto,
"error": f"Chyba připojení: {e}"
}
@app.route("/")
def index():
vysledky_pocasi = []
for kontkretni_mesto in mesta:
vysledky_pocasi.append(nacti_pocasi(kontkretni_mesto))
html = "<h1> Aktuální počasí ve městech </h1>"
html += f"<p>{mesta}</p>"
for vysledek in vysledky_pocasi:
if "error" in vysledek:
html += f"<h2>{vysledek['name']}</h2>"
html += f"<ul><li>Chyba:{vysledek['error']}</li></ul>"
else:
html += f"<h2>{vysledek['name']}</h2>"
html += "<ul>"
html += f"<li>Teplota: {vysledek['temp']}°C</li>"
html += f"<li>Vlhkost: {vysledek['hum']}%</li>"
html += f"<li>Popis: {vysledek['desc']}</li>"
html += "</ul>"
html += '<p><a href="/">Aktualizovat data</a></p>'
return html
if __name__ == "__main__":
print("Multi town Weather Dashboard")
print("Link: http://localhost:8080")
print(f"Města: {', '.join(mesta)}")
app.run(host="0.0.0.0",port="8080",debug=True)
Loading…
Cancel
Save