Exemple #1
0
    def get_access_token(self):
        """Get token if it active, else update before get.

        :return: access_token: str, elasticpath token
        """

        token_work = time.time() < self.expires

        if token_work:
            # No need update token
            return self.access_token

        data = {'client_id': self.client_id, 'grant_type': 'implicit'}

        response = requests.post('https://api.moltin.com/oauth/access_token',
                                 data=data)
        raise_response_errors(response)

        response_json = response.json()

        self.access_token = response_json['access_token']
        self.expires = response_json['expires']

        logger.debug('elasticpathh access token was updated')

        return self.access_token
Exemple #2
0
    def _upload_image_on_server(self, image_name):
        """Internal method which upload image on server.

        :param image_name: str, image name (recommend give with path)
        """
        self._get_server_upload_url()
        self.logger.debug('Start upload image on server')
        self.logger.debug('Open image')

        image_file_descriptor = open(image_name, 'rb')
        self.logger.debug('Image opened')

        # upload image on server
        files = {'photo': image_file_descriptor}
        response = requests.post(self.upload_server_url, files=files)
        cf.raise_response_errors(response)

        self.logger.info('Image was uploaded on server')
        image_file_descriptor.close()
        os.remove(image_name)
        self.logger.debug('Image was closed and removed')

        self.server = response.json()['server']
        self.photo = response.json()['photo']
        self.vk_hash = response.json()['hash']
Exemple #3
0
    def post_img_on_wall(self, message, from_group, image_name):
        """Posting photo to group wall with message

        :param message: str, signature for photo
        :param from_group: str or int, 1 if author of photo is group, 0 if user
        :param image_name: str, image name (recommend give with path)
        """
        self.logger.debug('Start posting photo on group wall')
        # preprocessing before posting
        self._upload_image_on_server(image_name)
        self._save_photo_in_group_album()
        self._make_modif_params_for_photo_posting()

        params = {
            'access_token': self.token,
            'v': self.api_version,
            'owner_id': self.owner_id,
            'from_group': from_group,
            'attachments': self.attachments,
            'message': message
        }

        response = requests.post(self.wall_post_url, params)
        cf.raise_response_errors(response)

        self.logger.info('Photo was posted on wall')
Exemple #4
0
def create_customer(access_keeper, name, email):
    """Create a new customer with name-:name: and email-:email:.

    If the client exists, the status code 409 will be returned.
    If the name or email address is incorrect, status code 422 will be returned.
    Else result in json will be returned.

    :param access_keeper: object, Access class instance
    :param name: str, name of client, not Null
    :param email: str, email of client, should be valid (elasticpath API will check)
    :return: dict or int, info about creation or status code
    """
    logger.debug(f'Creating customer {name} with email {email}...')
    headers = get_authorization_headers(access_keeper)
    headers['Content-Type'] = 'application/json'

    data = {'data': {'type': 'customer', 'name': name, 'email': email}}

    response = requests.post('https://api.moltin.com/v2/customers',
                             headers=headers,
                             json=data)
    if response.status_code not in [409, 422]:
        raise_response_errors(response)
        logger.debug('customer was added')
        return response.json()

    return response.status_code
Exemple #5
0
def add_product_to_cart(access_keeper, product_id, quantity, reference):
    """Add :quantity: of product to cart by :produt_id: for :reference: client.

    :param access_keeper: object, Access class instance
    :param product_id: str, id of product
    :param quantity: str or int, quantity of product (in pcs)
    :param reference: str, some internal string-ID of the client that is used to search for the cart in the future
    :return: dict, response of API
    """
    logger.debug(
        f'adding product {product_id} in cart. quantity: {quantity}. reference: {reference}...'
    )
    headers = get_authorization_headers(access_keeper)
    headers['Content-Type'] = 'application/json'

    data = {
        'data': {
            'id': product_id,
            'type': 'cart_item',
            'quantity': int(quantity)  # if not int API return 400
        }
    }

    response = requests.post(
        f'https://api.moltin.com/v2/carts/{reference}/items',
        headers=headers,
        json=data)
    raise_response_errors(response)
    logger.debug('product was added')

    return response.json()
def get_xkcd_comic_meta():
    """Load xkcd comic image and get meta information about comic
    :return: dict, comic meta information
    """
    # get random comic if from 1 to last comic on now
    comic_id = random.randint(1, cf.get_last_xkcd_num())

    url = f'http://xkcd.com/{comic_id}/info.0.json'
    response = requests.get(url)
    cf.raise_response_errors(response)

    comic_meta = response.json()

    return comic_meta
