Esempio n. 1
0
    def test_get_browse_nodes_UnrecognizedClient(self):
        host = "webservices.amazon.com"
        region = "us-east-1"
        default_api = DefaultApi(access_key="",
                                 secret_key="",
                                 host=host,
                                 region=region)

        get_browse_node_request = GetBrowseNodesRequest(
            partner_tag="",
            partner_type=PartnerType.ASSOCIATES,
            marketplace="www.amazon.com",
            browse_node_ids=[],
            resources=[],
        )

        try:
            response = default_api.get_browse_nodes(get_browse_node_request)
        except ApiException as exception:
            self.assertEquals(exception.status, 401, "Status Check")
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Code"],
                UNRECOGNIZED_CLIENT,
                "Error Code Check",
            )
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Message"],
                "The Access Key ID or security token included in the request is invalid.",
                "Message Check",
            )
Esempio n. 2
0
    def test_get_browse_nodes_IncompleteSignature(self):
        host = "webservices.amazon.com"
        region = "us-east-1"
        default_api = DefaultApi(
            access_key=DUMMY_ACCESS_KEY,
            secret_key=DUMMY_SECRET_KEY,
            host=host,
            region=region,
        )

        get_browse_node_request = GetBrowseNodesRequest(
            partner_tag="",
            partner_type=PartnerType.ASSOCIATES,
            marketplace="www.amazon.com",
            browse_node_ids=[],
            resources=[],
        )

        try:
            response = default_api.get_browse_nodes(get_browse_node_request)
        except ApiException as exception:
            self.assertEquals(exception.status, 400, "Status Check")
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Code"],
                INCOMPLETE_SIGNATURE,
                "Error Code Check",
            )
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Message"],
                "The request signature did not include all of the required components. If you are using an AWS SDK, requests are signed for you automatically; otherwise, go to https://webservices.amazon.com/paapi5/documentation/sending-request.html#signing.",
                "Message Check",
            )
Esempio n. 3
0
    def test_get_browse_nodes_aync_UnrecognizedClient(self):
        host = "webservices.amazon.com"
        region = "us-east-1"
        connetion_pool_max_size = 12
        configuration = Configuration()
        configuration.__init__(connetion_pool_max_size)
        api_client = ApiClient(
            access_key="",
            secret_key="",
            host=host,
            region=region,
            configuration=configuration,
        )
        default_api = DefaultApi(
            access_key="",
            secret_key="",
            host=host,
            region=region,
            api_client=api_client,
        )

        get_browse_node_request = GetBrowseNodesRequest(
            partner_tag="",
            partner_type=PartnerType.ASSOCIATES,
            marketplace="www.amazon.com",
            browse_node_ids=[],
            resources=[],
        )

        try:
            thread = default_api.get_browse_nodes(get_browse_node_request,
                                                  async_req=True)
            api_client.__del__()
            response = thread.get()
        except ApiException as exception:
            self.assertEquals(exception.status, 401, "Status Check")
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Code"],
                UNRECOGNIZED_CLIENT,
                "Error Code Check",
            )
            self.assertEquals(
                (json.loads(exception.body)["Errors"])[0]["Message"],
                "The Access Key ID or security token included in the request is invalid.",
                "Message Check",
            )
Esempio n. 4
0
class AmazonAPI:
    """Creates an instance containing your API credentials.

    Args:
        key (str): Your API key.
        secret (str): Your API secret.
        tag (str): The tag you want to use for the URL.
        country (str): Country code. Use one of the following:
            AU, BR, CA, FR, DE, IN, NL, IT, JP, MX, ES, TR, AE, UK, US.
        throttling (float, optional): It should be greater than 0 or False to disable throttling.
        This value determines wait time between API calls.
    """
    def __init__(self,
                 key: str,
                 secret: str,
                 tag: str,
                 country: str,
                 throttling=0.8):
        self.key = key
        self.secret = secret
        self.tag = tag
        try:
            if throttling is True:
                raise ValueError
            elif throttling is False:
                self.throttling = False
            else:
                self.throttling = float(throttling)
                if self.throttling <= 0:
                    raise ValueError
        except ValueError:
            raise AmazonException(
                'ValueError', 'Throttling should be False or greater than 0')
        self.country = country
        try:
            self.host = 'webservices.amazon.' + DOMAINS[country]
            self.region = REGIONS[country]
            self.marketplace = 'www.amazon.' + DOMAINS[country]
        except KeyError:
            raise AmazonException('KeyError', 'Invalid country code')
        self.last_query_time = time.time()
        self.api = DefaultApi(access_key=self.key,
                              secret_key=self.secret,
                              host=self.host,
                              region=self.region)

    def _throttle(self):
        if self.throttling:
            wait_time = 1 / self.throttling - (time.time() -
                                               self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
        self.last_query_time = time.time()

    def get_products(self,
                     product_ids: [str, list],
                     condition='Any',
                     merchant='All',
                     async_req=False):
        """Find product information for multiple products on Amazon.

        Args:
            product_ids (str|list): One or more item IDs like ASIN or product URL.
                Use a string separated by comma or as a list.
            condition (str, optional): Specify the product condition.
                Allowed values: Any, Collectible, New, Refurbished, Used.
                Defaults to Any.
            merchant (str, optional): Filters search results to return items
                having at least one offer sold by target merchant. Allowed values:
                All, Amazon. Defaults to All.
            async_req (bool, optional): Specify if a thread should be created to
                run the request. Defaults to False.

        Returns:
            list of instances: A list containing 1 instance for each product
                or None if no results.
        """

        # Clean up input data and remove 10 items limit from Amazon API
        if isinstance(product_ids, str):
            product_ids = [x.strip() for x in product_ids.split(',')]
        elif not isinstance(product_ids, list):
            raise AmazonException(
                'TypeError', 'Arg product_ids should be a list or string')
        asin_full_list = list(set([get_asin(x) for x in product_ids]))
        asin_full_list = list(chunks(asin_full_list, 10))

        results = []
        for asin_list in asin_full_list:
            try:
                request = GetItemsRequest(partner_tag=self.tag,
                                          partner_type=PartnerType.ASSOCIATES,
                                          marketplace=self.marketplace,
                                          merchant=merchant,
                                          condition=CONDITION[condition],
                                          item_ids=asin_list,
                                          resources=PRODUCT_RESOURCES)
            except KeyError:
                raise AmazonException('KeyError', 'Invalid condition value')
            except Exception as e:
                raise AmazonException('GetItemsError', e)

            for x in range(3):
                try:
                    # Send the request and create results
                    self._throttle()
                    if async_req:
                        thread = self.api.get_items(request, async_req=True)
                        response = thread.get()
                    else:
                        response = self.api.get_items(request)
                    break
                except ApiException as e:
                    if x == 2:
                        raise AmazonException('ApiException', e)
            try:
                if response.items_result is not None:
                    if len(response.items_result.items) > 0:
                        for item in response.items_result.items:
                            results.append(parse_product(item))
            except Exception as e:
                raise AmazonException('ResponseError', e)

        if results:
            return results
        else:
            return None

    def get_product(self,
                    product_id: str,
                    condition='Any',
                    merchant='All',
                    async_req=False):
        """Find product information for a specific product on Amazon.

        Args:
            product_id (str): One item ID like ASIN or product URL.
            condition (str, optional): Specify the product condition.
                Allowed values: Any, Collectible, New, Refurbished, Used.
                Defaults to Any.
            merchant (str, optional): Filters search results to return items
                having at least one offer sold by target merchant. Allowed values:
                All, Amazon. Defaults to All.
            async_req (bool, optional): Specify if a thread should be created to
                run the request. Defaults to False.

        Returns:
            instance: An instance containing all the available information
                for the product or None if no results.
        """
        if isinstance(product_id, list):
            raise AmazonException('TypeError',
                                  'Arg product_id should be string')
        if isinstance(product_id, str):
            check_product_id = product_id.split(',')
            if len(check_product_id) > 1:
                raise AmazonException(
                    'ValueError', 'Only 1 product ID is allowed, use '
                    'get_products for multiple requests')
        product = self.get_products(product_id,
                                    condition=condition,
                                    merchant=merchant,
                                    async_req=async_req)
        if product:
            return product[0]
        else:
            return None

    def search_products(self,
                        item_count=10,
                        item_page=1,
                        items_per_page=10,
                        keywords=None,
                        actor=None,
                        artist=None,
                        author=None,
                        brand=None,
                        title=None,
                        availability='Available',
                        browse_node=None,
                        condition='Any',
                        delivery=None,
                        max_price=None,
                        min_price=None,
                        min_rating=None,
                        min_discount=None,
                        merchant='All',
                        search_index='All',
                        sort_by=None,
                        async_req=False):
        """Search products on Amazon using different parameters. At least one of the
        following parameters should be used: keywords, actor, artist, author, brand,
        title.

        Args:
            item_count (int, optional): The total number of products to get. Should be between
                1 and 100. Defaults to 10.
            item_page (int, optional): The page where the results start from. Should be between
                1 and 10. Defaults to 1.
            items_per_page (int, optional): Products on each page. Should be between
                1 and 10. Defaults to 10.
            keywords (str, optional): A word or phrase that describes an item.
            actor (str, optional): Actor name associated with the item.
            artist (str, optional): Artist name associated with the item.
            author (str, optional): Author name associated with the item.
            brand (str, optional): Brand name associated with the item.
            title (str, optional): Title associated with the item.
            availability (str, optional): Filters available items on Amazon. Allowed values:
            Available, IncludeOutOfStock. Defaults to Available.
            browse_node (str, optional): A unique ID assigned by Amazon that
                identifies a product category or subcategory.
            condition (str, optional): The condition parameter filters offers by
                condition type. Allowed values: Any, Collectible, New, Refurbished, Used.
                Defaults to Any.
            delivery (list, optional): The delivery flag filters items which
                satisfy a certain delivery program promoted by the specific
                Amazon Marketplace. Allowed values: AmazonGlobal, FreeShipping,
                FulfilledByAmazon, Prime.
            max_price (int, optional): Filters search results to items with at
                least one offer price below the specified value.
            min_price (int, optional): Filters search results to items with at
                least one offer price above the specified value.
            min_rating (int, optional): Filters search results to items with
                customer review ratings above specified value.
            min_discount (int, optional): Filters search results to items with
                at least one offer having saving percentage above the specified
                value.
            merchant (str, optional): Filters search results to return items
                having at least one offer sold by target merchant. Allowed values:
                All, Amazon. Defaults to All.
            search_index (str, optional): Indicates the product category to
                search. Defaults to All.
            sort_by (str, optional): The way in which items in the response
                are sorted. Allowed values: AvgCustomerReviews, Featured,
                NewestArrivals, Price:HighToLow, Price:LowToHigh, Relevance.
            async_req (bool, optional): Specify if a thread should be created to
                run the request. Defaults to False.

        Returns:
            list of instances: A list containing 1 instance for each product
                or None if no results.
        """
        if items_per_page > 10 or items_per_page < 1:
            raise AmazonException(
                'ValueError', 'Arg items_per_page should be between 1 and 10')
        if item_count > 100 or item_count < 1:
            raise AmazonException(
                'ValueError', 'Arg item_count should be between 1 and 100')
        if item_page < 1:
            raise AmazonException('ValueError',
                                  'Arg item_page should be 1 or higher')
        if not keywords and not actor and not artist and not author and not brand and not title and not browse_node and not search_index:
            raise AmazonException(
                'ValueError', 'At least one of the following args must be '
                'provided: keywords, actor, artist, author, brand, '
                'title, browse_node, search_index')
        results = []
        while len(results) < item_count:
            try:
                request = SearchItemsRequest(
                    partner_tag=self.tag,
                    partner_type=PartnerType.ASSOCIATES,
                    actor=actor,
                    artist=artist,
                    author=author,
                    availability=availability,
                    brand=brand,
                    browse_node_id=browse_node,
                    condition=CONDITION[condition],
                    delivery_flags=delivery,
                    item_count=items_per_page,
                    item_page=item_page,
                    keywords=keywords,
                    max_price=max_price,
                    merchant=merchant,
                    min_price=min_price,
                    min_reviews_rating=min_rating,
                    min_saving_percent=min_discount,
                    offer_count=1,
                    resources=SEARCH_RESOURCES,
                    search_index=search_index,
                    sort_by=sort_by,
                    title=title)
            except KeyError:
                raise AmazonException('KeyError', 'Invalid condition value')
            except Exception as e:
                raise AmazonException('SearchItemsError', e)

            for x in range(3):
                try:
                    # Send the request and create results
                    self._throttle()
                    if async_req:
                        thread = self.api.search_items(request, async_req=True)
                        response = thread.get()
                    else:
                        response = self.api.search_items(request)
                    break
                except ApiException as e:
                    if x == 2:
                        raise AmazonException('ApiException', e)
            try:
                if response.search_result is not None:
                    if response.search_result.items is not None:
                        for item in response.search_result.items:
                            results.append(parse_product(item))
                            if len(results) >= item_count:
                                break
                        if len(response.search_result.items) < items_per_page:
                            break
                else:
                    break
                if response.errors is not None:
                    raise AmazonException(response.errors[0].code,
                                          response.errors[0].message)
            except Exception as e:
                if e.status == "NoResults":
                    break
                raise AmazonException('ResponseError', e)
            item_page += 1

        if results:
            return results
        else:
            return None

    def get_variations(self,
                       asin,
                       item_count=10,
                       item_page=1,
                       items_per_page=10,
                       condition='Any',
                       merchant='All',
                       async_req=False):
        """Returns a set of items that are the same product, but differ according to a
        consistent theme, for example size and color.

        Args:
            asin (str): One item ID like ASIN or product URL.
            item_count (int, optional): The total number of products to get. Should be between
                1 and 100. Defaults to 10.
            item_page (int, optional): The page where the results start from. Should be between
                1 and 10. Defaults to 1.
            items_per_page (int, optional): Products on each page. Should be between
                1 and 10. Defaults to 10.
            condition (str, optional): The condition parameter filters offers by
                condition type. Allowed values: Any, Collectible, New, Refurbished, Used.
                Defaults to Any.
            merchant (str, optional): Filters search results to return items
                having at least one offer sold by target merchant. Allowed values:
                All, Amazon. Defaults to All.
            async_req (bool, optional): Specify if a thread should be created to
                run the request. Defaults to False.

        Returns:
            list of instances: A list containing 1 instance for each product
                or None if no results.
        """
        if items_per_page > 10 or items_per_page < 1:
            raise AmazonException(
                'ValueError', 'Arg items_per_page should be between 1 and 10')
        if item_count > 100 or item_count < 1:
            raise AmazonException(
                'ValueError', 'Arg item_count should be between 1 and 100')
        if item_page < 1:
            raise AmazonException('ValueError',
                                  'Arg item_page should be 1 or higher')

        results = []
        while len(results) < item_count:
            try:
                request = GetVariationsRequest(
                    partner_tag=self.tag,
                    partner_type=PartnerType.ASSOCIATES,
                    marketplace=self.marketplace,
                    asin=get_asin(asin),
                    condition=CONDITION[condition],
                    merchant=merchant,
                    offer_count=1,
                    variation_count=items_per_page,
                    variation_page=item_page,
                    resources=VARIATION_RESOURCES)
            except KeyError:
                raise AmazonException('KeyError', 'Invalid condition value')
            except Exception as e:
                raise AmazonException('GetVariationsError', e)

            for x in range(3):
                try:
                    # Send the request and create results
                    self._throttle()
                    if async_req:
                        thread = self.api.get_variations(request,
                                                         async_req=True)
                        response = thread.get()
                    else:
                        response = self.api.get_variations(request)
                    break
                except ApiException as e:
                    if x == 2:
                        raise AmazonException('ApiException', e)
            try:
                if response.variations_result is not None:
                    if response.variations_result.items is not None:
                        for item in response.variations_result.items:
                            results.append(parse_product(item))
                            if len(results) >= item_count:
                                break
                        if len(response.variations_result.items
                               ) < items_per_page:
                            break
                else:
                    break
                if response.errors is not None:
                    raise AmazonException(response.errors[0].code,
                                          response.errors[0].message)
            except Exception as e:
                raise AmazonException('ResponseError', e)
            item_page += 1

        if results:
            return results
        else:
            return None

    def get_browsenodes(self, browse_nodes, async_req=False):
        """Get browse nodes information from Amazon.

        Args:
            browse_nodes (list): List of strings containing the browse node ids.
            async_req (bool, optional): Specify if a thread should be created to
                run the request. Defaults to False.

        Returns:
            dict: A dictionary containing the browse node information.
        """

        if isinstance(browse_nodes, list) is False:
            raise Exception('Browse nodes parameter should be a list')
        elif not browse_nodes:
            raise Exception('Browse nodes parameter can\'t be empty')

        try:
            request = GetBrowseNodesRequest(
                partner_tag=self.tag,
                partner_type=PartnerType.ASSOCIATES,
                marketplace=self.marketplace,
                browse_node_ids=browse_nodes,
                languages_of_preference=None,
                resources=BROWSE_RESOURCES)
        except ValueError as e:
            raise AmazonException("ValueError", e)

        try:
            self._throttle()
            if async_req:
                thread = self.api.get_browse_nodes(request, async_req=True)
                response = thread.get()
            else:
                response = self.api.get_browse_nodes(request)
        except ApiException as e:
            raise AmazonException('ApiException', e)

        try:
            if response.browse_nodes_result is not None:
                res = [
                    AmazonBrowseNode(item)
                    for item in response.browse_nodes_result.browse_nodes
                ]
                return parse_browsenode(res)
            if response.errors is not None:
                raise AmazonException(response.errors[0].code,
                                      response.errors[0].message)
        except TypeError as e:
            raise AmazonException("TypeError", e)
        except ValueError as e:
            raise AmazonException(ValueError, e)
        except AmazonException as e:
            raise AmazonException(e.status, e.reason)
        except Exception as e:
            raise AmazonException("General", e)
Esempio n. 5
0
class AmazonAPI:
    """
    Creates an instance containing your API credentials.

    params:
        *access_key (string)*
            Your API key
        *secret_key (string)*
            Your API secret
        *partner_tag (string)*
            The tag you want to use for the URL
        *country (string)*
            Country code
        *throttling (float, optional)*
            Reduce this value to wait longer between API calls
        *CacheReader (function)*
            Write a function to read the stored responses from previous api calls
        *CacheWriter (function)*
            Write a function to save the responses returned by amazon api calls
    
    
    """
    def __init__(self, access_key, secret_key, partner_tag, country='US', throttling=0.9, CacheReader=None, CacheWriter=None):
        """
            init AmazonApi. It is necessary to specify *access_key, secret_key, partner_tag, country* parameters
            By default the throttling parameter is set to 0.9. Increse or descrease this number to manage the time among different calls
            
            params:
                *access_key (string)*
                    amazon key of AWS account
                *secret_key (string)*
                    amazon secret of AWS account
                *partner_tag*
                    tag of the service Amazon Product Advertising account
                *country (string)*
                    possible values are defined in `amazon.constant.REGIONS`
                *throttling (float)*
                    value in the range (0,1] to wait among calls
                *CacheReader (function)*
                    function to read from cache 
                *CacheWriter (function)*
                    function to write results into the cache 

        """
        self.access_key = access_key
        self.secret_key = secret_key
        self.partner_tag = partner_tag
        self.throttling = throttling
        self.country = country
        self.host = 'webservices.amazon.' + DOMAINS[country]
        self.region = REGIONS[country]
        self.marketplace = 'www.amazon.' + DOMAINS[country]
        self.last_query_time = time.time()
        self.CacheReader = CacheReader
        self.CacheWriter = CacheWriter

        self.default_api = DefaultApi(
            access_key=self.access_key, secret_key=self.secret_key, host=self.host, region=self.region
        )
        

    def _cache_url(self, query):
        """
            return a url used to identify the call and retrieve it from the cache if CacheReader and CacheWriter are set.
        """
        return self.host + "?" + _quote_query(query)



    
    def search_items(self, actor=None, artist=None,author=None, availability=None, brand=None, browse_node_id=None, condition=None, currency_of_preference=None, delivery_flags=None, item_count=10,item_page=1, keywords=None, languages_of_preference=None, max_price=None, merchant="All", min_price=None,  min_reviews_rating=None, min_saving_percent=None, offer_count=1, search_index="All", sort_by= None,  title=None,  http_info=False, async_req=False, search_items_resource=SEARCH_RESOURCES):
        """ 
        Search products based on keywords
        Choose resources you want from SEARCH_RESOURCES enum 
        For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter 

        args:
            *actor (string)*
                actor to search products
            *artist (string)*
                artist to search products
            *author (string)*
                author to search products
            *availability (string)*
                availability to search products. Admitted values: "Available", "IncludeOutOfStock"
            *brand* (string, optional)*
                filter the products based on the brand
            *browse_node_id (string)*
                search products into a specific browse node
            *condition* (enum, optional)*
                filter the products based on the condition
            *currency_of_preference (string)*
                Currency of preference in which the prices information should be returned in response. By default the prices are returned in the default currency of the marketplace. Expected currency code format is the ISO 4217 currency code (i.e. USD, EUR etc.)
            *delivery_flags (list of string)*
                The delivery flag filters items which satisfy a certain delivery program promoted by the specific Amazon Marketplace. For example, Prime DeliveryFlag will return items having at least one offer which is Prime Eligible.
            *item_count (integer)*
                number of products returned. Values in the range [1,10]. Default 10
            *item_page (integer)*
                can be used to fetch the specific set/page of items to be returned from the available Search Results. The number of items returned in a page is determined by the item_count parameter. For e.g. if the third set of 5 items (i.e. items numbered 11 to 15) are desired for a search request, you may specify
            *keywords (string)*
                keywords to search products
            *languages_of_preference (list of string)*
                Languages in order of preference in which the item information should be returned in response. By default the item information is returned in the default language of the marketplace.
            *max_price (positive integers)*
                Filters search results to items with at least one offer price below the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $31.41.
            *merchant (string)*
                Filters search results to return items having at least one offer sold by target merchant. By default the value "All" is passed. 
            *min_price (positive integers)*
                Filters search results to items with at least one offer price above the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $32.41.
            *min_reviews_rating (positive integers less than 5)*
                Filters search results to items with customer review ratings above specified value.
            *min_saving_percent (integers less than 100)*
                Filters search results to items with at least one offer having saving percentage above the specified value
            *offer_count (integer)*
                The number of offers desired for each item in the search results. Default: 1
            *search_index (string)*
                search products based on an index. Default value "All"
            *sort_by (string, optional)*
                sort hte results based on the specification defined at https://webservices.amazon.com/paapi5/documentation/search-items.html#sortby-parameter
            *title (string)*
                Title associated with the item. Title searches are subset of Keywords searches. Use a Keywords search if a Title search does not return desired items.
            *http_info (boolean)*
                specify if http header should be returned
            *async_req (boolean)*
                specify if a thread should be created to run the request
            *search_items_resource (list)*
                For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter. By deafult all possible resources are requested
        return
            Dict with 
                *data* 
                    contains the AmazonProduct list
                *http_info*
                    contains the http header information if requested. By default None
        """

        try:
            if item_count > 10 or item_count < 1:
                item_count = 10
            cache_url = self._cache_url(
                {'partner_tag':self.partner_tag,
                'partner_type':PartnerType.ASSOCIATES,
                'keywords':keywords,
                'search_index':search_index,
                'item_count':item_count,
                'condition':condition,
                'browse_node_id': browse_node_id,
                'brand': brand,
                'sort_by': sort_by,
                'actor': actor,
                'artist': artist,
                'author': author,
                'availability': availability,
                'currency_of_preference': currency_of_preference,
                'delivery_flags': delivery_flags,
                'item_page': item_page,
                'languages_of_preference': languages_of_preference,
                'max_price': max_price,
                'merchant': merchant,
                'min_price': min_price,
                'min_reviews_rating': min_reviews_rating,
                'min_saving_percent': min_saving_percent,
                'offer_count': offer_count,
                'title': title
                }
            )
            
            if self.CacheReader:
                cached_response_text = self.CacheReader(cache_url)
                if cached_response_text is not None:
                    return {'data': pickle.loads(cached_response_text['data']), 'http_info': pickle.loads(cached_response_text['http_info'])}

            search_items_request = SearchItemsRequest(
                partner_tag=self.partner_tag,
                partner_type=PartnerType.ASSOCIATES,
                actor=actor,
                artist=artist,
                author=author,
                availability=availability,
                brand=brand,
                browse_node_id=browse_node_id,
                condition=condition,
                currency_of_preference=currency_of_preference,
                delivery_flags=delivery_flags,
                item_count=item_count,
                item_page=item_page,
                keywords=keywords,
                languages_of_preference=languages_of_preference,
                max_price=max_price,
                merchant=merchant,
                min_price=min_price,
                min_reviews_rating=min_reviews_rating,
                min_saving_percent=min_saving_percent,
                offer_count=offer_count,
                resources=search_items_resource,
                search_index=search_index,
                sort_by=sort_by,
                title=title
            )
            
            
        except ValueError as exception:
            #print("Error in forming SearchItemsRequest: ", exception)
            raise AmazonException("ValueError", exception)
        except AmazonException as exception:
            #print("Error in forming SearchItemsRequest: ", exception)
            raise AmazonException(exception.status, exception.reason)

        try:
            """ Sending request """
            wait_time = 1 / self.throttling - (time.time() - self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
            self.last_query_time = time.time()
            resp_http = None
            if http_info:
                response_with_http_info = self.default_api.search_items_with_http_info(search_items_request)
                """ Parse response """
                if response_with_http_info is not None:
                    response = response_with_http_info[0]
                    resp_http = response_with_http_info[2]
                    if response.search_result is not None:
                        resp = [ AmazonProduct(item) for item in response.search_result.items]
                        if self.CacheWriter:
                            self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                        return {'data': resp, 'http_info': resp_http}
                    if response.errors is not None:
                        #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                        #print("Error code", response.errors[0].code)
                        #print("Error message", response.errors[0].message)
                        raise AmazonException(response.errors[0].code, response.errors[0].message)

            else:
                if async_req:
                    thread = self.default_api.search_items(search_items_request, async_req=True)
                    response = thread.get()
                else:
                    response = self.default_api.search_items(search_items_request)
                """ Parse response """
                if response.search_result is not None:
                    resp = [ AmazonProduct(item) for item in response.search_result.items]
                    if self.CacheWriter:
                        self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                    return {'data': resp, 'http_info': resp_http}
                if response.errors is not None:
                    #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                    #print("Error code", response.errors[0].code)
                    #print("Error message", response.errors[0].message)
                    if response.errors[0].code == "NoResults":
                        resp = []
                        if self.CacheWriter:
                            self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))  
                    raise AmazonException(response.errors[0].code, response.errors[0].message)

        except ApiException as exception:
            #print("Error calling PA-API 5.0!")
            #print("Status code:", exception.status)
            #print("Errors :", exception.body)
            #print("Request ID:", exception.headers["x-amzn-RequestId"])
            raise AmazonException("ApiException", exception.body)

        except TypeError as exception:
            #print("TypeError :", exception)
            raise AmazonException("TypeError", exception)

        except ValueError as exception:
            #print("ValueError :", exception)
            raise AmazonException(ValueError, exception)

        except AmazonException as exception:
            raise AmazonException(exception.status, exception.reason)
        
        except Exception as exception:
            raise AmazonException("General", exception)


    
    def search_items_pool(self, actor=None, artist=None,author=None, availability=None, brand=None, browse_node_id=None, condition=None, currency_of_preference=None, delivery_flags=None, item_count=10,item_page=1, keywords=None, languages_of_preference=None, max_price=None, merchant="All", min_price=None,  min_reviews_rating=None, min_saving_percent=None, offer_count=1, search_index="All", sort_by= None,  title=None, search_items_resource=SEARCH_RESOURCES ,connetion_pool_max_size=12):
        """ 
        Search products based on keywords. You can specify max connection pool size here. We recommend a value equal to cpu_count * 5.
        Choose resources you want from SEARCH_RESOURCES enum.
        For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter 

        args:
            *actor (string)*
                actor to search products
            *artist (string)*
                artist to search products
            *author (string)*
                author to search products
            *availability (string)*
                availability to search products. Admitted values: "Available", "IncludeOutOfStock"
            *brand* (string, optional)*
                filter the products based on the brand
            *browse_node_id (string)*
                search products into a specific browse node
            *condition* (enum, optional)*
                filter the products based on the condition
            *currency_of_preference (string)*
                Currency of preference in which the prices information should be returned in response. By default the prices are returned in the default currency of the marketplace. Expected currency code format is the ISO 4217 currency code (i.e. USD, EUR etc.)
            *delivery_flags (list of string)*
                The delivery flag filters items which satisfy a certain delivery program promoted by the specific Amazon Marketplace. For example, Prime DeliveryFlag will return items having at least one offer which is Prime Eligible.
            *item_count (integer)*
                number of products returned. Values in the range [1,10]. Default 10
            *item_page (integer)*
                can be used to fetch the specific set/page of items to be returned from the available Search Results. The number of items returned in a page is determined by the item_count parameter. For e.g. if the third set of 5 items (i.e. items numbered 11 to 15) are desired for a search request, you may specify
            *keywords (string)*
                keywords to search products
            *languages_of_preference (list of string)*
                Languages in order of preference in which the item information should be returned in response. By default the item information is returned in the default language of the marketplace.
            *max_price (positive integers)*
                Filters search results to items with at least one offer price below the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $31.41.
            *merchant (string)*
                Filters search results to return items having at least one offer sold by target merchant. By default the value "All" is passed. 
            *min_price (positive integers)*
                Filters search results to items with at least one offer price above the specified value. Prices appear in lowest currency denomination. For example, in US marketplace, 3241 is $32.41.
            *min_reviews_rating (positive integers less than 5)*
                Filters search results to items with customer review ratings above specified value.
            *min_saving_percent (integers less than 100)*
                Filters search results to items with at least one offer having saving percentage above the specified value
            *offer_count (integer)*
                The number of offers desired for each item in the search results. Default: 1
            *search_index (string)*
                search products based on an index. Default value "All"
            *sort_by (string, optional)*
                sort hte results based on the specification defined at https://webservices.amazon.com/paapi5/documentation/search-items.html#sortby-parameter
            *title (string)*
                Title associated with the item. Title searches are subset of Keywords searches. Use a Keywords search if a Title search does not return desired items.
            *search_items_resource (list)*
                For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter. By deafult all possible resources are requested
            *connetion_pool_max_size (integer)*
                sice of connection pool. Default 12
        return
            Dict with 
                *data* 
                    contains the AmazonProduct list
                *http_info*
                    contains the http header information if requested. By default None
        """
        
        configuration = Configuration()
        configuration.__init__(connetion_pool_max_size)

        """ API Client Declaration """
        api_client = ApiClient(
            access_key=self.access_key,
            secret_key=self.secret_key,
            host=self.host,
            region=self.region,
            configuration=configuration,
        )

        """ API declaration """
        default_api = DefaultApi(api_client=api_client)

        """ Forming request """
        try:
            if item_count > 10 or item_count < 1:
                item_count = 10

            cache_url = self._cache_url(
                {'partner_tag':self.partner_tag,
                'partner_type':PartnerType.ASSOCIATES,
                'keywords':keywords,
                'search_index':search_index,
                'item_count':item_count,
                'condition':condition,
                'browse_node_id': browse_node_id,
                'brand': brand,
                'sort_by': sort_by,
                'actor': actor,
                'artist': artist,
                'author': author,
                'availability': availability,
                'currency_of_preference': currency_of_preference,
                'delivery_flags': delivery_flags,
                'item_page': item_page,
                'languages_of_preference': languages_of_preference,
                'max_price': max_price,
                'merchant': merchant,
                'min_price': min_price,
                'min_reviews_rating': min_reviews_rating,
                'min_saving_percent': min_saving_percent,
                'offer_count': offer_count,
                'title': title
                }
            )
            
            if self.CacheReader:
                cached_response_text = self.CacheReader(cache_url)
                if cached_response_text is not None:
                    return {'data': pickle.loads(cached_response_text['data']), 'http_info': pickle.loads(cached_response_text['http_info'])}

            search_items_request = SearchItemsRequest(
                partner_tag=self.partner_tag,
                partner_type=PartnerType.ASSOCIATES,
                actor=actor,
                artist=artist,
                author=author,
                availability=availability,
                brand=brand,
                browse_node_id=browse_node_id,
                condition=condition,
                currency_of_preference=currency_of_preference,
                delivery_flags=delivery_flags,
                item_count=item_count,
                item_page=item_page,
                keywords=keywords,
                languages_of_preference=languages_of_preference,
                max_price=max_price,
                merchant=merchant,
                min_price=min_price,
                min_reviews_rating=min_reviews_rating,
                min_saving_percent=min_saving_percent,
                offer_count=offer_count,
                resources=search_items_resource,
                search_index=search_index,
                sort_by=sort_by,
                title=title
            )
            

        except ValueError as exception:
            #print("Error in forming SearchItemsRequest: ", exception)
            raise AmazonException("ValueError", exception)

        try:
            """ Sending request """
            wait_time = 1 / self.throttling - (time.time() - self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
            self.last_query_time = time.time()
            resp_http = None
            response = default_api.search_items(search_items_request)

            """ Parse response """
            if response.search_result is not None:
                resp = [ AmazonProduct(item) for item in response.search_result.items]
                if self.CacheWriter:
                    self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                return {'data': resp, 'http_info': resp_http}
            if response.errors is not None:
                #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                #print("Error code", response.errors[0].code)
                #print("Error message", response.errors[0].message)
                raise AmazonException(response.errors[0].code, response.errors[0].message)

        except ApiException as exception:
            #print("Error calling PA-API 5.0!")
            #print("Status code:", exception.status)
            #print("Errors :", exception.body)
            #print("Request ID:", exception.headers["x-amzn-RequestId"])
            raise AmazonException("ApiException", exception.body)

        except TypeError as exception:
            #print("TypeError :", exception)
            raise AmazonException("TypeError", exception)

        except ValueError as exception:
            #print("ValueError :", exception)
            raise AmazonException(ValueError, exception)

        except AmazonException as exception:
            raise AmazonException(exception.status, exception.reason)
        
        except Exception as exception:
            raise AmazonException("General", exception)
            raise Exception(exception)

    """ Choose resources you want from GetVariationsResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-variations.html#resources-parameter """
    def get_variations(self, asin, condition=None, currency_of_preference=None, languages_of_preference=None, merchant="All", offer_count=1, variation_count=10, variation_page=1, async_req=False, http_info=False, get_variations_resources=VARIATION_RESOURCES):
        """ 
        Get product variation using the asin of orginal product.
        Choose resources you want from VARIATION_RESOURCES enum.
        For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-variations.html#request-parameters

        args:
            *asin (string)*
                asin of the product for which we want the variations
            *condition* (enum, optional)*
                filter the products based on the condition
            *currency_of_preference (string)*
                specify the currency of returned results
            *languages_of_preference (list of string)*
                specify the language of returned results
            *merchant (string)*
                Filters search results to return items having at least one offer sold by target merchant. By default the value "All" is passed. 
            *offer_count (integer)*
                The number of offers desired for each item in the search results. Default: 1
            *variation_count (integer)*
                Number of variations to be returned per page. Default: 10
            *variation_page (integer)*
                Page number of variations returned by get_variations. Default: 1 
            *http_info (boolean)*
                specify if http header should be returned
            *async_req (boolean)*
                specify if a thread should be created to run the request
            *get_variations_resources (list)*
                For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-variations.html#request-parameters. By deafult all possible resources are requested
            
        return
            Dict with 
                *data* 
                    contains the AmazonProduct list
                *http_info*
                    contains the http header information if requested. By default None
        """
        try:
            cache_url = self._cache_url(
                {'partner_tag':self.partner_tag,
                'partner_type':PartnerType.ASSOCIATES,
                'asin':asin,
                'condition': condition,
                'currency_of_preference': currency_of_preference,
                'languages_of_preference':languages_of_preference,
                'merchant':merchant,
                'offer_count': offer_count,
                'variation_count': variation_count,
                'variation_page': variation_page
                }
            )
            
            if self.CacheReader:
                cached_response_text = self.CacheReader(cache_url)
                if cached_response_text is not None:
                    return {'data': pickle.loads(cached_response_text['data']), 'http_info': pickle.loads(cached_response_text['http_info'])}

            get_variations_request = GetVariationsRequest(
                partner_tag=self.partner_tag,
                partner_type=PartnerType.ASSOCIATES,
                marketplace=self.marketplace,
                asin=asin,
                condition=condition,
                currency_of_preference=currency_of_preference,
                languages_of_preference=languages_of_preference,
                merchant=merchant,
                offer_count=offer_count,
                variation_count=variation_count,
                variation_page=variation_page,
                resources=get_variations_resources
            )
            
        except ValueError as exception:
            #print("Error in forming GetVariationsRequest: ", exception)
            raise AmazonException("ValueError", exception)

        try:
            wait_time = 1 / self.throttling - (time.time() - self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
            self.last_query_time = time.time()
            resp_http = None
            """ Sending request """
            if http_info:
                response_with_http_info = self.default_api.get_variations_with_http_info(get_variations_request)

                """ Parse response """
                if response_with_http_info is not None:
                    response = response_with_http_info[0]
                    resp_http = response_with_http_info[2]
                    if response.variations_result is not None:
                        resp = [ AmazonProduct(item) for item in response.variations_result.items]
                        if self.CacheWriter:
                            self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                        return {'data': resp, 'http_info': resp_http}

                    if response.errors is not None:
                        #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                        #print("Error code", response.errors[0].code)
                        #print("Error message", response.errors[0].message)
                        raise AmazonException(response.errors[0].code, response.errors[0].message)
            else:
                if async_req:
                    thread = self.default_api.get_variations(get_variations_request, async_req=True)
                    response = thread.get()
                else:
                    response = self.default_api.get_variations(get_variations_request)

                """ Parse response """
                if response.variations_result is not None:
                    resp = [ AmazonProduct(item) for item in response.variations_result.items]
                    if self.CacheWriter:
                        self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                    return {'data': resp, 'http_info': resp_http}

                if response.errors is not None:
                    #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                    #print("Error code", response.errors[0].code)
                    #print("Error message", response.errors[0].message)
                    raise AmazonException(response.errors[0].code, response.errors[0].message)

        except ApiException as exception:
            #print("Error calling PA-API 5.0!")
            #print("Status code:", exception.status)
            #print("Errors :", exception.body)
            #print("Request ID:", exception.headers["x-amzn-RequestId"])
            raise AmazonException("ApiException", exception.body)

        except TypeError as exception:
            #print("TypeError :", exception)
            raise AmazonException("TypeError", exception)

        except ValueError as exception:
            #print("ValueError :", exception)
            raise AmazonException(ValueError, exception)

        except AmazonException as exception:
            raise AmazonException(exception.status, exception.reason)
        
        except Exception as exception:
            raise AmazonException("General", exception)


    """ Choose resources you want from GetItemsResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter """
    def get_items(self, item_ids=[], condition=None, currency_of_preference=None, item_id_type="ASIN",languages_of_preference=None, merchant="All", offer_count=1, http_info=False, async_req=False, get_items_resource=ITEM_RESOURCES):
        """ 
        Get items' information.
        Choose resources you want from ITEM_RESOURCES enum 
        For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#ItemLookup-rp

        args:
            *item_ids (list of string)*
                list of asin of the products of interest
            *condition* (enum, optional)*
                filter the products based on the condition
            *currency_of_preference (string)*
                specify the currency of returned results
            *item_id_type (string)*
                Type of item identifier used to look up an item. Default: ASIN
            *languages_of_preference (list of string)*
                Languages in order of preference in which the item information should be returned in response. By default the item information is returned in the default language of the marketplace
            *merchant (string)*
                Filters search results to return items having at least one offer sold by target merchant. By default the value "All" is passed. 
            *offer_count (integer)*
                The number of offers desired for each item in the search results. Default: 1
            *http_info (boolean)*
                specify if http header should be returned
            *async_req (boolean)*
                specify if a thread should be created to run the request
            *get_items_resource (list)*
                For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#ItemLookup-rp. By deafult all possible resources are requested
            
        return
            Dict with 
                *data* 
                    Dict of ASIN to AmazonProduct object
                *http_info*
                    contains the http header information if requested. By default None
        """
        
        if len(item_ids) == 0:
            raise Exception('No item ids specified')
        
        """ Forming request """
        try:
            cache_url = self._cache_url(
                {'partner_tag':self.partner_tag,
                'partner_type':PartnerType.ASSOCIATES,
                'item_ids':item_ids,    
                'condition':condition,
                'currency_of_preference': currency_of_preference,
                'item_id_type': item_id_type,
                'languages_of_preference': languages_of_preference,
                'merchant': merchant,
                'offer_count': offer_count
                }
            )
            
            if self.CacheReader:
                cached_response_text = self.CacheReader(cache_url)
                if cached_response_text is not None:
                    return {'data': parse_response_item( pickle.loads(cached_response_text['data']) ), 'http_info': pickle.loads(cached_response_text['http_info'])}

            get_items_request = GetItemsRequest(
                partner_tag=self.partner_tag,
                partner_type=PartnerType.ASSOCIATES,
                marketplace=self.marketplace,
                item_ids=item_ids,
                condition=condition,
                currency_of_preference=currency_of_preference,
                item_id_type=item_id_type,
                languages_of_preference=languages_of_preference,
                merchant=merchant,
                offer_count=offer_count,
                resources=get_items_resource
            )
            

        except ValueError as exception:
            #print("Error in forming GetItemsRequest: ", exception)
            raise AmazonException("ValueError", exception)

        try:
            wait_time = 1 / self.throttling - (time.time() - self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
            self.last_query_time = time.time()
            resp_http = None

            if http_info:
                response_with_http_info = self.default_api.get_items_with_http_info(
                    get_items_request
                )

                """ Parse response """
                if response_with_http_info is not None:
                    response = response_with_http_info[0]
                    resp_http = response_with_http_info[2]
                    if response.items_result is not None:
                        resp = [ AmazonProduct(item) for item in response.items_result.items]
                        if self.CacheWriter:
                            self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                        return {'data': parse_response_item(resp), 'http_info': resp_http}
                        
                    if response.errors is not None:
                        #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                        #print("Error code", response.errors[0].code)
                        #print("Error message", response.errors[0].message)
                        raise AmazonException(response.errors[0].code, response.errors[0].message)

            else:
                """ Sending request """
                if async_req:
                    thread = self.default_api.get_items(get_items_request, async_req=True)
                    response = thread.get()
                else:
                    response = self.default_api.get_items(get_items_request)

                """ Parse response """
                if response.items_result is not None:
                    resp = [ AmazonProduct(item) for item in response.items_result.items]
                    if self.CacheWriter:
                        self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                    return {'data': parse_response_item(resp), 'http_info': resp_http}

                if response.errors is not None:
                    #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                    #print("Error code", response.errors[0].code)
                    #print("Error message", response.errors[0].message)
                    raise AmazonException(response.errors[0].code, response.errors[0].message)


        except ApiException as exception:
            #print("Error calling PA-API 5.0!")
            #print("Status code:", exception.status)
            #print("Errors :", exception.body)
            #print("Request ID:", exception.headers["x-amzn-RequestId"])
            raise AmazonException("ApiException", exception.body)

        except TypeError as exception:
            #print("TypeError :", exception)
            raise AmazonException("TypeError", exception)

        except ValueError as exception:
            #print("ValueError :", exception)
            raise AmazonException(ValueError, exception)

        except AmazonException as exception:
            raise AmazonException(exception.status, exception.reason)
        
        except Exception as exception:
            raise AmazonException("General", exception)



    """ Choose resources you want from GetBrowseNodesResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html#resources-parameter """
    def get_browse_nodes(self, browse_node_ids=[], languages_of_preference = None, http_info=False, async_req=False, get_browse_node_resources=BROWSE_RESOURCES):
        """" 
        Get browse nodes' information.
        Choose resources you want from BROWSE_RESOURCES enum 
        For more details, refer: https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html#request-parameters

        args:
            *browse_node_ids (list of string)*
                list of browse node ids
            *languages_of_preference (list of string)*
                specify the language of returned results
            *http_info (boolean)*
                specify if http header should be returned
            *async_req (boolean)*
                specify if a thread should be created to run the request
            
            *get_browse_node_resources (list)*
                For more details, refer: https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html#request-parameters. By deafult all possible resources are requested
            
        return
            Dict with 
                *data* 
                    Dict of BrowseNodeID to AmazonBrowseNode object
                *http_info*
                    contains the http header information if requested. By default None
        """
        
        if isinstance(browse_node_ids, list) == False or len (browse_node_ids) == 0:
            raise Exception('Browse node ids are not in the right format')
        
        """ Forming request """
        try:
            cache_url = self._cache_url(
                {'partner_tag':self.partner_tag,
                'partner_type':PartnerType.ASSOCIATES,
                'browse_node_ids':browse_node_ids,
                'languages_of_preference':languages_of_preference }
                )
            
            if self.CacheReader:
                cached_response_text = self.CacheReader(cache_url)
                if cached_response_text is not None:
                    return {'data': parse_response_browse_node (pickle.loads(cached_response_text['data']) ), 'http_info': pickle.loads(cached_response_text['http_info'])}

            get_browse_node_request = GetBrowseNodesRequest(
                partner_tag=self.partner_tag,
                partner_type=PartnerType.ASSOCIATES,
                marketplace=self.marketplace,
                languages_of_preference=languages_of_preference,
                browse_node_ids=browse_node_ids,
                resources=get_browse_node_resources,
            )
            
        except ValueError as exception:
            #print("Error in forming GetBrowseNodesRequest: ", exception)
            raise AmazonException("ValueError", exception)

        try:
            wait_time = 1 / self.throttling - (time.time() - self.last_query_time)
            if wait_time > 0:
                time.sleep(wait_time)
            self.last_query_time = time.time()
            resp_http = None

            if http_info:
                response_with_http_info = self.default_api.get_browse_nodes_with_http_info(get_browse_node_request)

                """ Parse response """
                if response_with_http_info is not None:
                    response = response_with_http_info[0]
                    resp_http = response_with_http_info[2]
                    if response.browse_nodes_result is not None:
                        resp = [ AmazonBrowseNode(node) for node in response.browse_nodes_result.browse_nodes]
                        if self.CacheWriter:
                            self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                        return {'data': parse_response_browse_node(resp), 'http_info': resp_http}
                        
                    if response.errors is not None:
                        #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                        #print("Error code", response.errors[0].code)
                        #print("Error message", response.errors[0].message)
                        raise AmazonException(response.errors[0].code, response.errors[0].message)

            else:
                """ Sending request """
                if async_req:
                    thread = self.default_api.get_browse_nodes(get_browse_node_request, async_req=True)
                    response = thread.get()
                else:
                    response = self.default_api.get_browse_nodes(get_browse_node_request)

                """ Parse response """
                if response.browse_nodes_result is not None:
                    resp = [ AmazonBrowseNode(item) for item in response.browse_nodes_result.browse_nodes]
                    if self.CacheWriter:
                        self.CacheWriter(cache_url, pickle.dumps(resp), pickle.dumps(resp_http))
                    return {'data': parse_response_browse_node(resp), 'http_info': resp_http}
                    
                if response.errors is not None:
                    #print("\nPrinting Errors:\nPrinting First Error Object from list of Errors")
                    #print("Error code", response.errors[0].code)
                    #print("Error message", response.errors[0].message)
                    raise AmazonException(response.errors[0].code, response.errors[0].message)

        except ApiException as exception:
            #print("Error calling PA-API 5.0!")
            #print("Status code:", exception.status)
            #print("Errors :", exception.body)
            #print("Request ID:", exception.headers["x-amzn-RequestId"])
            raise AmazonException("ApiException", exception.body)

        except TypeError as exception:
            #print("TypeError :", exception)
            raise AmazonException("TypeError", exception)

        except ValueError as exception:
            #print("ValueError :", exception)
            raise AmazonException(ValueError, exception)

        except AmazonException as exception:
            raise AmazonException(exception.status, exception.reason)
        
        except Exception as exception:
            raise AmazonException("General", exception)
Esempio n. 6
0
def get_browse_nodes():
    """ Following are your credentials """
    """ Please add your access key here """
    access_key = "<YOUR ACCESS KEY>"
    """ Please add your secret key here """
    secret_key = "<YOUR SECRET KEY>"
    """ Please add your partner tag (store/tracking id) here """
    partner_tag = "<YOUR PARTNER TAG>"
    """ PAAPI host and region to which you want to send request """
    """ For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region"""
    host = "webservices.amazon.com"
    region = "us-east-1"
    """ API declaration """
    default_api = DefaultApi(access_key=access_key,
                             secret_key=secret_key,
                             host=host,
                             region=region)
    """ Request initialization"""
    """ Specify browse_node id(s) """
    browse_node_ids = ["3040", "0", "3045"]
    """ Specify language of preference """
    """ For more details, refer https://webservices.amazon.com/paapi5/documentation/locale-reference.html"""
    languages_of_preference = ["es_US"]
    """ Choose resources you want from GetBrowseNodesResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html#resources-parameter """
    get_browse_node_resources = [
        GetBrowseNodesResource.ANCESTOR,
        GetBrowseNodesResource.CHILDREN,
    ]
    """ Forming request """
    try:
        get_browse_node_request = GetBrowseNodesRequest(
            partner_tag=partner_tag,
            partner_type=PartnerType.ASSOCIATES,
            marketplace="www.amazon.com",
            languages_of_preference=languages_of_preference,
            browse_node_ids=browse_node_ids,
            resources=get_browse_node_resources,
        )
    except ValueError as exception:
        print("Error in forming GetBrowseNodesRequest: ", exception)
        return

    try:
        """ Sending request """
        response = default_api.get_browse_nodes(get_browse_node_request)

        print("API called Successfully")
        print("Complete Response:\n", response)
        """ Parse response """
        if response.browse_nodes_result is not None:
            print("Printing all browse node information in BrowseNodesResult:")
            response_list = parse_response(
                response.browse_nodes_result.browse_nodes)
            for browse_node_id in browse_node_ids:
                print(
                    "Printing information about the browse node with Id: ",
                    browse_node_id,
                )
                if browse_node_id in response_list:
                    browse_node = response_list[browse_node_id]
                    if browse_node is not None:
                        if browse_node.id is not None:
                            print("BrowseNodeId: ", browse_node.id)
                        if browse_node.display_name is not None:
                            print("DisplayName: ", browse_node.display_name)
                        if browse_node.context_free_name is not None:
                            print("ContextFreeName: ",
                                  browse_node.context_free_name)
                else:
                    print("BrowseNode not found, check errors")

        if response.errors is not None:
            print(
                "\nPrinting Errors:\nPrinting First Error Object from list of Errors"
            )
            print("Error code", response.errors[0].code)
            print("Error message", response.errors[0].message)

    except ApiException as exception:
        print("Error calling PA-API 5.0!")
        print("Status code:", exception.status)
        print("Errors :", exception.body)
        print("Request ID:", exception.headers["x-amzn-RequestId"])

    except TypeError as exception:
        print("TypeError :", exception)

    except ValueError as exception:
        print("ValueError :", exception)

    except Exception as exception:
        print("Exception :", exception)