-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_client.py
46 lines (39 loc) · 1.23 KB
/
api_client.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
import json
import logging
from urllib.request import urlopen
from utils import CITIES, ERR_MESSAGE_TEMPLATE
logger = logging.getLogger()
class YandexWeatherAPI:
"""
Base class for requests
"""
@staticmethod
def _do_req(url):
"""Base request method"""
try:
with urlopen(url) as req:
resp = req.read().decode("utf-8")
resp = json.loads(resp)
if req.status != 200:
raise Exception(
"Error during execute request. {}: {}".format(
resp.status, resp.reason
)
)
return resp
except Exception as ex:
logger.error(ex)
raise Exception(ERR_MESSAGE_TEMPLATE)
@staticmethod
def _get_url_by_city_name(city_name: str) -> str:
try:
return CITIES[city_name]
except KeyError:
raise Exception("Please check that city {} exists".format(city_name))
def get_forecasting(self, city_name: str):
"""
:param city_name: key as str
:return: response data as json
"""
city_url = self._get_url_by_city_name(city_name)
return self._do_req(city_url)