iT邦幫忙

0

每日技術:python中使用async時,如何得到回傳結果

  • 分享至 

  • xImage
  •  

場景是:我要批量打api:異步打api之後,統計所有成功的api,存在successCount(int)中;
代碼如下

def cloudUpdateOwnerDoveInfoMulti(self, url,paramsList):
        '''
        依據本地端公環相對應的 ownerid and doveid 批量更新雲端公環對應的鴿主與鴿舍資訊
            Parameters:
                url(string)
                paramsList (Array[object]): {raceID, ownerID, ownerName, doveID, orgRing, dovecoteID, rfID}
             Returns:
                successCount (int)
        '''
        try:
            # sess = requests.Session()
            successCount= 0
            failCount = 0
            payloadList = []
            for params in paramsList:
                ownerID = params['ownerID']
                ownerName = params['ownerName']
                doveID = params['doveID']
                orgRing = params['orgRing']
                dovecoteID = params['dovecoteID']
                rfID = params['rfID']
                raceID = params['raceID']

                payload = {
                'updatetype' : 'ownerDove',
                'ownerID' : ownerID,
                'ownerName' : ownerName,
                'doveID' : doveID,
                'orgRing' : orgRing,
                'dovecoteID' : dovecoteID,
                'rfid' : rfID,
                'raceID' : raceID
                }
                payloadList.append(payload)

            async def sendRequest(session,param):
                async with session.post(url,data=param,verify_ssl =False) as response:
                    return await response.json()
            async def loopAskapi():
                successCount = 0
                async with aiohttp.ClientSession() as session:
                    tasks = []
                    for payload in payloadList:
                        task = asyncio.ensure_future(sendRequest(session, payload))
                        # task = sendRequest(session,payload)
                        tasks.append(task)
                    responses = await asyncio.gather(*tasks)
                    print(len(responses))
                    for res in responses:
                        # print(res)
                        # j = json.loads(r.text)
                        status = res['results']
                        if status == 1:
                            successCount +=1
                    print("successCount in func",successCount)
                        # print('status', successCount+failCount)
                return successCount
            
            def start_loop(loop):
                asyncio.set_event_loop(loop)
                print("successCount in return",loop.run_until_complete(loopAskapi()))
            
            #一般使用下面這段代碼開線程
            # loop = asyncio.new_event_loop()
            # t = threading.Thread(target=start_loop, args=(loop,))
            # t.start()
            # t.join()

            #**但是如果要得到回傳結果的話,使用下面這段代碼,把結果保存在自定義的線程物件中**
            class MyThread(threading.Thread):
                def __init__(self,loop):
                    threading.Thread.__init__(self)
                    self.loop = loop
                    self.successCount = 0

                def run(self):
                    asyncio.set_event_loop(self.loop)
                    self.successCount = loop.run_until_complete(loopAskapi())

            loop = asyncio.new_event_loop()
            t = MyThread(loop)
            t.start()  # start the thread
            t.join()   # wait for the thread to complete

            # get the result from the thread
            successCount = t.successCount

            return successCount
            # print(responseList)
        except Exception as e:
            print(e)中
            return 0

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言