X Tutup
Skip to content

Commit 21fdaa4

Browse files
committed
utils.request: decorate functions with general try... except...
refs python-telegram-bot#134
1 parent 79f29c4 commit 21fdaa4

File tree

1 file changed

+43
-30
lines changed

1 file changed

+43
-30
lines changed

telegram/utils/request.py

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
"""This module contains methods to make POST and GET requests"""
2121

22+
import functools
2223
import json
2324
import socket
2425
from ssl import SSLError
@@ -49,14 +50,42 @@ def _parse(json_data):
4950
try:
5051
data = json.loads(decoded_s)
5152
except ValueError:
52-
raise TelegramError('Invalid server response; probably bad token')
53+
raise TelegramError('Invalid server response')
5354

5455
if not data.get('ok') and data.get('description'):
5556
return data['description']
5657

5758
return data['result']
5859

5960

61+
def _try_except_req(func):
62+
"""Decorator for requests to handle known exceptions"""
63+
@functools.wraps(func)
64+
def decorator(*args, **kwargs):
65+
try:
66+
return func(*args, **kwargs)
67+
except HTTPError as error:
68+
if error.getcode() == 403:
69+
raise TelegramError('Unauthorized')
70+
if error.getcode() == 502:
71+
raise TelegramError('Bad Gateway')
72+
73+
try:
74+
message = _parse(error.read())
75+
except ValueError:
76+
message = 'Unknown HTTPError'
77+
78+
raise TelegramError(message)
79+
except (SSLError, socket.timeout) as error:
80+
if "operation timed out" in str(error):
81+
raise TelegramError("Timed out")
82+
83+
raise TelegramError(str(error))
84+
85+
return decorator
86+
87+
88+
@_try_except_req
6089
def get(url):
6190
"""Request an URL.
6291
Args:
@@ -71,6 +100,7 @@ def get(url):
71100
return _parse(result)
72101

73102

103+
@_try_except_req
74104
def post(url,
75105
data,
76106
network_delay=2.):
@@ -95,39 +125,22 @@ def post(url,
95125
else:
96126
timeout = None
97127

98-
try:
99-
if InputFile.is_inputfile(data):
100-
data = InputFile(data)
101-
request = Request(url,
102-
data=data.to_form(),
103-
headers=data.headers)
104-
else:
105-
data = json.dumps(data)
106-
request = Request(url,
107-
data=data.encode(),
108-
headers={'Content-Type': 'application/json'})
109-
110-
result = urlopen(request, timeout=timeout).read()
111-
except HTTPError as error:
112-
if error.getcode() == 403:
113-
raise TelegramError('Unauthorized')
114-
if error.getcode() == 502:
115-
raise TelegramError('Bad Gateway')
116-
117-
try:
118-
message = _parse(error.read())
119-
except ValueError:
120-
message = 'Unknown HTTPError'
121-
122-
raise TelegramError(message)
123-
except (SSLError, socket.timeout) as error:
124-
if "operation timed out" in str(error):
125-
raise TelegramError("Timed out")
128+
if InputFile.is_inputfile(data):
129+
data = InputFile(data)
130+
request = Request(url,
131+
data=data.to_form(),
132+
headers=data.headers)
133+
else:
134+
data = json.dumps(data)
135+
request = Request(url,
136+
data=data.encode(),
137+
headers={'Content-Type': 'application/json'})
126138

127-
raise TelegramError(str(error))
139+
result = urlopen(request, timeout=timeout).read()
128140
return _parse(result)
129141

130142

143+
@_try_except_req
131144
def download(url,
132145
filename):
133146
"""Download a file by its URL.

0 commit comments

Comments
 (0)
X Tutup