我正在尝试实施使用Amazon API的程序。我使用了yoavaviram制作的包装纸。我将我的代码推送到github,并通知我的亚马逊,我不应该在我的代码中明确地拥有我的AWS凭据。我发现了一些使用boto访问AWS等存储桶的代码,但我认为我不需要使用它。如何在未在代码中明确写入其值的情况下,在以下代码中传递我的凭据?
#windowShopping will take all of the Amazon HTMLs from a data structure and will retrieve all of the used/new prices
import re
import json
import requests
from bs4 import BeautifulSoup
from amazon.api import AmazonAPI
import time
AMAZON_ACCESS_KEY = < my access key >
AMAZON_SECRET_KEY = < my secret key >
AMAZON_ASSOC_TAG = < my user name >
asin_regex = r'/([A-Z0-9]{10})'
isbn_regex = r'/([0-9]{10})'
def get_amazon_item_id(url):
# return either ASIN or ISBN
asin_search = re.search(asin_regex, url)
isbn_search = re.search(isbn_regex, url)
if asin_search:
return asin_search.group(1)
elif isbn_search:
return isbn_search.group(1)
else:
# log this URL
return None
def get_amazon_product_meta(url):
# the input URL is always of amazon
amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)
item_id = get_amazon_item_id(url)
if not item_id:
return None
try:
product = amazon.lookup(ItemId=item_id)
except amazon.api.AsinNotFound:
# log this ASIN
return None
except Exception:
return None
# product.price_and_currency returns in the form (price, currency)
# product_price = product.price_and_currency[0]
new_price = product._safe_get_element_text("OfferSummary.LowestNewPrice.FormattedPrice")
used_price = product._safe_get_element_text("OfferSummary.LowestUsedPrice.FormattedPrice")
trade_in_price = product._safe_get_element_text("ItemAttributes.TradeInValue.FormattedPrice")
if new_price or used_price or trade_in_price:
return new_price, used_price, trade_in_price
return Nonesting.Price.FormattedPrice
def unpickle(fileName):
f = open(fileName, 'r')
HTML_Dict = json.load(f)
print(fileName)
f.close()
return HTML_Dict
def pickle(structure,fileName):
f = open(fileName, 'w' )
json.dump(structure,f)
f.close()
def get_prices(urls,newPricesDict, usedPricesDict, tradeInDict):
#iterates through document of book urls
for url in urls:
price = get_amazon_product_meta(urls[url])
newPricesDict[url] = price[0]
usedPricesDict[url] = price[1]
tradeInDict[url] = price[2]
time.sleep(1)
print(url)
print("\t" + str(price))
def main():
newPrices = {}
usedPrices = {}
tradeInPrices = {}
urlDict = unpickle('addresses.dat')
get_prices(urlDict, newPrices, usedPrices, tradeInPrices)
pickle(newPrices, "newPrices.dat")
pickle(usedPrices, "usedPrices.dat")
pickle(tradeInPrices, "tradeInPrices.dat")
if __name__ == '__main__':
main()
答案 0 :(得分:2)
创建另一个名为credentials.py
的文件
定义变量。
AMAZON_ACCESS_KEY = "access_key"
AMAZON_SECRET_KEY = "secret_key"
AMAZON_ASSOC_TAG = "tag_name"
然后在你的文件中,
from credentials import *
AMAZON_ACCESS_KEY = AMAZON_ACCESS_KEY
AMAZON_SECRET_KEY = AMAZON_SECRET_KEY
AMAZON_ASSOC_TAG = AMAZON_ASSOC_TAG
答案 1 :(得分:1)
您绝对应该使用具有EC2角色的IAM凭据。它在开始时有点难,但它付出了代价。它可确保凭据不断轮换。
我不知道你正在使用的库,但我可以告诉你,当python中的其他库在分配了IAM角色的EC2实例中运行时会自动检测,并且它们会自动加载相应的凭据。