本文整理汇总了Python中amazon.api.AmazonAPI类的典型用法代码示例。如果您正苦于以下问题:Python AmazonAPI类的具体用法?Python AmazonAPI怎么用?Python AmazonAPI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AmazonAPI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Item
class Item(object):
def __init__(self, product):
self.product = product
self.amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)
def prod_search(self):
products_found = self.amazon.search_n(1, Keywords= self.product, SearchIndex= "All")
return products_found
def prod_item(self):
products_found = self.prod_search()
try:
return products_found[0].title
except IndexError:
raise Exception('No product found')
def prod_asin(self):
products_found = self.prod_search()
try:
return products_found[0].asin
except IndexError:
raise Exception('No Asin found')
def prod_price(self):
product_asin = self.prod_asin()
the_product = self.amazon.lookup(ItemId='' + product_asin + '')
found_product_price = the_product.price_and_currency
print the_product.image
return found_product_price
示例2: search_item
def search_item():
query = request.args.get('q')
category = request.args.get('c')
## replace confidencial to secret file and put it in gitignore
from amazon.api import AmazonAPI
amazon = AmazonAPI(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY'], 'papylus-22', region="JP")
if not category:
category = 'All'
try:
products = amazon.search_n(5, Keywords=query, SearchIndex=category)
except:
# in case 503 Error occurs without any reason
import time
for i in range(3):
print '503 Error'
time.sleep(1)
products = amazon.search_n(5, Keywords=query, SearchIndex=category)
if products:
break
items = []
for i in products:
pub_date = i.publication_date.strftime(u'%Y-%m-%d') if i.publication_date != None else ''
items.append({'name': i.title, 'url': i.offer_url, 'img': i.medium_image_url, 'publisher': i.publisher, 'pub_date': pub_date})
return json.dumps(items)
示例3: update_price
def update_price(self):
# check if this is an Amazon product
if self.distributor.name == 'Amazon':
amazon = AmazonAPI(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_ASSOCIATE_TAG)
try:
product = amazon.lookup(ItemId=self.part.asin)
price = product.price_and_currency
return price[0]
except:
pass
else:
import urllib2
from lxml import etree
import microdata
import urllib
items = microdata.get_items(urllib.urlopen(self.url))
for i in items:
if i.offers:
return "%s (md)".replace("$", "") % i.offers.price.strip().replace("$", "")
html = urllib2.urlopen(self.url).read()
tree = etree.HTML(html)
price = tree.xpath("%s/text()[1]" % self.xpath)
try:
return "%s (xp)" % price[0].replace("$", "")
except:
return "N/A"
示例4: get
def get(self):
search = self.request.get('search')
amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG) #initiates a new Amazon API
amazon_results = amazon.search_n(15, Keywords=search, SearchIndex='All')
# returns in JSON name, salePrice, and URL of user's search from BestBuy
best_buy_url = 'http://api.remix.bestbuy.com/v1/products(search='+ search.replace(' ', '&search=')+')?format=json&show=sku,name,salePrice,url,image,upc&pageSize=15&page=5&apiKey=24ta6vtsr78a22fmv8ngfjet'
best_buy_results = json.load(urllib2.urlopen(best_buy_url)).get('products')
walmart_url = "http://api.walmartlabs.com/v1/search?query=%s&format=json&apiKey=cz9kfm3vuhssnk6hn33zg86k&responseGroup=base" % search.replace(' ','+')
walmart_results = json.load(urllib2.urlopen(walmart_url)).get('items')
results = []
for product in amazon_results:
results += [(product.title, product.price_and_currency[0], product.offer_url, product.medium_image_url, 'Amazon','/wishlist?type=amazon&id=%s'%product.asin,"/compare?upc=%s" %str(product.upc), '/email?producturl=%s'%product.offer_url)]
#How to retrive asin for amazon products and decrease image size
for product in best_buy_results:
results += [(product.get('name'), product.get('salePrice'), product.get('url'), product.get('image'), 'Best Buy','/wishlist?type=bestbuy&id=%s'%product.get('sku'),"/compare?upc=%s" %str(product.get('upc')), '/email?producturl=%s'%product.get('url'))]
for product in walmart_results:
results += [(product.get('name'), product.get('salePrice'), product.get('productUrl'), product.get('thumbnailImage'), 'Walmart','/wishlist?type=walmart&id=%s'%product.get('itemId'),"/compare?upc=%s" %str(product.get('upc')),'/email?producturl=%s'%product.get('productUrl'))]
results = sorted(results,key=lambda x: x[1])
for item in results:
i = results.index(item)
if str(item[1])[len(str(item[1]))-2] == '.':
item = list(item)
item[1] = str(item[1]) + '0'
item = tuple(item)
results[i] = item
template_variables={"user_search":search, 'results':results, 'user': users.get_current_user(), 'logout' : users.create_logout_url('/'), 'login' : users.create_login_url('/')}
template=jinja_environment.get_template('/templates/results.html')
self.response.write(template.render(template_variables))
示例5: __init__
class GiftlyAmazonAPI:
amazon_product_details = ['api', 'asin', 'author', 'authors',
'aws_associate_tag', 'binding', 'brand',
'browse_nodes', 'color', 'creators', 'ean',
'edition', 'editorial_review', 'editorial_reviews',
'eisbn', 'features', 'get_attribute',
'get_attribute_details', 'get_attributes',
'get_parent', 'images', 'isbn', 'label', 'languages',
'large_image_url', 'list_price', 'manufacturer',
'medium_image_url', 'model', 'mpn', 'offer_url',
'pages', 'parent', 'parent_asin', 'parsed_response',
'part_number', 'price_and_currency', 'publication_date',
'publisher', 'region', 'release_date', 'reviews', 'sales_rank',
'sku', 'small_image_url', 'tiny_image_url', 'title',
'to_string', 'upc']
amazon_search_index = ['All','Apparel','Appliances','ArtsAndCrafts','Automotive', 'Baby',
'Beauty','Blended','Books','Classical','Collectibles','DVD',
'DigitalMusic','Electronics', 'GiftCards','GourmetFood','Grocery',
'HealthPersonalCare','HomeGarden','Industrial','Jewelry', 'KindleStore',
'Kitchen','LawnAndGarden','Marketplace','MP3Downloads','Magazines','Miscellaneous',
'Music','MusicTracks','MusicalInstruments','MobileApps','OfficeProducts','OutdoorLiving',
'PCHardware', 'PetSupplies','Photo','Shoes','Software','SportingGoods',
'Tools','Toys','UnboxVideo','VHS','Video', 'VideoGames','Watches','Wireless','WirelessAccessories']
def __init__(self, secret_key, access_key, assoc_tag):
self.amazon = AmazonAPI(access_key, secret_key, assoc_tag)
#Keywords is a comma-separated string
#Returns a dictionary of products mapped as ASIN:TITLE
#Can Android parse for keys? We'll find out...
def get_similar_items(self, keywords, numitems=None, category=None):
keywords = keywords if keywords else None
numitems = numitems if numitems else 10
category = category if category else 'All'
print "%d items found with keywords %s in the %s category" % (numitems, keywords, category)
products = self.amazon.search_n(numitems, Keywords=keywords, SearchIndex=category)
product_dict = {}
for product in products:
product_dict[product.asin] = product.title
return product_dict
def get_item_by_asin(self, asin):
product = self.amazon.lookup(ItemId=asin)
product = AmazonProduct(product.asin, product.title)
return product.get_product()
#asin_list is a list of individual asin strings
#they are joined together as one large string
def get_items_by_asin(self, asin_list):
product_list = []
products = self.amazon.lookup(ItemId=(asin_list))
for product in products:
product_list.append(AmazonProduct(product.asin, product.title).get_product())
print product_list
return product_list
示例6: asin_image
def asin_image(self):
amazon = AmazonAPI(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_ASSOCIATE_TAG)
try:
product = amazon.lookup(ItemId=self.asin)
return product.large_image_url
except:
return None
示例7: AmazonScraper
class AmazonScraper(object):
def __init__(self, access_key, secret_key, associate_tag, *args, **kwargs):
self.api = AmazonAPI(access_key, secret_key, associate_tag, *args, **kwargs)
def reviews(self, ItemId=None, URL=None):
return Reviews(self, ItemId, URL)
def review(self, Id=None, URL=None):
return Review(self, Id, URL)
def lookup(self, URL=None, **kwargs):
if URL:
kwargs['ItemId'] = extract_asin(URL)
result = self.api.lookup(**kwargs)
if isinstance(result, (list, tuple)):
result = [Product(p) for p in result]
else:
result = Product(result)
return result
def similarity_lookup(self, **kwargs):
for p in self.api.similarity_lookup(**kwargs):
yield Product(p)
def browse_node_lookup(self, **kwargs):
return self.api.browse_node_lookup(**kwargs)
def search(self, **kwargs):
for p in self.api.search(**kwargs):
yield Product(p)
def search_n(self, n, **kwargs):
for p in self.api.search_n(n, **kwargs):
yield Product(p)
示例8: asin_search
def asin_search(self):
try:
amazon = AmazonAPI(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_ASSOCIATE_TAG)
products = amazon.search_n(10, Keywords="%s %s" % (self.company.name, self.number), SearchIndex="All")
except:
products = None
return products
示例9: handle
def handle(self, *args, **options):
amazon = AmazonAPI(settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY, settings.AMAZON_ASSOC_TAG)
two_days_ago = date.today() - timedelta(days=2)
# isbns = [book.isbn for book in Book.objects.filter(mod_date__gte=two_days_ago)]
isbns = [book.isbn for book in Book.objects.all()]
grouped_isbns = map(None, *[iter(isbns)]*10)
print "=== Start daily book update."
for index, isbns in enumerate(grouped_isbns):
isbns = filter(None, isbns)
isbns = ",".join(isbns)
print " == index : %s / items : %s" % (str(index), isbns)
amazon_books = amazon.lookup(ItemId=isbns)
for amazon_book in amazon_books:
try:
dbbook = Book.objects.get(isbn__exact=amazon_book.isbn)
dbbook.update(amazon_book)
except Book.DoesNotExist:
Book.objects.create_book(amazon_book)
time.sleep(4)
print "=== Successful updated all books"
示例10: amazonResults
def amazonResults(amazonID):
'''Puts ASIN through Amazon API and returns item title, price, and image'''
amazon = AmazonAPI(amazonAccessKey, amazonSecretKey, amazonAssocTag)
product = amazon.lookup(ItemId=amazonID)
title = product.title
image = product.large_image_url
price = product.price_and_currency
return title, price, image
示例11: amazon_price
def amazon_price(self):
amazon = AmazonAPI(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_ASSOCIATE_TAG)
try:
product = amazon.lookup(ItemId=self.asin)
price = product.price_and_currency
return "$%.2f %s" % (price[0], price[1])
except:
return None
示例12: app_results
def app_results(query):
amazon = AmazonAPI(AWS_KEY, SECRET_KEY, ASSOC_TAG)
products = amazon.search(Keywords=query, SearchIndex='All')
if referrer == 'dashboard':
return render_template("amazon_bottlenose2.html", products = products)
else:
form = AddProductForm()
return render_template("amazon_bottlenose_add.html", products = products, form=form)
示例13: add_book
def add_book(request, isbn):
amazon = AmazonAPI(settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY, settings.AMAZON_ASSOC_TAG)
amazon_book = amazon.lookup(ItemId=isbn)
Book.objects.create_book(amazon_book)
if request.is_ajax():
return HttpResponse(status=200)
else:
return HttpResponseRedirect(request.META.get("HTTP_REFERER", ""))
示例14: get
def get(self):
amazon = AmazonAPI()
watches = models.get_db_watches()
if watches:
for WatchListing in watches:
product = amazon.lookup(ItemId=WatchListing.ItemId)
WatchListing.Price = product.price_and_currency[0]
WatchListing.put()
time.sleep(1) #amazon only allows a single API per second...
return
示例15: generate_csv
def generate_csv():
# initialize amazon api with access key, secret key, and associate tag
amazon = AmazonAPI('AKIAJPT5M67Z5DB6R3XA', 'P0ekhRiDVDC2xeJa4fZz1P5qHY/B2Qig71G6wZB3', 'thedeepdark-20')
print("Querying amazon API")
# returns available book subjects
subjects = amazon.browse_node_lookup(BrowseNodeId=1000)
f = open('data.csv', 'wb')
writer = csv.writer(f)
print("\tReturned with " + str(len(subjects[0].children)) + " subjects")
# creates books and author lists
for subject in subjects:
for genre in subject.children:
# skip calendar entries
if genre.name.text == 'Calendars': continue
# returns first 1000 entries in each subject
# Amazons api limits the number of return pages to 10
# with 10 items on each for a maximum of 100 items
books = amazon.search_n(100, Condition='All', BrowseNode=genre.id, SearchIndex='Books', MaxQPS=0.9)
print("Queried " + genre.name + ", returned " + str(len(books)) + " books")
failed = 0
for book in books:
b_isbn = book.isbn
b_title = book.title
b_pub_date = str(book.publication_date)
b_genre = genre.name
b_publisher = book.publisher
b_list_price = book.list_price[0]
b_price = book.price_and_currency[0]
if len(book.authors) == 0:
break
book_item = [b_isbn, b_title, book.authors[0], b_pub_date, b_publisher, b_genre, b_list_price, b_price]
for x in range(len(book_item)):
if isinstance(book_item[x], str):
book_item[x] = unicode(book_item[x], 'utf-8')
try:
writer.writerow(book_item)
except UnicodeEncodeError:
failed += 1
print("\tDone processing books, failed to convert unicode characters " + str(failed) + " times")
time.sleep(5)