如何加速重复的API调用?

2024-09-26 18:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

为了详细了解,我附上了一个文件链接: Actual file

我在列表中有类似语法的数据,如:

i = [a.b>c.d , e.f.g>h.i.j ]

例如,列表中的每个元素都有多个子元素,以“.”和“>;”分隔

 for i in range(0, len(l)):
    reac={}
    reag={}
    t = l[i].split(">")
    REAC = t[0]
    Reac = REAC.split(".")

    for o in range(len(Reac)):

        reaco = "https://ai.chemistryinthecloud.com/smilies/" + Reac[o]

        respo = requests.get(reaco)
        reac[o] ={"Smile":Reac[o],"Details" :respo.json()}

    if (len(t) != 1):
        REAG = t[1]
        Reag = REAG.split(".")
        for k in range(len(Reag)):

            reagk = "https://ai.chemistryinthecloud.com/smilies/" + Reag[k]
            repo = requests.get(reagk)
            reag[k] = {"Smile": Reag[k], "Details" :repo.json()}
        res = {"Reactants": list(reac.values()), "Reagents": list(reag.values())}
        boo.append(res)
    else:
        res = {"Reactants": list(reac.values()), "Reagents": "No reagents"}
        boo.append(res)

我们已经分离了所有元素,对于每个元素,我们调用第三方API。那会消耗太多的时间

是否有任何方法可以减少此时间并优化循环

回复大约需要1分钟。我们希望优化到5-10秒


Tags: in元素列表forlenrangereslist
1条回答
网友
1楼 · 发布于 2024-09-26 18:18:53

就这么做吧。我更改了输出的格式,因为它使事情变得不必要的复杂,并删除了许多您正在做的非Python的事情。第二次运行应该是瞬时的,如果在方程式或反应侧面有重复值,第一次应该快得多

# pip install cachetools diskcache
from cachetools import cached
from diskcache import Cache

BASE_URL = "https://ai.chemistryinthecloud.com/smilies/"
CACHEDIR = "api_cache"

@cached(cache=Cache(CACHEDIR))
def get_similies(value):
    return requests.get(BASE_URL + value).json()


def parse_eq(eq):
    reac, _, reag = (set(v.split(".")) for v in eq.partition(">"))
    return {
        "reactants": {i: get_similies(i) for i in reac},
        "reagents": {i: get_similies(i) for i in reag}
    }

result = [parse_eq(eq) for eq in eqs]

相关问题 更多 >

    热门问题