在python中使用回调函数进行异步调用,并且在任何响应的情况下回调都应退出

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

我正在学习,我需要调用2个外部API,但不想等待响应,这意味着要调用asyc。每当我从这些API获得第一个响应时,都应该调用我的回调函数之一,并且不应捕获来自另一个API的响应,这意味着它应该仅根据我得到的响应调用一次。我应该如何实现?下面是任务-

def callback_function(response):
    pass #do some action here

def test_async():
    print 'some'
    print 'some2'
    request.post('api1', payload) # this should call my callback 
    request.post('api2', payload) # this should call my callback
    print 'some3'
    print 'some4'
    return 1
python python-2.x python-multithreading
1个回答
0
投票

最新回应,但可能对其他人有用。

一个可能的解决方案如下所示:

import threading
import time
import random


def dummy_rqst():
    rndint = random.randint(1,5)
    print(f"request received at :{time.time()}")
    time.sleep(rndint)
    return rndint

def callback_function(response):
    # pass #do some action here
    print(f"Response received :{response}, time:{time.time()}")
    return


def async_request(api,payload,callback):
    # response = request.post(api,payload)
    response = dummy_rqst()
    callback(response)
    return


def test_async():
    print('some')
    print('some2')
    rqst_thread1 = threading.Thread(target=async_request,args=('api1',None,callback_function,))
    rqst_thread1.start()
    rqst_thread2 = threading.Thread(target=async_request,args=('api2',None,callback_function,))
    rqst_thread2.start()
    print('some3')
    print('some4')
    return 1

if __name__ == "__main__":
    test_async()

基本上是在线程中发出请求并提供回调函数。因此,每当收到响应时,相同的线程都会回调给定的函数。

© www.soinside.com 2019 - 2024. All rights reserved.