Skip to main content
 首页 » 编程设计

python之如何并行使用分页 api

2024年11月24日8pengyingh

我在 while 循环中按顺序查询带有请求的分页 API。我知道总共有多少个项目,每个响应的最大项目数是 200。我还可以计算偏移量。然而,这非常慢,我想并行发出请求,但研究表明存在一种称为全局解释器锁的东西,并且通过多个进程将数据附加到全局列表很容易出错。

实现此目标的最 pythonic 方法是什么?

def downloadUsers(token, totalUsers): 
    offset = 0  
    limit = 200   
    authToken = token 
    has_more = True 
    allUsers = [] 
 
    while has_more: 
        batch = offset + limit 
        if batch > totalUsers: 
            batch = totalUsers 
        url = f"https://example.com/def/v1/users?offset={offset}&limit={limit}" 
        response = requests.get(url, headers={'Authorization': authToken}).json() 
 
        allUsers.extend(response["data"]) 
        offset += 200 
        has_more = response['has_more'] 
 
    allUsers = doSomethingElse(allUsers) 
    return allUsers 

请您参考如下方法:

你是对的,有一个著名的 GIL。 但是,这会阻止您的 Python 应用程序仅使用一个线程。术语使用非常重要。 因为在应用过程中,有时python会将任务委托(delegate)给其他系统并等待答案。 在您的情况下,您正在等待建立网络连接。

您可以使用并发模块中的 future 类来实现应用程序的多线程。

它会是这样的:

from concurrent import futures 
maxWorker = min(10,len(total_amount_of_pages)) ## how many thread you want to deal in parallel. Here 10 maximum, or the amount of pages requested. 
urls = ['url'*n for n in total_amount_of_pages] ## here I create an iterable that the function will consume. 
with futures.ThreadPoolExecutor(workers) as executor: 
                res = executor.map(requests.get,urls) ## it returns a generator 
## it is consuming the function in the first argument and the iterable in the 2nd arguments, you can send more than 1 argument by adding new ones (as iterable).  
myresult = list(res) 
 
````