How to continue to execute python code after responding to the client's request in the view?

I have a project that needs to interface with a system of APIs. The system pushes to my django project through a message, and I must respond within 5 seconds, otherwise the other server will determine that the message push is a failure. I used the view function to do the following:


def systemAPI(request):
    ...
    #Do some data verification
    ...
    try:   
        ...
        #Do some operations, such as writing to the database
        ...
        return JsonResponse({"code":0,"msg":"success"},status = 200)   
#About the JsonResponse, According to the format requirements of the other server, I have tested it and there is no problem.The code execution time to here is very short, no more than 5 seconds
    except Exception as error: #
        ...
        #Do some operations, such as catch the exception and write to the error log 
        ...

    finally:    
        ...
        #Perform some complex operations, including network requests, database read and write, etc. The total time will exceed 5 seconds.If I control the logic processing time this time within 5 seconds, the other server will receive the correct response.
        ...

I want to know how to reply to the other server within 5 seconds. Although I responded at the beginning, the other server did not actually receive a response.

To answer the direct question being asked in the title, you can’t. The response to the client’s request ends the view. To do otherwise requires an external handler like a celery task.

So in this case, I’d accept the data, validate it to the degree possible, call the celery task with that received data, and return the response. The celery task can take as long as necessary to actually process the data.

thank you very much! I tried to solve it with the method you provided