访问Python中另一个函数中的一个函数的值列表?

时间:2018-06-23 03:17:52

标签: python while-loop

我有一个收集UPC列表的功能。我创建了另一个函数来获取列表并搜索价格。我遇到的问题是找不到UPC时发生KeyError。如何忽略不匹配的UPC并继续执行代码?当前版本的代码是一个无限循环。

def trending():
    trending = requests.get('http://api.com/trends?format=json&apiKey={}'.format(apiKey))
    trendingResponse = trending.json()
    items = trendingResponse['items']

    for item in items:
        price = item['salePrice']
        name = item['name']
        upc = item['upc']
        stock = item['stock']
        image = item['largeImage']
        url = item['productUrl']
        sDescription = item['shortDescription']
        brandName = item['brandName']
        availableOnline = item['availableOnline']

        print('Current UPC = ' + str(upc))
        return upc_lookup(upc)

def upc_lookup(upc):
    products_api = mws.Products(access_key, secret_key, seller_id, region='US')
    # lookup product by upc
    products = products_api.get_matching_product_for_id(marketplaceid=marketplace_usa, type_='UPC', ids=upc)
    parse = products.parsed

    while True:
        try:
            # return asin from UPC lookup
            asin = parse['Products']['Product']['Identifiers']['MarketplaceASIN']['ASIN']['value']
            print('ASIN Found = ' + str(asin))
        except KeyError:
            print('UPC {} not Found in Amazon'.format(upc))

2 个答案:

答案 0 :(得分:0)

好像我不得不将第一个函数中的Return移出For循环。

答案 1 :(得分:0)

def function_1():
    function_1.item = {'sale-Price':100, 'name':'ABC', 'stock':3, 'brand-name':4}`

def function_2():
    item = function_1.item
    sp = item['salePrice']
    name = item['name']
    stock = item['stock']
    print(sp, name, stock)

function_1()
function_2()