简体   繁体   English

为 API 调用集成进度条

[英]Integrating Progress Bar for API Call

Background: I have seen lots of examples of integrating a progress bar into a for loop, however nothing for my use case, and as such am looking for some advice.背景:我已经看到很多将进度条集成到 for 循环中的示例,但是对于我的用例来说没有任何意义,因此我正在寻找一些建议。

For my use case, I am calling an API and testing if meta is in the response ( meta = data I need).对于我的用例,我正在调用 API 并测试meta是否在响应中( meta = 我需要的数据)。 If meta is not in the API response, then the API returns a key pair value named percent_complete , which indicates the data I am trying to return is still aggregating, and provides a value on the progress of data aggregation.如果meta不在 API 响应中,则percent_complete会返回一个名为 percent_complete 的密钥对值,这表明我尝试返回的数据仍在聚合中,并提供了数据聚合进度的值。

Current code:当前代码:

def api_call():

    key, secret, url = ini_reader()
    endpoint_url = endpoint_initializer()
    
    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"vendor-firm": "111"})
        api_response = json.loads(response.text)

        if "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = api_response["data"]["attributes"].get("percent_complete", '')*100
            print(f' Your data request for: {id_value} is {res2}% complete!')
            time.sleep(60)

       elif "meta" in api_response:
            
     return api_response

What I am trying to achieve: {res2} *100 gives the percentage, which I would like to use the measure of progress in a progress bar.我要达到的目标: {res2} *100 给出百分比,我想在进度条中使用进度度量。

Can anyone suggest an appropriate dependency to use?任何人都可以建议使用适当的依赖项吗?

You can use the Enlighten library.您可以使用Enlighten库。 You can keep your print statements and have multiple progress bars at the same time without making any other changes.您可以保留打印语句并同时拥有多个进度条,而无需进行任何其他更改。 Below is an example of how you might implement it.下面是一个如何实现它的示例。

Based on your example it looks like id_value changes, so I wrote the example like that.根据你的例子,它看起来像id_value变化,所以我写了这样的例子。 If it doesn't change you can just use it in the description.如果它没有改变,你可以在描述中使用它。 And if you have multiples, you'd probably want to create a progress bar for each.如果您有多个,您可能希望为每个创建一个进度条。 If you want to remove your progress bars after they complete, just add leave=False to manager.Counter() .如果您想在进度条完成后删除它们,只需将leave=False添加到manager.Counter()即可。

The library is very customizable and the documentation has a lot ofexamples .该库是非常可定制的,文档中有很多示例

import enlighten

BAR_FORMAT = u'{id_value} {percentage:3.0f}%|{bar}| ' u'[{elapsed}<{eta}, {rate:.2f} %/s]'

manager = enlighten.get_manager()

def api_call():
    pbar = manager.counter(total=100, bar_format=BAR_FORMAT)
    ...
    while True:
        ...
    if "meta" not in api_response:
        ...
        pbar.count = res2
        pbar.update(incr=0, id_value=id_value)

    else:
        ...
        pbar.count = 100
        pbar.update(incr=0, id_value=id_value)

    pbar.close()
    return api_response

Thanks to Aviso, and for everyone's benefit, here is the completed function -感谢 Aviso,为了大家的利益,这里是完整的 function -

def api_call():
    endpoint_url = endpoint_initializer()
    key, secret, url = ini_reader()
    
    BAR_FORMAT = u'{id_value} {percentage:3.0f}%|{bar}| ' u'[{elapsed}<{eta}, {rate:.2f} %/s]'
    manager = enlighten.get_manager()
    
    date = dt.datetime.today().strftime("%Y-%m-%d")
    print("------------------------------------\n","API URL constructed for:", date, "\n------------------------------------")
    print("-------------------------------------------------------------\n","Endpoint:", endpoint_url, "\n-------------------------------------------------------------") 
    
    pbar = manager.counter(total=100, bar_format=BAR_FORMAT)

    while True:
        response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"vendor-firm": "381"})
        api_response = json.loads(response.text) 
        
        if "meta" not in api_response:
            id_value = "id"
            res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
            id_value = "".join(res1)
            percent_value = "percent_complete"
            res2 = api_response["data"]["attributes"].get("percent_complete", '')*100
            pbar.count = res2
            pbar.update(incr=0, id_value=id_value)
            time.sleep(60)
        
        elif "meta" in api_response:
            pbar.count = 100
            pbar.update(incr=0, id_value=id_value)
            pbar.close()
            return api_response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM