0

I am in learning face and I need to call 2 external APIs but don't want to wait for response which means asyc call. whenever I get the 1st response from those APIs it should call one of my callback function and it should not capture the response from another API, means it should call only once time based on the response I am getting first. How should I achieve this? Below is the task-

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
  • Possible duplicate of [How to use threading in Python?](https://stackoverflow.com/questions/2846653/how-to-use-threading-in-python) – Omar Einea Apr 23 '18 at 17:20
  • @OmarEinea I checked the Queue implementation and understood that q is what having the response but now how will I do the operation with the response? – Karan Varshney Apr 23 '18 at 18:01

1 Answers1

0

Late response, but could be useful to someone else.

One possible solution can look like this:

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()

Basically, making request in a thread and giving a callback function. So whenever the response is received the same thread will make a callback to the given function.

Shubham Jain
  • 876
  • 1
  • 9
  • 17