コード例 #1
0
    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 > 10 or item_page < 1:
            raise AmazonException('ValueError',
                                  'Arg item_page should be between 1 and 10')

        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:
                    # Wait before doing the 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()

                    # Send the request and create results
                    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:
                    for item in response.variations_result.items:
                        results.append(parse_product(item))
                        if len(results) >= item_count:
                            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 item_page > 10:
                break

        if results:
            return results
        else:
            return None
コード例 #2
0
def get_variations():
    """ 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 ASIN """
    asin = "B07H65KP63"
    """ 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 GetVariationsResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-variations.html#resources-parameter """
    get_variations_resources = [
        GetVariationsResource.ITEMINFO_TITLE,
        GetVariationsResource.OFFERS_LISTINGS_PRICE,
        GetVariationsResource.VARIATIONSUMMARY_VARIATIONDIMENSION,
    ]
    """ Forming request """
    try:
        get_variations_request = GetVariationsRequest(
            partner_tag=partner_tag,
            partner_type=PartnerType.ASSOCIATES,
            marketplace="www.amazon.com",
            languages_of_preference=languages_of_preference,
            asin=asin,
            resources=get_variations_resources,
        )
    except ValueError as exception:
        print("Error in forming GetVariationsRequest: ", exception)
        return

    try:
        """ Sending request """
        response = default_api.get_variations(get_variations_request)

        print("API called Successfully")
        print("Complete Response:", response)
        """ Parse response """
        if response.variations_result is not None:
            print("Printing VariationSummary:")
            if (response.variations_result.variation_summary is not None
                    and response.variations_result.variation_summary.
                    variation_count is not None):
                print(
                    "VariationCount: ",
                    response.variations_result.variation_summary.
                    variation_count,
                )

            print("Printing first item information in VariationsResult:")
            item_0 = response.variations_result.items[0]
            if item_0 is not None:
                if item_0.asin is not None:
                    print("ASIN: ", item_0.asin)
                if item_0.detail_page_url is not None:
                    print("DetailPageURL: ", item_0.detail_page_url)
                if (item_0.item_info is not None
                        and item_0.item_info.title is not None
                        and item_0.item_info.title.display_value is not None):
                    print("Title: ", item_0.item_info.title.display_value)
                if (item_0.offers is not None
                        and item_0.offers.listings is not None
                        and item_0.offers.listings[0].price is not None
                        and item_0.offers.listings[0].price.display_amount
                        is not None):
                    print("Buying Price: ",
                          item_0.offers.listings[0].price.display_amount)
        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)
コード例 #3
0
    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)