[英]How do I consume a paginated api in parallel?
我正在按顺序在 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将任务委托给其他系统并等待答案。 在这种情况下,您正在等待建立网络连接。
您可以通过使用来自并发模块的未来类来实现应用程序的多线程。
它会是这样的:
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)
````
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.