Esempio n. 1
0
    def get_currencies(cls):
        """Get the list of currencies from free.currencyconverterapi.com

        Return:
            A list of valid currencies

        """
        memcache_timeout = 60 * 30

        # try to get from memcache
        currencies = cache.get(u'CURRENCIES')
        if currencies:
            return currencies

        # not found in memcache, get from api service
        try:
            data = requests.get(cls.CURRENCY_LIST_URL)
            data = json.loads(data.content)
            cache.set(u'CURRENCIES', data['results'], timeout=memcache_timeout)

            return data['results']
        except Exception as e:
            return Exception(
                'Unable to load the list of available currencies'.format(
                    e.message))
Esempio n. 2
0
def post_register_name(session,
                       snap_name,
                       registrant_comment=None,
                       is_private=False,
                       store=None):

    json = {
        'snap_name': snap_name,
    }

    if registrant_comment:
        json['registrant_comment'] = registrant_comment

    if is_private:
        json['is_private'] = is_private

    if store:
        json['store'] = store

    response = cache.get(REGISTER_NAME_URL,
                         headers=get_authorization_header(session),
                         json=json,
                         method='POST')

    if authentication.is_macaroon_expired(response.headers):
        raise MacaroonRefreshRequired()

    return process_response(response)
Esempio n. 3
0
def snap_screenshots(snap_id, session, data=None, files=None):
    method = None
    files_array = None
    headers = get_authorization_header(session)
    headers['Accept'] = 'application/json'

    if data:
        method = 'PUT'

        files_array = []
        if files:
            for f in files:
                files_array.append(
                    (f.filename, (f.filename, f.stream, f.mimetype)))
        else:
            # API requires a multipart request, but we have no files to push
            # https://github.com/requests/requests/issues/1081
            files_array = {'info': ('', data['info'])}
            data = None

    screenshot_response = cache.get(
        SCREENSHOTS_QUERY_URL.format(snap_id=snap_id),
        headers=headers,
        data=data,
        method=method,
        files=files_array)

    if authentication.is_macaroon_expired(screenshot_response.headers):
        raise MacaroonRefreshRequired()

    return process_response(screenshot_response)
Esempio n. 4
0
def get_snap_info(snap_name, session):
    response = cache.get(SNAP_INFO_URL.format(snap_name=snap_name),
                         headers=get_authorization_header(session))

    if authentication.is_macaroon_expired(response.headers):
        raise MacaroonRefreshRequired()

    return process_response(response)
Esempio n. 5
0
def get_account(session):
    headers = get_authorization_header(session)

    response = cache.get(url=ACCOUNT_URL, method='GET', headers=headers)

    if authentication.is_macaroon_expired(response.headers):
        raise MacaroonRefreshRequired()

    return process_response(response)
Esempio n. 6
0
def get_agreement(session):
    headers = get_authorization_header(session)

    agreement_response = cache.get(AGREEMENT_URL, headers)

    if authentication.is_macaroon_expired(agreement_response.headers):
        raise MacaroonRefreshRequired()

    return agreement_response.json()
Esempio n. 7
0
    def get_products(cls):
        """Get the list of products from memcache is present otherwise from json file

        Raises:
            An exception if the operation fails

        """

        # try to get from memcache
        products = cache.get(u'PRODUCTS')
        if products:
            return products

        # not found in memcache, get the data from json file
        Pricing.load_from_json()

        products = cache.get(u'PRODUCTS')
        return products
Esempio n. 8
0
    def get_vat_bands(cls):
        """Get the list of products from memcache is present otherwise from json file

        Raises:
            An exception if the operation fails

        """

        # try to get from memcache
        vat_bands = cache.get(u'VAT_BANDS')
        if vat_bands:
            return vat_bands

        # not found in memcache, get the data from json file
        Pricing.load_from_json()

        vat_bands = cache.get(u'VAT_BANDS')
        return vat_bands
Esempio n. 9
0
def post_agreement(session, agreed):
    headers = get_authorization_header(session)

    json = {'latest_tos_accepted': agreed}
    agreement_response = cache.get(AGREEMENT_URL, headers, json)

    if authentication.is_macaroon_expired(agreement_response.headers):
        raise MacaroonRefreshRequired()

    return process_response(agreement_response)
Esempio n. 10
0
def snap_metadata(snap_id, session, json=None):
    method = "PUT" if json is not None else None

    metadata_response = cache.get(METADATA_QUERY_URL.format(snap_id=snap_id),
                                  headers=get_authorization_header(session),
                                  json=json,
                                  method=method)

    if authentication.is_macaroon_expired(metadata_response.headers):
        raise MacaroonRefreshRequired()

    return process_response(metadata_response)
Esempio n. 11
0
def get_publisher_metrics(session, json):
    authed_metrics_headers = PUB_METRICS_QUERY_HEADERS.copy()
    auth_header = get_authorization_header(session)['Authorization']
    authed_metrics_headers['Authorization'] = auth_header

    metrics_response = cache.get(SNAP_PUB_METRICS_URL,
                                 headers=authed_metrics_headers,
                                 json=json)

    if authentication.is_macaroon_expired(metrics_response.headers):
        raise MacaroonRefreshRequired()

    return process_response(metrics_response)
Esempio n. 12
0
    def get_by_id(cls, id):
        """Gets the Client with the given id."""
        # Overriding this to return trusted clients.
        logging.debug("Retrieving client with id %s (trusted: %s)" % (id, id in TRUSTED_CLIENTS))
        client = TRUSTED_CLIENTS.get(id)
        if not client:
            client = cache.get("client-%s" % id)

        if not client:
            client = cls.from_dict(cls.get(id))
            cache.set("client-%s" % id, client)

        return client
Esempio n. 13
0
    def get_by_id(cls, id):
        """Gets the Client with the given id."""
        # Overriding this to return trusted clients.
        logging.debug("Retrieving client with id %s (trusted: %s)" %
                      (id, id in TRUSTED_CLIENTS))
        client = TRUSTED_CLIENTS.get(id)
        if not client:
            client = cache.get("client-%s" % id)

        if not client:
            client = cls.from_dict(cls.get(id))
            cache.set("client-%s" % id, client)

        return client
Esempio n. 14
0
def post_username(session, username):
    headers = get_authorization_header(session)
    json = {'short_namespace': username}
    username_response = cache.get(url=ACCOUNT_URL,
                                  headers=headers,
                                  json=json,
                                  method='PATCH')

    if authentication.is_macaroon_expired(username_response.headers):
        raise MacaroonRefreshRequired()

    if username_response.status_code == 204:
        return {}
    else:
        return process_response(username_response)
Esempio n. 15
0
def get_user():
    """get the user for the current session."""
    token = session.get("token")
    user_id = session.get("user_id")

    if (not token) or (not user_id):
        return None

    cache_result = cache.get("session-" + token)
    if cache_result is None:
        return None

    if user_id != cache_result:
        raise errors.AuthError("The session isn't valid.")

    return User.get_by_id(user_id)
Esempio n. 16
0
def get_user():
    """get the user for the current session."""
    token = session.get("token")
    user_id = session.get("user_id")

    if (not token) or (not user_id):
        return None

    cache_result = cache.get("session-" + token)
    if cache_result is None:
        return None

    if user_id != cache_result:
        raise errors.AuthError("The session isn't valid.")

    return User.get_by_id(user_id)
Esempio n. 17
0
    def get_exchange_rate(cls, currency):
        """Get the exchange rate from GBP to given currency

           Args:
               currency: The id of the currency (3 chars)

           Return:
               The exchange rate from GBP to the given currency
        """
        memcache_timeout = 60 * 5

        currency = currency.upper()
        currencies = cls.get_currencies()

        # check if the given currency is in the allowed currencis
        if currency not in currencies:
            raise Exception('Invalid currency: {}'.format(currency))

        # set the exchange currencies
        exchange = u'GBP_{}'.format(currency)

        # try to get the exchange rate from memcache
        rate = cache.get(exchange)
        if rate:
            return rate

        # the exchange rate is not in memcache get api service
        try:
            url = cls.EXCHANGE_RATE_URL.format(exchange)
            data = requests.get(url)
            data = json.loads(data.content)
            rate = data[exchange][u'val']
        except Exception as e:
            raise Exception(u'Unable to retrieve the rate for {}'.format(
                e.message))

        # try to convert the rate to float
        try:
            rate = float(rate)
            cache.set(exchange, rate, memcache_timeout)
            return rate
        except Exception as e:
            raise Exception(
                u'Unable to convert the rate for {} -> {}: {}'.format(
                    exchange, rate, e.message))
Esempio n. 18
0
def get_error(url):
    """Check whether the given url returned an error code"""
    return cache.get(url)
Esempio n. 19
0
 def get_progress(cls, user_id, episode_id):
     id = cls._make_id(user_id, episode_id)
     progress = cache.get("progress_%s" % id)
     return progress or cls.get(id).progress
Esempio n. 20
0
 def get_progress(cls, user_id, episode_id):
     id = cls._make_id(user_id, episode_id)
     progress = cache.get("progress_%s" % id)
     return progress or cls.get(id).progress
Esempio n. 21
0
def get_error(url):
    """Check whether the given url returned an error code"""
    return cache.get(url)
Esempio n. 22
0
 def lookup(cls, client_id, code):
     """Looks up a grant token for the given client and code."""
     return cache.get("GRANT_TOKEN_"+cls.make_id(client_id, code))
Esempio n. 23
0
def _get_next(key):
    """Get the url to go to after login, by its associated key."""
    return cache.get(key)
Esempio n. 24
0
def get_snap_details(snap_name, snap_channel):
    details_response = cache.get(SNAP_DETAILS_URL.format(
        snap_name=snap_name, snap_channel=snap_channel),
                                 headers=DETAILS_QUERY_HEADERS)

    return process_response(details_response)
Esempio n. 25
0
def get_searched_snaps(snap_searched, size, page):
    searched_response = cache.get(SNAP_SEARCH_URL.format(
        snap_name=snap_searched, size=size, page=page),
                                  headers=SEARCH_QUERY_HEADERS)

    return process_response(searched_response)
Esempio n. 26
0
def get_promoted_snaps():
    promoted_response = cache.get(PROMOTED_QUERY_URL,
                                  headers=PROMOTED_QUERY_HEADERS)

    return process_response(promoted_response)
Esempio n. 27
0
def get_featured_snaps():
    featured_response = cache.get(FEATURE_SNAPS_URL,
                                  headers=SEARCH_QUERY_HEADERS)

    return process_response(featured_response)
Esempio n. 28
0
def get_public_metrics(snap_name, json):
    metrics_response = cache.get(SNAP_METRICS_URL.format(snap_name=snap_name),
                                 headers=METRICS_QUERY_HEADERS,
                                 json=json)

    return process_response(metrics_response)
Esempio n. 29
0
def _get_next(key):
    """Get the url to go to after login, by its associated key."""
    return cache.get(key)