Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from gettext import gettext as _
- from launcher import logger
- from urllib.request import urlopen, Request
- from urllib.parse import urlsplit, urlunsplit, urlencode
- def add_api_key(f):
- """
- Add api key to the request.
- :param f: Function to be decorated
- :return:
- """
- def get_w_key(self, uri, params):
- if self.api_key is not None:
- msg = _('Adding API key "%s" to request') % self.api_key
- logger.info(msg)
- params.update({
- 'api_key': self.api_key
- })
- return f(self, uri, params)
- return get_w_key
- class CCApi:
- """
- Basic API call class.
- Provides easy way to communicate with REST APIs.
- """
- def __init__(self, base_url, api_key):
- """
- Initialize object.
- :param base_url: str
- :param api_key: str
- """
- msg = _('Initializing %s') % __class__
- logger.info(msg)
- self.base_url = urlsplit(base_url)
- self.api_key = api_key
- @add_api_key
- def get(self, uri, params={}):
- """
- Call GET API method and return response.
- :param uri: str
- :param params: dict
- :return:
- """
- msg = _('GET %s') % uri
- logger.info(msg)
- msg = _('Params: %s') % params
- logger.debug(msg)
- qs = urlencode(params)
- url = urlunsplit((
- self.base_url.scheme, self.base_url.netloc, uri, qs, ''
- ))
- req = Request(
- url,
- method='GET',
- )
- response = urlopen(req)
- ret_response = response.read().decode('utf8')
- msg = _('Response: %s') % ret_response
- logger.debug(msg)
- return ret_response
- @add_api_key
- def post(self, uri, params={}):
- """
- Call POST API method and return response.
- :param uri: str
- :param params: dict
- :return:
- """
- msg = _('POST %s') % uri
- logger.info(msg)
- msg = _('Params: %s') % params
- logger.debug(msg)
- qs = ''
- url = urlunsplit((
- self.base_url.scheme, self.base_url.netloc, uri, qs, ''
- ))
- # we need to transform params dict into bytes string for Request data
- # argument
- #
- # replacing ' to " is just for further processing of json data
- # in some cases json data are considered correct only with
- # " as quotation mark
- data = params.__repr__().replace("'", '"').encode('ascii')
- req = Request(
- url,
- headers={
- 'Content-Type': 'application/json'
- },
- method='POST',
- data=data,
- )
- response = urlopen(req)
- ret_response = response.read().decode('utf8')
- msg = _('Response: %s') % ret_response
- logger.debug(msg)
- return ret_response
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement