コード例 #1
0
    def __init__(self,
                 access_key,
                 secret_key,
                 host,
                 region,
                 configuration=None,
                 header_name=None,
                 header_value=None,
                 cookie=None):
        if configuration is None:
            configuration = Configuration()
        self.configuration = configuration

        self.pool = None
        self.rest_client = rest.RESTClientObject(configuration)
        self.default_headers = {}
        if header_name is not None:
            self.default_headers[header_name] = header_value
        self.cookie = cookie
        # Set default User-Agent.
        self.user_agent = 'paapi5-python-sdk/1.0.0'

        self.access_key = access_key
        self.secret_key = secret_key
        self.host = host
        self.region = region
コード例 #2
0
    def test_get_browse_nodes_http_info_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_with_http_info(
                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",
            )
コード例 #3
0
    def test_get_browse_nodes_http_Info_aync_IncompleteSignature(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=DUMMY_ACCESS_KEY,
            secret_key=DUMMY_SECRET_KEY,
            host=host,
            region=region,
            configuration=configuration,
        )
        default_api = DefaultApi(
            access_key=DUMMY_ACCESS_KEY,
            secret_key=DUMMY_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_with_http_info(
                get_browse_node_request, async_req=True)
            api_client.__del__()
            response = thread.get()
        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",
            )
def search_items():
    """ 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"
    """ You can specify max connection pool size here. By default it's cpu_count * 5."""
    connetion_pool_max_size = 12
    configuration = Configuration()
    configuration.__init__(connetion_pool_max_size)
    """ API Client Declaration """
    api_client = ApiClient(
        access_key=access_key,
        secret_key=secret_key,
        host=host,
        region=region,
        configuration=configuration,
    )
    """ API declaration """
    default_api = DefaultApi(api_client=api_client)
    """ Request initialization"""
    """ Specify keywords """
    keywords = "Harry Potter"
    """ Specify the category in which search request is to be made """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/use-cases/organization-of-items-on-amazon/search-index.html """
    search_index = "All"
    """ Specify item count to be returned in search result """
    item_count = 1
    """ Choose resources you want from SearchItemsResource enum """
    """ For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter """
    search_items_resource = [
        SearchItemsResource.IMAGES_PRIMARY_LARGE,
        SearchItemsResource.ITEMINFO_TITLE,
        SearchItemsResource.OFFERS_LISTINGS_PRICE,
    ]
    """ Forming request """
    try:
        search_items_request = SearchItemsRequest(
            partner_tag=partner_tag,
            partner_type=PartnerType.ASSOCIATES,
            keywords=keywords,
            search_index=search_index,
            item_count=item_count,
            resources=search_items_resource,
        )
    except ValueError as exception:
        print("Error in forming SearchItemsRequest: ", exception)
        return

    try:
        """ Sending request """
        response = default_api.search_items(search_items_request)

        print("API called Successfully")
        print("Complete Response:", response)
        """ Parse response """
        if response.search_result is not None:
            print("Printing first item information in SearchResult:")
            item_0 = response.search_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)
コード例 #5
0
    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)