コード例 #1
0
 def search(self, keywords):
     """Adding method to test amz searches from the CLI, unused otherwise"""
     return self.api.search_items(
         SearchItemsRequest(
             partner_tag=self.tag,
             partner_type=PartnerType.ASSOCIATES,
             keywords=keywords,
         ))
コード例 #2
0
def get_kindle_books():
    env_path = os.path.join(os.path.dirname(__file__), '.env')
    load_dotenv(env_path)

    AMAZON_ACCESS_KEY = os.environ.get("AMAZON_ACCESS_KEY")
    AMAZON_SECRET_KEY = os.environ.get("AMAZON_SECRET_KEY")
    AMAZON_ASSOC_TAG = os.environ.get("AMAZON_ASSOC_TAG")

    HOST = "webservices.amazon.co.jp"
    REGION = "us-west-2"

    default_api = DefaultApi(access_key=AMAZON_ACCESS_KEY,
                             secret_key=AMAZON_SECRET_KEY,
                             host=HOST,
                             region=REGION)

    # request paraeters
    KEYWORDS = os.environ.get("KEYWORDS")
    SEARCH_INDEX = os.environ.get("SEARCH_INDEX")
    BROWSE_NODE_ID = os.environ.get("BROWSE_NODE_ID")
    ITEM_COUNT = int(os.environ.get("ITEM_COUNT"))

    # For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter
    search_items_resource = [
        SearchItemsResource.ITEMINFO_TITLE,
        SearchItemsResource.OFFERS_LISTINGS_PRICE,
        SearchItemsResource.ITEMINFO_BYLINEINFO,
        SearchItemsResource.ITEMINFO_CONTENTINFO,
        SearchItemsResource.ITEMINFO_TECHNICALINFO,
        SearchItemsResource.IMAGES_PRIMARY_LARGE
    ]

    try:
        # Forming request
        search_items_request = SearchItemsRequest(
            partner_tag=AMAZON_ASSOC_TAG,
            partner_type=PartnerType.ASSOCIATES,
            keywords=KEYWORDS,
            search_index=SEARCH_INDEX,
            browse_node_id=BROWSE_NODE_ID,
            item_count=ITEM_COUNT,
            resources=search_items_resource,
        )
        # Sending request
        response = default_api.search_items(search_items_request)
        # print("Complete Response:", response)

        # Parse response
        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)
            return

        if response.search_result is not None:
            print("API called Successfully")
            return (response.search_result.items)

    except:
        print_exc()
        raise Exception
コード例 #3
0
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"
    """ API declaration """
    default_api = DefaultApi(access_key=access_key,
                             secret_key=secret_key,
                             host=host,
                             region=region)
    """ 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.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)
コード例 #4
0
    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 > 10 or item_page < 1:
            raise AmazonException('ValueError',
                                  'Arg item_page should be between 1 and 10')
        if not keywords and not actor and not artist and not author and not brand and not title:
            raise AmazonException(
                'ValueError', 'At least one of the following args must be '
                'provided: keywords, actor, artist, author, brand,'
                'title')
        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:
                    # 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.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:
                    for item in response.search_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
コード例 #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)