【问题标题】:How can I get returns from APIs faster? I need to get returns from over 400 API endpoints as fast as possible如何更快地从 API 获得回报?我需要尽快从 400 多个 API 端点获得回报
【发布时间】:2021-09-25 21:38:59
【问题描述】:

我正在尝试从 Premiere League 获取每位球员的统计数据,但是,每位球员都有不同的 API 端点,我需要获取超过 470 名球员的信息。反正有没有让这更快?最好只有几秒钟。

import requests

response1 = requests.get("https://fantasy.premierleague.com/api/bootstrap-static/")
json_general = response1.json()

def get_json_element(element_id):
    response = requests.get("https://fantasy.premierleague.com/api/element-summary/" + str(element_id) + "/")
    return response.json()

def get_fdr(element_id):
    element_id = 1
    points_sum = 0
    fixtures_remaining = len(get_json_element(element_id)["fixtures"])
    ratio = []

    for i in range(fixtures_remaining):
        ratio.append(2 ** i)

    points = 1000 / sum(ratio)

    for i in range(fixtures_remaining):
        output = ((5 - (get_json_element(element_id)["fixtures"][i]["difficulty"])) * (points * ratio[(len(ratio) - 1 - i)] / 5))
        points_sum = points_sum + output
    return points_sum

fdr_dict = {}

for i in range(len(json_general["elements"])):
    fdr_dict.update({json_general["elements"][i]["id"]: get_fdr(json_general["elements"][i]["id"])})

for key, value in fdr_dict.items():
    print(value, key)

尝试2:

导入请求 导入 aiohttp 导入异步

response1 = requests.get("https://fantasy.premierleague.com/api/bootstrap-static/")
json_general = response1.json()


def id_list():
    id_list = []
    for i in range(len(json_general["elements"])):
        id_list.append(json_general["elements"][i]["id"])
    return id_list


async def main():
    async with aiohttp.ClientSession() as session:
        tasks = []
        for element_id in id_list():
            task = asyncio.ensure_future(get_json_element(session, element_id))
            tasks.append(task)

        fdr_list = await asyncio.gather(*tasks)

    print(dict(fdr_list))


async def get_json_element(session, element_id):
    url = "https://fantasy.premierleague.com/api/element-summary/" + str(element_id) + "/"

    async with session.get(url) as response:
        json_element = await response.json()
        fixtures = json_element["fixtures"]
        return element_id, fixtures

asyncio.run(main())

【问题讨论】:

  • 使用线程或异步并同时进行多个调用。
  • 您能解释一下我如何将它集成到我的代码中吗?
  • @acushner 我试过这个,但它返回一个错误。有任何想法吗?我已将更新后的代码放在帖子中。
  • 什么样的错误?另一种方法可能是使用像 scrapy 这样的网络抓取框架
  • 感谢您的回复,我意识到我正在使用的 api 有一个奇怪的标头,需要声明。

标签: python json performance api


【解决方案1】:

通过使用单个 session object 来重用 http 连接。

否则,瓶颈可能是 API,所以除了检查它们是否为您的用例提供批量/批量之外,您在客户端无能为力。

【讨论】:

  • 我试过了,但它返回一个错误。有任何想法吗?我已将更新后的代码放在帖子中。
  • 如果您向我们提供有关错误的详细信息。
  • 您好,感谢您的回复,我意识到我使用的 api 有一个奇怪的标头,我需要声明。
猜你喜欢
  • 2011-11-23
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 2018-03-01
  • 2020-11-06
  • 2016-04-14
  • 2018-08-27
相关资源
最近更新 更多