I have a function that modifies data and returns it to the user after modifying. At this point that is the information the user needs so I want to return it ASAP, but I need that modified_data to make calls to an API and upload data it to a DB, but this can be done in the background. Is there a way to have modify_data() return while letting get_more_data() finish?
I tried using threading, but it waits until get_more_data() returns before returning modify_data. I’ve also considered placing both into seprate threads in a parent function but I need modify_data() to generate the data for get_more_data() first.
import threading
def modify_data(data):
#modify data... example
modified_data = [item+1 for item in data]
th = threading.Thread(target=get_more_data(set(modified_data)))
th.start()
return modified_data
def get_more_data(data):
#call api for more data
#upload to DB
>Solution :
In this line
th = threading.Thread(target=get_more_data(set(modified_data)))
you are executing the get_more_data method to get the target.
Try
th = threading.Thread(target=get_more_data, args=(set(modified_data),))
If you want to learn more about this, take a look here.