-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.py
86 lines (66 loc) · 2.42 KB
/
weather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import urllib.parse
import urllib.request
import json
import urllib.error
from platformdirs import user_data_dir
import os.path
key_file = os.path.join(user_data_dir("whather", "yesseruser", ensure_exists=True), "key.txt")
def set_key(key: str):
with open(key_file, "a") as file:
file.write(key)
def get_key() -> str:
if not os.path.isfile(key_file):
return ""
with open(key_file, "r") as file:
return file.readline().rstrip()
def delete_key():
if not os.path.isfile(key_file):
return
os.remove(key_file)
Url = "https://api.openweathermap.org/data/2.5/weather"
IconUrl = "https://openweathermap.org/img/wn/"
def get_api_params(city: str, key: str) -> dict:
return {
"appid": key,
"units": "metric",
"lang": "cz",
"q": city
}
def get_api_response(params: dict) -> dict:
print("Získávání informací o počasí v " + str(params["q"]).capitalize())
params = urllib.parse.urlencode(params)
try:
response = urllib.request.urlopen(Url + "?" + params)
return json.loads(response.read().decode())
except urllib.error.HTTPError as error:
if error.code == 401:
print("Zkontrolujte klíč.")
else:
print("Chyba HTTP: Zkotrolujte zadaný název města")
exit()
except urllib.error.URLError:
print("Chyba URL: Zkontrolujte připojení k internetu")
exit()
def get_current_weather(city: str):
key = get_key()
params = get_api_params(city, key)
response = get_api_response(params)
return get_weather_object(response)
def get_weather_object(data: dict) -> dict:
return {
"desc": str(data["weather"][0]["description"]),
"temp": str(data["main"]["temp"]) + "°C",
"feels_like": str(data["main"]["feels_like"]) + "°C",
"press": str(data["main"]["pressure"]) + "hPa",
"speed": str(data["wind"]["speed"]) + "m/s",
"deg": str(data["wind"]["deg"]) + "° vpravo od severu",
"icon": IconUrl + (data["weather"][0]["icon"]) + "@2x.png"
}
def print_weather_info(w: dict):
print(str(w["desc"]).capitalize())
print("Teplota: " + str(w["temp"]))
print("Pocitová teplota: " + str(w["feels_like"]))
print("Atmosférický tlak: " + str(w["press"]))
print("Rychlost větru: " + str(w["speed"]))
print("Směr větru: " + str(w["deg"]))
print("Ikona(Webová stránka): " + str(w["icon"]))