Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
'http://tests.com/api', {'a': 1, 'b': 2})
# Test raising URLError
if 'urllib2' in context: # Python 2.x
urllib2.urlopen = self.mock_urlopen_raising_URLError
else: # Python 3.x
urllib.request.urlopen = self.mock_urlopen_raising_URLError
self.assertRaises(APICallError, self.__instance.call_API,
'http://tests.com/api', {'a': 1, 'b': 2})
# Test raising URLError upon unusual (eg. non 401, 404, 502) HTTP errors
if 'urllib2' in context: # Python 2.x
urllib2.urlopen = self.mock_urlopen_raising_unusual_HTTPError
else: # Python 3.x
urllib.request.urlopen = self.mock_urlopen_raising_unusual_HTTPError
self.assertRaises(APICallError, self.__instance.call_API,
'http://tests.com/api', {'a': 1, 'b': 2})
# Tear down monkey patching
if 'urllib2' in context: # Python 2.x
urllib2.urlopen = ref_to_original_urlopen
else: # Python 3.x
urllib.request.urlopen = ref_to_original_urlopen
class APICallTimeoutError(APICallError):
"""
Error class that represents response timeout conditions
:param message: the message of the error
:type message: str
:param triggering_error: optional *Exception* object that triggered this
error (defaults to ``None``)
:type triggering_error: an *Exception* subtype
"""
pass
class APIInvalidSSLCertificateError(APICallError):
"""
Error class that represents failure in verifying the SSL certificate provided
by the OWM API
:param message: the message of the error
:type message: str
:param triggering_error: optional *Exception* object that triggered this
error (defaults to ``None``)
:type triggering_error: an *Exception* subtype
"""
pass
def update_forecast(self):
"""Get the latest forecast from OpenWeatherMap."""
from pyowm.exceptions.api_call_error import APICallError
try:
if self._mode == 'daily':
fcd = self.owm.daily_forecast_at_coords(
self.latitude, self.longitude, 15)
else:
fcd = self.owm.three_hours_forecast_at_coords(
self.latitude, self.longitude)
except APICallError:
_LOGGER.error("Exception when calling OWM web API "
"to update forecast")
return
if fcd is None:
_LOGGER.warning("Failed to fetch forecast data from OWM")
return
self.forecast_data = fcd.get_forecast()
def check_status_code(cls, status_code, payload):
if status_code < 400:
return
if status_code == 400:
raise api_call_error.APICallError(payload)
elif status_code == 401:
raise api_response_error.UnauthorizedError('Invalid API Key provided')
elif status_code == 404:
raise api_response_error.NotFoundError('Unable to find the resource')
elif status_code == 502:
raise api_call_error.BadGatewayError('Unable to contact the upstream server')
else:
raise api_call_error.APICallError(payload)
from urllib.request import build_opener
opener = build_opener()
if bearer_token_header:
opener.addheaders = [
('Authorization', bearer_token_header)]
except ImportError:
from urllib2 import build_opener
opener = build_opener()
if bearer_token_header:
opener.addheaders = [
('Authorization', bearer_token_header)]
response = opener.open(url, None, timeout)
except HTTPError as e:
raise api_call_error.APICallError(str(e.reason), e)
except URLError as e:
raise api_call_error.APICallError(str(e.reason), e)
else:
data = response.read().decode('utf-8')
self._cache.set(url, data)
return data
return cached
else:
try:
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
response = urlopen(API_full_url, None, timeout)
except HTTPError as e:
if '401' in str(e):
raise unauthorized_error.UnauthorizedError('Invalid API key')
if '404' in str(e):
raise not_found_error.NotFoundError('The resource was not found')
if '502' in str(e):
raise api_call_error.BadGatewayError(str(e), e)
raise api_call_error.APICallError(str(e), e)
except URLError as e:
raise api_call_error.APICallError(str(e), e)
else:
data = response.read().decode('utf-8')
cache.set(API_full_url, data)
return data
def update(self):
"""Get the latest data from OWM and updates the states."""
try:
self._owm.update()
self._owm.update_forecast()
except APICallError:
_LOGGER.error("Exception when calling OWM web API to update data")
return
self.data = self._owm.data
self.forecast_data = self._owm.forecast_data
def update(self):
"""Get the latest data from OpenWeatherMap."""
from pyowm.exceptions.api_call_error import APICallError
try:
obs = self.owm.weather_at_coords(self.latitude, self.longitude)
except (APICallError, TypeError):
_LOGGER.error("Exception when calling OWM web API "
"to get weather at coords")
obs = None
if obs is None:
_LOGGER.warning("Failed to fetch data")
return
self.data = obs.get_weather()
if self.forecast == 1:
try:
obs = self.owm.three_hours_forecast_at_coords(
self.latitude, self.longitude)
self.fc_data = obs.get_forecast()
except (ConnectionResetError, TypeError):
elif cuacaskrg < 800: # Cerah
statusbesok += "🌤️ "
elif cuacaskrg < 801: # Sedikit berawan
statusbesok += "⛅️ "
elif cuacaskrg < 804: # Berawan
statusbesok += "☁️ "
statusbesok += besok._detailed_status
cuacabsk = besok.get_weather_code()
update.message.reply_text("{} hari ini sedang {}, sekitar {}°C.\n".format(lokasinya,
statusnya, temperatur) +
"Untuk besok pada pukul 06:00, akan {}, sekitar {}°C".format(statusbesok, temperaturbesok))
except pyowm.exceptions.api_call_error.APICallError:
update.effective_message.reply_text("Tulis lokasi untuk mengecek cuacanya")
except pyowm.exceptions.api_response_error.NotFoundError:
update.effective_message.reply_text("Maaf, lokasi tidak ditemukan 😞")
else:
return