# ==================================================================================================================== #
# MesoPy #
# Version: 2.0.0 #
# Copyright (c) 2015 MesoWest Developers <atmos-mesowest@lists.utah.edu> #
# #
# LICENSE: #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated #
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the #
# rights to use,copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to #
# permit persons to whom the Software is furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the #
# Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE #
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS #
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR #
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
# #
# ==================================================================================================================== #
try:
import urllib.parse
import urllib.request
import urllib.error
except ImportError:
import urllib2
import urllib
import json
# ==================================================================================================================== #
# MesoPyError class #
# Type: Exception #
# Description: This class is simply the means for error handling when an exception is raised. #
# ==================================================================================================================== #
class MesoPyError(Exception):
def __init__(self, error_message):
self.error_message = error_message
def __str__(self):
r""" This just returns one of the error messages listed in the checkresponse() function"""
return repr(self.error_message)
# ==================================================================================================================== #
# Meso class #
# Type: Main #
# Description: This class defines an instance of MesoPy and takes in the user's token #
# ==================================================================================================================== #
class Meso(object):
def __init__(self, token):
r""" Instantiates an instance of MesoPy.
Arguments:
----------
token: string, mandatory
Your API token that authenticates you for requests against MesoWest.mes
Returns:
--------
None.
Raises:
-------
None.
"""
self.base_url = 'http://api.mesowest.net/v2/'
self.token = token
self.geo_criteria = ['stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc',
'subgacc']
# ================================================================================================================ #
# Functions: #
# ================================================================================================================ #
@staticmethod
def _checkresponse(response):
r""" Returns the data requested by the other methods assuming the response from the API is ok. If not, provides
error handling for all possible API errors. HTTP errors are handled in the get_response() function.
Arguments:
----------
None.
Returns:
--------
The response from the API as a dictionary if the API code is 2.
Raises:
-------
MesoPyError: Gives different response messages depending on returned code from API. If the response is 2,
resultsError is displayed. For a response of 200, an authError message is shown. A ruleError is displayed
if the code is 400, a formatError for -1, and catchError for any other invalid response.
"""
results_error = 'No results were found matching your query'
auth_error = 'The token or API key is not valid, please contact Josh Clark at joshua.m.clark@utah.edu to ' \
'resolve this'
rule_error = 'This request violates a rule of the API. Please check the guidelines for formatting a data ' \
'request and try again'
catch_error = 'Something went wrong. Check all your calls and try again'
if response['SUMMARY']['RESPONSE_CODE'] == 1:
return response
elif response['SUMMARY']['RESPONSE_CODE'] == 2:
raise MesoPyError(results_error)
elif response['SUMMARY']['RESPONSE_CODE'] == 200:
raise MesoPyError(auth_error)
elif response['SUMMARY']['RESPONSE_CODE'] == 400:
raise MesoPyError(rule_error)
elif response['SUMMARY']['RESPONSE_CODE'] == -1:
format_error = response['SUMMARY']['RESPONSE_MESSAGE']
raise MesoPyError(format_error)
else:
raise MesoPyError(catch_error)
def _get_response(self, endpoint, request_dict):
""" Returns a dictionary of data requested by each function.
Arguments:
----------
endpoint: string, mandatory
Set in all other methods, this is the API endpoint specific to each function.
request_dict: string, mandatory
A dictionary of parameters that are formatted into the API call.
Returns:
--------
response: A dictionary that has been dumped from JSON.
Raises:
-------
MesoPyError: Overrides the exceptions given in the requests library to give more custom error messages.
Connection_error occurs if no internet connection exists. Timeout_error occurs if the request takes too
long and redirect_error is shown if the url is formatted incorrectly.
"""
http_error = 'Could not connect to the API. This could be because you have no internet connection, a parameter' \
' was input incorrectly, or the API is currently