Improve design of this class

This commit is contained in:
leandrotoledo 2015-09-07 15:54:12 -03:00
parent a409fc511d
commit e1edeb7bec

View file

@ -38,19 +38,18 @@ def _parse(json_data):
dictionary if there is any error. dictionary if there is any error.
Args: Args:
json_data: url:
JSON results from Telegram Bot API. urllib.urlopen object
Returns: Returns:
A JSON parsed as Python dict with results. A JSON parsed as Python dict with results.
""" """
try: try:
data = json.loads(json_data.decode()) data = json.loads(json_data.decode())
if not data['ok']:
raise TelegramError(data['description']) if not data.get('ok') and data.get('description'):
return data['description']
except ValueError: except ValueError:
if '<title>403 Forbidden</title>' in json_data:
raise TelegramError({'message': 'API must be authenticated'})
raise TelegramError({'message': 'JSON decoding'}) raise TelegramError({'message': 'JSON decoding'})
return data['result'] return data['result']
@ -61,14 +60,13 @@ def get(url):
Args: Args:
url: url:
The web location we want to retrieve. The web location we want to retrieve.
Returns: Returns:
A JSON object. A JSON object.
""" """
try:
result = urlopen(url).read() result = urlopen(url).read()
return _parse(result) return _parse(result)
except URLError as error:
raise TelegramError(str(error))
def post(url, def post(url,
@ -79,30 +77,24 @@ def post(url,
The web location we want to retrieve. The web location we want to retrieve.
data: data:
A dict of (str, unicode) key/value pairs. A dict of (str, unicode) key/value pairs.
Returns: Returns:
A JSON object. A JSON object.
""" """
try: try:
if InputFile.is_inputfile(data): if InputFile.is_inputfile(data):
data = InputFile(data) data = InputFile(data)
request = Request(url, data=data.to_form(), headers=data.headers)
request = Request(
url,
data=data.to_form(),
headers=data.headers
)
result = urlopen(request).read() result = urlopen(request).read()
else: else:
result = urlopen( result = urlopen(url, urlencode(data).encode()).read()
url,
urlencode(data).encode()
).read()
return _parse(result)
except HTTPError as error: except HTTPError as error:
raise TelegramError(str(error)) message = _parse(error.read())
raise TelegramError(message)
except URLError as error: except URLError as error:
raise TelegramError(str(error)) raise TelegramError(str(error))
except IOError as error: except IOError as error:
raise TelegramError(str(error)) raise TelegramError(str(error))
return _parse(result)