Exemple #7
0
    def _get_server_upload_url(self):
        """Internal method which get server url for upload photo."""
        params = {
            'access_token': self.token,
            'v': self.api_version,
            'group_id': self.group_id
        }
        self.logger.debug('Getting server url for upload')
        response = requests.get(self.server_upload_url, params)
        cf.raise_response_errors(response)

        self.upload_server_url = response.json()['response']['upload_url']

        self.logger.info('Got server url for upload')
Exemple #8
0
def get_cart_items_info(access_keeper, reference):
    """Get all product in cart for :reference:.

    :param access_keeper: object, Access class instance
    :param reference: str, some internal string-ID of the client that is used to search for the cart in the future
    :return: dict, keys 'products' (value list of dict with product params) and 'total_price' (value string with formatted price)
    """
    logger.debug(f'getting cart items. reference - {reference}...')
    headers = get_authorization_headers(access_keeper)

    response = requests.get(
        f'https://api.moltin.com/v2/carts/{reference}/items', headers=headers)
    raise_response_errors(response)
    logger.debug('cart items were got')

    response_json = response.json()
    items_in_cart = response_json['data']

    logger.debug(f'{len(items_in_cart)} items in cart')

    items_in_cart_for_response = {'products': []}
    for item in items_in_cart:
        item_in_cart = {
            'description':
            item['description'],
            'name':
            item['name'],
            'quantity':
            item['quantity'],
            'price_per_unit':
            item['meta']['display_price']['with_tax']['unit']['formatted'],
            'total_price':
            item['meta']['display_price']['with_tax']['value']['formatted'],
            'product_id':
            item['product_id'],
            'cart_item_id':
            item['id']
        }
        items_in_cart_for_response['products'].append(item_in_cart)
        logger.debug(f'item {item["id"]} was handled')

    total_price = response_json['meta']['display_price']['with_tax'][
        'formatted']
    items_in_cart_for_response['total_price'] = total_price

    logger.debug('items in carts were handled')

    return items_in_cart_for_response
Exemple #9
0
def get_all_products(access_keeper):
    """Get list of products

    :param access_keeper: object, Access class instance
    :return: list of dicts, list of products where product is dict
    """
    logger.debug('getting products...')
    headers = get_authorization_headers(access_keeper)

    response = requests.get('https://api.moltin.com/v2/products',
                            headers=headers)
    raise_response_errors(response)

    products = response.json()['data']
    logger.debug(f'{len(products)} products was got')

    return products
Exemple #10
0
    def _save_photo_in_group_album(self):
        """Internal method which saves photo in group photoalbum"""
        params = {
            'access_token': self.token,
            'v': self.api_version,
            'group_id': self.group_id,
            'photo': self.photo,
            'server': self.server,
            'hash': self.vk_hash
        }
        self.logger.debug('Start saving photo in group photoalbum')
        response = requests.post(self.save_photo_in_group_album_url, params)
        cf.raise_response_errors(response)

        # parameters for posting photo on wall method
        self.attachments_owner_id = response.json()['response'][0]['owner_id']
        self.media_id = response.json()['response'][0]['id']
        self.logger.info('Photo was saved in group photoalbum')
Exemple #11
0
def get_product_by_id(access_keeper, product_id):
    """Get one product by id (:product_id:).

    :param access_keeper: object, Access class instance
    :param product_id: str, id of product
    :return: dict, product params which recorded in dict
    """
    logger.debug(f'getting product by id: {product_id}...')
    headers = get_authorization_headers(access_keeper)

    response = requests.get(f'https://api.moltin.com/v2/products/{product_id}',
                            headers=headers)
    raise_response_errors(response)

    product = response.json()['data']
    logger.debug('product was got')

    return product
Exemple #12
0
def delete_cart_item(access_keeper, reference, cart_item_id):
    """Delete product from :reference: cart by :cart_item_id:

    :param access_keeper: object, Access class instance
    :param reference: str, some internal string-ID of the client that is used to search for the cart in the future
    :param cart_item_id: str, id of item in cart
    :return: dict, response of API
    """
    logger.debug(f'delete cart item {cart_item_id}...')
    headers = get_authorization_headers(access_keeper)

    response = requests.delete(
        f'https://api.moltin.com/v2/carts/{reference}/items/{cart_item_id}',
        headers=headers)
    raise_response_errors(response)
    logger.debug(f'cart item {cart_item_id} was deleted')

    return response.json()
Exemple #13
0
def get_file_href_by_id(access_keeper, file_id):
    """Get href of file by id (:file_id:).

    :param access_keeper: object, Access class instance
    :param file_id: str, id of file
    :return: str, href
    """
    logger.debug(f'getting href by file id: {file_id}...')
    headers = get_authorization_headers(access_keeper)

    response = requests.get(f'https://api.moltin.com/v2/files/{file_id}',
                            headers=headers)
    raise_response_errors(response)

    href = response.json()['data']['link']['href']
    logger.debug('href was got')

    return href