本文整理汇总了Python中amazonproduct.api.API类的典型用法代码示例。如果您正苦于以下问题:Python API类的具体用法?Python API怎么用?Python API使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了API类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_associate_tag_is_written_to_url
def test_associate_tag_is_written_to_url(self):
tag = "ABC12345"
api = API("XXX", "XXX", "de", associate_tag=tag)
url = api._build_url(Operation="ItemSearch", SearchIndex="Books")
qs = parse_qs(urlparse(url)[4])
assert qs["AssociateTag"][0] == tag
示例2: __init__
def __init__(self, access_key_id, secret_access_key, locale, cachedir=DEFAULT_CACHE_DIR, **kwargs):
"""
:param cachedir: Path to directory containing cached responses.
"""
API.__init__(self, access_key_id, secret_access_key, locale, **kwargs)
self.cache = cachedir
if self.cache and not os.path.isdir(self.cache):
os.mkdir(self.cache)
示例3: pytest_funcarg__api
def pytest_funcarg__api(request):
server = request.getfuncargvalue('server')
api = API('XXX', 'XXX', 'uk') # locale does not matter here!
api.host = '%s:%s' % server.server_address
if hasattr(request, 'param'): # for tests generated by pytest_generate_tests
api.VERSION = request.param['version']
api.REQUESTS_PER_SECOND = 10000 # just for here!
return api
示例4: pytest_funcarg__api
def pytest_funcarg__api(request):
server = request.getfuncargvalue("server")
api = API("XXX", "XXX", "uk") # locale does not matter here!
api.host = "%s:%s" % server.server_address
if hasattr(request, "param"): # for tests generated by pytest_generate_tests
api.VERSION = request.param["version"]
api.REQUESTS_PER_SECOND = 10000 # just for here!
return api
示例5: __init__
def __init__(self, *args, **kwargs):
"""
:param cachedir: Path to directory containing cached responses.
"""
self.cache = kwargs.pop("cachedir", DEFAULT_CACHE_DIR)
API.__init__(self, *args, **kwargs)
if self.cache and not os.path.isdir(self.cache):
os.mkdir(self.cache)
示例6: __init__
def __init__(self, *args, **kwargs):
"""
:param cachedir: Path to directory containing cached responses.
"""
self.cache = kwargs.pop('cachedir', DEFAULT_CACHE_DIR)
self.cachetime = kwargs.pop('cachetime', False) # i.e. indefinite
API.__init__(self, *args, **kwargs)
if self.cache and not os.path.isdir(self.cache):
os.mkdir(self.cache)
示例7: create_cart
def create_cart(asin, quantity=1):
api = API(
settings.AMAZON_AWS_KEY,
settings.AMAZON_SECRET_KEY,
settings.AMAZON_API_LOCALE,
settings.AMAZON_ASSOCIATE_TAG)
cart = api.cart_create({asin: quantity})
try:
return unicode(cart.Cart.PurchaseURL)
except ValueError, InvalidCartItem:
raise ValidationError()
示例8: getAmazonContent
def getAmazonContent(query):
api = API(AWS_KEY, SECRET_KEY, 'uk', associate_tag='giracake-21', processor=minidom_response_parser)
node = api.item_search('All', Keywords=query, ResponseGroup="Medium")
products = node.getElementsByTagName('Item')
data = []
for product in products:
#print product.toprettyxml()
summaryNodes = product.getElementsByTagName('OfferSummary')
if len(summaryNodes) > 0:
for summaryNode in summaryNodes:
priceNodes = summaryNode.getElementsByTagName('LowestNewPrice')
for priceNode in priceNodes:
formattedPrice = priceNode.getElementsByTagName('FormattedPrice')
price = formattedPrice[0].childNodes[0].nodeValue
imageSetsNodes = product.getElementsByTagName('ImageSets')
if len(imageSetsNodes) > 0:
for imageSetsNode in imageSetsNodes:
imageSetNodes = imageSetsNode.getElementsByTagName('ImageSet')
for imageSetNode in imageSetNodes:
if imageSetNode.attributes["Category"].value != "primary":
continue
mediumImage = imageSetNode.getElementsByTagName('LargeImage')
url = mediumImage[0].getElementsByTagName('URL')[0]
image = url.childNodes[0].nodeValue
prod = {}
prod['url'] = getText(product.getElementsByTagName('DetailPageURL')[0].childNodes)
prod['title'] = getText(product.getElementsByTagName('Title')[0].childNodes)
prod['img'] = image
prod['price'] = price
#imagesets = getText(product.getElementsByTagName('MediumImage'))[0].childNodes
#print imagesets
#imageset = getText(imagesets.getElementsByTagName('ImageSet'))[0]
data += [prod]
return data
示例9: _fetch
def _fetch(self, url):
"""
Retrieves XML response from Amazon. In case of a timeout, it will try
:const:`~RetryAPI.TRIES`` times before raising an error.
"""
attempts = 0
delay = self.DELAY
while True:
try:
attempts += 1
return API._fetch(self, url)
except URLError:
e = sys.exc_info()[1] # Python 2/3 compatible
# if a timeout occurred
# wait for some time before trying again
reason = getattr(e, 'reason', None)
if isinstance(reason, socket.timeout) and attempts < self.TRIES:
time.sleep(delay)
delay *= self.BACKOFF
continue
# otherwise reraise the original error
raise
示例10: amazon_search
def amazon_search():
api = API(AWS_KEY, SECRET_KEY, 'us', ASSOC_TAG)
result = api.item_search('All',
ResponseGroup='Large', AssociateTag='boitba-20', Keywords='tent marmot', ItemPage=2)
total_results = result.results
#item_search returns pages not items
# extract paging information
#total_results = result.results
#Stotal_pages = len(result) # or result.pages
#~ from lxml import etree
#~ print etree.tostring(root, pretty_print=True)
return render_template("amazon_search.html", node = result, total_results=total_results)
示例11: amazon
def amazon(query):
api = API(AWS_KEY, SECRET_KEY, 'us', ASSOC_TAG)
similar_root = api.similarity_lookup('B0058U6DQC', ResponseGroup='Large')
product_root = api.item_lookup('B0058U6DQC', ResponseGroup='Large')
product_root = api.item_search(title='unicorn', ResponseGroup='Large')
more_products = api.item_search('Books', Publisher='Galileo Press')
#~ from lxml import etree
#~ print etree.tostring(root, pretty_print=True)
nspace = similar_root.nsmap.get(None, '')
similar_products = similar_root.xpath('//aws:Items/aws:Item',
namespaces={'aws' : nspace})
# more_products = product_root.xpath('//aws:Items/aws:Item',
# namespaces={'aws' : nspace})
return render_template("amazon.html", similar_products=similar_products, more_products = more_products, query=query)
示例12: search
def search():
form = SearchForm()
if form.validate_on_submit():
referrer = form.referrer.data
query = form.query.data
results = model.session.query(model.Library).filter(model.Library.product_desc.like('%'+ query + '%')).all()
if not results:
#redirect to new page with amazon search results
return redirect(url_for('amazon_bottlenose2', query=query, referrer=referrer))
else:
for i in results:
similar_products = None
if i.product.asin:
asin = i.product.asin
api = API(AWS_KEY, SECRET_KEY, 'us', ASSOC_TAG)
try:
similar_root = api.similarity_lookup(asin, ResponseGroup='Large')
#~ from lxml import etree
#~ print etree.tostring(root, pretty_print=True)
nspace = similar_root.nsmap.get(None, '')
similar_products = similar_root.xpath('//aws:Items/aws:Item',
namespaces={'aws' : nspace})
except:
similar_products = None
#render page with search results
if referrer == 'dashboard':
return render_template('results.html', results=results, similar_products=similar_products)
else:
form = AddProductForm()
return render_template('add_product_results.html', results=results, similar_products=similar_products, form=form)
# else:
# flash("Invalid Search")
return render_template("search.html", form=form)
示例13: __init__
def __init__(self, locale='de'):
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title("BrowseNode Explorer")
self.set_size_request(400, 200)
self.connect("delete_event", self.on_delete)
self.locale = locale
self.api = API(AWS_KEY, SECRET_KEY, self.locale)
# create a TreeStore with one string column to use as the model
self.treestore = gtk.TreeStore(int, str)
# create the TreeView using treestore
self.treeview = gtk.TreeView(self.treestore)
# add column id
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('id', renderer, text=0)
self.treeview.append_column(column)
# add column name
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('name', renderer, text=1)
column.set_sort_column_id(1) # Allow sorting on the column
self.treeview.append_column(column)
# make it clickable
self.treeview.add_events(gtk.gdk.BUTTON_PRESS_MASK)
self.treeview.connect('button_press_event', self.on_tree_click)
scrolled = gtk.ScrolledWindow()
scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scrolled.add(self.treeview)
self.add(scrolled)
self.show_all()
# populate with root nodes
# but avoid duplicated node ids
node_ids = set(NODE_IDS[self.locale].values())
for name, id in NODE_IDS[self.locale].items():
if id in node_ids:
self.treestore.append(None, [id, name])
node_ids.remove(id)
示例14: _fetch
def _fetch(self, url):
if self.cache:
path = os.path.join(self.cache, "%s.xml" % self.get_hash(url))
# if response was fetched previously, use that one
if os.path.isfile(path):
return open(path)
# fetch original response from Amazon
resp = API._fetch(self, url)
if self.cache:
fp = open(path, "w+")
fp.write(etree.tostring(etree.parse(resp), pretty_print=True))
fp.seek(0)
return fp
return resp
示例15: _fetch
def _fetch(self, url):
if self.cache:
path = os.path.join(self.cache, '%s.xml' % self.get_hash(url))
# if response was fetched previously, use that one
if os.path.isfile(path):
return open(path)
# fetch original response from Amazon
resp = API._fetch(self, url)
if self.cache:
fp = open(path, 'w+')
node = xml.dom.minidom.parseString(resp.read())
fp.write(node.toprettyxml())
#from lxml import etree
#fp.write(etree.tostring(etree.parse(resp), pretty_print=True))
fp.seek(0)
return fp
return resp