'Run a function even after code exit in the background until condition is False

I am trying to check if I can build an API with asyncio where a function needs to be run continuously until a check flag is False. I either run into timeout or have the function stop abruptly once the execution is complete.

In short, my API is called. I start a worker as a background task and return a 200 response and exit the code. I am working with Python 3.6.

Here is what I have tried so far:

def fire_and_forget(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
    return wrapped

def send_response(payload):
    user_id = payload.get('user_id', "")
    user_name= payload.get('auth_key', "")
    if not MyModel.objects.filter(user_id=user_id).exists():
        MyModel.objects.create(user_id=user_id, user_name=user_name)
        MyModel.objects.filter(user_id=user_id).update(async_worker_running=True)
        print("Task started")
        task_worker(user_id, user_name)
        print("Task Ended")
    else:
        #do nothing
    return HttpResponse(status=200)

@fire_and_forget
def async_worker(user_id, user_name): 
    exit_loop=False
    while not exit_loop:
        data, exit_loop = api_to_third_party()
        Mymodel.objects.filter(user_id=user_id).update(user_data=data)
        time.sleep(5)

class MyModel(models.Model):
    user_id = models.CharField(max_length=255, null=False, blank=False)
    user_name = models.CharField(max_length=255, null=False, blank=False)
    data = models.IntegerField(null=True, blank=False)
    async_worker_running = models.BooleanField(default=False)

If I call the API with the payload needed, my task is not running in the background after the 200 success response is returned. I have been trying to tweak it but with no luck.

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source