我将如何跟踪一大批grequest的进度?

问题描述 投票:0回答:1

我有时通过Python的grequest.map函数发送大量请求。目前,我的代码如下所示

# passes these two into the function. The list of parameters can sometimes be thousands long.
# made this example up
local_path = 'https://www.google.com/search?q={}'
parameters = [('the+answer+to+life+the+universe+and+everything'), ('askew'), ('fun+facts')]
    s = requests.Session()
    retries = Retry(total=5, backoff_factor=0.2, status_forcelist=[500,502,503,504], raise_on_redirect=True, raise_on_status=True)
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))
    async_list = []
    for parameters in parameter_list:
        URL = local_path.format(*parameters)
        async_list.append(grequests.get(URL, session=s))
    results = grequests.map(async_list)

我是tqdm库的粉丝,很想知道有多少请求已完成以及还有多少正在等待中的进度指示器,但是我不确定是否可以轮询或生成钩子可以从grequest.getSession执行此操作。我确实尝试使用grequests.get(URL, hooks={'response': test}, session=s),但这似乎实际上将响应本身输入到测试函数中,然后results的内容为None

编辑:发布此问题后不久,我探索了test钩子函数的返回值,但是无论我如何尝试,似乎如果有一个钩子,则map函数直到有响应才被阻塞;导致None响应,也没有任何异常发生。

我将如何跟踪大量请求的进度?

python python-requests tqdm
1个回答
0
投票

使用hooks参数是正确的解决方案。我发现我设置的test回调遇到一个异常(诅咒那些微小的作用域错误),并且由于我没有为我的请求设置异常处理程序,因此它导致了一个静默错误,导致None响应。 >

这是我最终得到的设置。

track_requests = None
def request_fulfilled(r, *args, **kwargs):
    track_requests.update()

local_path = 'https://www.google.com/search?q={}'
parameters = [('the+answer+to+life+the+universe+and+everything'), ('askew'), ('fun+facts')]
    global track_requests # missing this line was the cause of my issue...
    s = requests.Session()
    s.hooks['response'].append(request_fulfilled) # assign hook here
    retries = Retry(total=5, backoff_factor=0.2, status_forcelist=[500,502,503,504], raise_on_redirect=True, raise_on_status=True)
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))
    async_list = []
    for parameters in parameter_list:
        URL = local_path.format(*parameters)
        async_list.append(grequests.get(URL, session=s))
    track_requests = tqdm(total=len(async_list))
    results = grequests.map(async_list)
    track_requests.close()
    track_requests = None
© www.soinside.com 2019 - 2024. All rights reserved.