【问题标题】:Handling Exceptions with Bulk API Requests处理批量 API 请求的异常
【发布时间】:2020-01-10 07:56:37
【问题描述】:

我从允许批量请求的 API 中提取数据,然后将数据存储到 Dataframe。当通过 API 查找的 一个 项目出现异常时,我想完全跳过该项目,(或将零写入 Dataframe)然后继续下一个项目。

但我的问题是,由于 API 数据被批量访问(即,不循环遍历列表中的每个项目),列表中 any 项目的异常会破坏程序。那么如何优雅地处理异常而不遍历tickers 列表中的每个单独的项目呢?

请注意,从tickers 列表中删除ERROR 将使程序能够成功运行:

import os
from iexfinance.stocks import Stock
import iexfinance

# Set IEX Finance API Token (Sandbox)
os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'
os.environ['IEX_TOKEN'] = 'Tpk_a4bc3e95d4c94810a3b2d4138dc81c5d'

# List of companies to get data for
tickers = ['MSFT', 'ERROR', 'AMZN']

batch = Stock(tickers, output_format='pandas')
income_ttm = 0

try:
    # Get income from last 4 quarters, sum it, and store to temp Dataframe
    df_income = batch.get_income_statement(period="year")
    print(df_income)

except (iexfinance.utils.exceptions.IEXQueryError, iexfinance.utils.exceptions.IEXSymbolError) as e:
    pass

【问题讨论】:

  • 如果这些是您的真实凭据,您应该立即使它们失效。它们永远受到损害,您需要生成新的。从您的问题中编辑它们是不够。 (我怀疑提供商甚至不希望您共享您的沙盒凭据。)
  • 感谢您的关注,但这些是与我的帐户无关的“一次性”凭据。此外,它们是沙盒凭据,这意味着它们返回的数据是随机的。我只是认为共享一些令牌更容易,这样人们就可以自己实际运行代码。
  • 您要返回现有数据吗?你想告诉用户哪一列失败了吗?
  • @ndclt - 理想情况下希望输出仅显示 API 未能查找的数据的 0。因此,在此示例中,当没有异常时,输出类似于:MSFT AMZN 作为列标题,然后行是从 API 返回的数据。相反,我希望列标题为MSFT ERROR AMZN,而行仍然是来自MSFTAMZN 的返回API 数据。但是ERROR 的所有行都为 0(因为 API 找不到它的数据)。

标签: python pandas api dataframe exception


【解决方案1】:

这应该做的工作

import os
from copy import deepcopy

from iexfinance.stocks import Stock
import iexfinance

def find_wrong_symbol(tickers, err):
    wrong_ticker = []
    for one_ticker in tickers:
        if one_ticker.upper() in err:
            wrong_ticker.append(one_ticker)
    return wrong_ticker

# Set IEX Finance API Token (Sandbox)

os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'
os.environ['IEX_TOKEN'] = 'Tpk_a4bc3e95d4c94810a3b2d4138dc81c5d'

# List of companies to get data for
tickers = ['MSFT', 'AMZN', 'failing']

batch = Stock(tickers, output_format='pandas')
income_ttm = 0

try:
    # Get income from last 4 quarters, sum it, and store to temp Dataframe
    df_income = batch.get_income_statement(period="year")
    print(df_income)

except (iexfinance.utils.exceptions.IEXQueryError, iexfinance.utils.exceptions.IEXSymbolError) as e:
    wrong_tickers = find_wrong_symbol(tickers, str(e))
    tickers_to_get = deepcopy(tickers)
    assigning_dict = {}
    for wrong_ticker in wrong_tickers:
        tickers_to_get.pop(tickers_to_get.index(wrong_ticker))
        assigning_dict.update({wrong_ticker: lambda x: 0})
    new_batch = Stock(tickers_to_get, output_format='pandas')
    df_income = new_batch.get_income_statement(period="year").assign(**assigning_dict)

我创建了一个小函数来查找 API 无法处理的代码。删除错误代码后,我回想起没有它的 API,并使用 assign 函数添加带有 0 值的缺失列(可以是任何值,NaN 或其他默认值)。

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2012-07-03
    相关资源
    最近更新 更多