Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_ssl_certs_verification_failure(self):
# https://wrong.host.badssl.com does not have a valid SSL cert
client = HttpClient(timeout=4, use_ssl=True, verify_ssl_certs=True)
self.assertRaises(api_call_error.APIInvalidSSLCertificateError,
HttpClient.get_json,
client, 'https://wrong.host.badssl.com')
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)
if self.apikey_valid:
debug.log("API Key hasn't been flagged as bad yet")
try:
self.observation = self.client.weather_at_place(self.location)
weather = self.observation.get_weather()
self.temp = weather.get_temperature(self.temperature_unit).get('temp', -99)
self.wind_speed = weather.get_wind(self.speed_unit).get('speed', -9)
self.wind_dir = weather.get_wind(self.speed_unit).get('deg', 0)
self.conditions = weather.get_status()
self.icon_name = weather.get_weather_icon_name()
debug.log("Weather: {}; Wind: {}; {} ({})".format(self.temperature_string(), self.wind_string(), self.conditions, self.icon_filename()))
except pyowm.exceptions.api_response_error.UnauthorizedError:
debug.warning("[WEATHER] The API key provided doesn't appear to be valid. Please check your config.json.")
debug.warning("[WEATHER] You can get a free API key by visiting https://home.openweathermap.org/users/sign_up")
self.apikey_valid = False
except (pyowm.exceptions.api_call_error.APICallTimeoutError, pyowm.exceptions.api_call_error.APICallError, pyowm.exceptions.api_call_error.APIInvalidSSLCertificateError, pyowm.exceptions.api_call_error.BadGatewayError) as e:
debug.warning("[WEATHER] Fetching weather information failed from a connection issue.")
debug.log("[WEATHER] Error Message: {}".format(e))
# Set some placeholder weather info if this is our first weather update
if self.temp is None:
self.temp = -99
if self.wind_speed is None:
self.wind_speed = -9
if self.wind_dir is None:
self.wind_dir = 0
if self.conditions is None:
self.conditions = "Error"
if self.icon_name is None:
self.icon_name = "50d"
async def weather(self, ctx, *, location : str):
'''Weather'''
try:
observation = self.bot.owm_client.weather_at_place(location)
except (pyowm.exceptions.api_response_error.NotFoundError,
pyowm.exceptions.api_call_error.BadGatewayError) as e:
# TODO: Catch base exceptions?
return await ctx.embed_reply(f":no_entry: Error: {e}")
location = observation.get_location()
description = f"**__{location.get_name()}, {location.get_country()}__**"
weather = observation.get_weather()
condition = weather.get_status()
condition_emotes = {"Clear": ":sunny:", "Clouds": ":cloud:", "Fog": ":foggy:",
"Rain": ":cloud_rain:", "Snow": ":cloud_snow:"}
# Emotes for Haze?, Mist?
emote = ' '
emote += condition_emotes.get(condition, "")
fields = [("Conditions", f"{condition}{emote}")]
temperature_c = weather.get_temperature(unit = "celsius")["temp"]
temperature_f = weather.get_temperature(unit = "fahrenheit")["temp"]
fields.append(("Temperature", f"{temperature_c}°C\n{temperature_f}°F"))
wind = weather.get_wind()
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)
def get_json(self, uri, params=None, headers=None):
try:
resp = requests.get(uri, params=params, headers=headers,
timeout=self.timeout, verify=self.verify_ssl_certs)
except requests.exceptions.SSLError as e:
raise api_call_error.APIInvalidSSLCertificateError(str(e))
except requests.exceptions.ConnectionError as e:
raise api_call_error.APIInvalidSSLCertificateError(str(e))
except requests.exceptions.Timeout:
raise api_call_error.APICallTimeoutError('API call timeouted')
HttpClient.check_status_code(resp.status_code, resp.text)
try:
return resp.status_code, resp.json()
except:
raise parse_response_error.ParseResponseError('Impossible to parse'
'API response data')
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
bearer_token_header = None
try:
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