Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
duedil-python / duedil / api.py
Size: Mime:
from __future__ import unicode_literals

import os

import requests
from requests.exceptions import HTTPError

API_PRO_URL = 'http://duedil.io/v3'
API_LITE_URL = 'http://api.duedil.com/open'
API_INTERNATIONAL_URL = 'http://api.duedil.com/international'

SUPPORTED_INTERNATIONAL_COUNTRY_CODES = (
    'be', 'cz', 'dk', 'fi', 'fr', 'de', 'hu', 'is', 'ie', 'it', 'lt', 'lu',
    'mt', 'nl', 'no', 'pl', 'pt', 'sk', 'se', 'gb',)

APIS_SUPPORTED = {
    'pro': API_PRO_URL,
    'lite': API_LITE_URL,
    'international': API_INTERNATIONAL_URL,
}


class Duedil(object):
    API = 'pro'
    API_KEY = os.environ.get('DUEDIL_API_KEY', None)
    LOCALE = 'uk'
    SANDBOX = False
    CACHE = None

    def get(self, endpoint, data=None):
        klass = self.__class__
        api_type = klass.API

        if api_type not in APIS_SUPPORTED.keys():
            raise TypeError(
                'Duedil API must be "pro", "lite", and "international"')

        base_url = APIS_SUPPORTED[api_type]
        api_key = klass.API_KEY

        if not api_key:
            raise ValueError("Please provide a valid Duedil API key")

        result = None

        data = data or {}

        if klass.SANDBOX:
            base_url = base_url + "/sandbox"

        if api_type in ('pro', 'international'):
            if api_type == 'pro' and klass.LOCALE not in ('uk', 'roi'):
                raise ValueError(
                    'Duedil Pro API can only search in the UK or \
                    Republic of Ireland')
            elif (
                api_type == 'international' and
                klass.LOCALE not in SUPPORTED_INTERNATIONAL_COUNTRY_CODES
            ):
                raise ValueError(
                    'Please select an international country supported \
                    by Duedil'
                )
            base_url += '/{locale}'.format(locale=klass.LOCALE)

        prepared_url = "{base_url}/{endpoint}.json".format(
            base_url=base_url,
            endpoint=endpoint)

        params = data.copy()
        params['api_key'] = api_key

        if klass.CACHE:
            result = klass.CACHE.get_url(prepared_url, url_params=params)

        if not result:
            response = requests.get(prepared_url, params=params)
            try:
                if not response.raise_for_status():
                    result = response.json()
                    if klass.CACHE:
                        klass.CACHE.set_url(prepared_url, result,
                                            url_params=params)
            except HTTPError:
                if response.status_code == 404:
                    pass
                else:
                    raise

        return result

api_client = Duedil()