Search code examples
pythondjangoasynchronousreturn

Run a command, after return, python


I have come across this issue, where I want to return something and call another function afterwards (in python)

heres my current code:

def new_user(request):
'''Takes a request and enters it in the database IF that wallet id is not in the database! '''
data = request.body
if data != '':
    user_info = eval(data)
    if type(user_info) != type({}):
       ... more code here ...
                send_email(vCode)
                return HttpResponse(response)

I want to call send_email after returning a response. I have tried a few things here: -calling both new_user and send_email in another function but I need to return some sort of HttpResponse (so I can't call new_user without returning it...) so this does not work - tried to yield a request, cannot call another function after yield -tried threading, had a similar issue -Currently trying asyncio but i'm running into issues with that aswell, is there anything else I can do?


Solution

  • The only way I know to achieve this would be to run the function in another thread. You say you've tried that but had no success but didn't provide an example of what you tried. Below is an example of code which should work

    import threading
    ...
    def new_user(request):
    '''Takes a request and enters it in the database IF that wallet id is not in the database! '''
    data = request.body
    if data != '':
        user_info = eval(data)
        if type(user_info) != type({}):
           ... more code here ...
                    task = threading.Thread(target=send_email, args=(vCode,))
                    task.daemon = True
                    task.start()
                    return HttpResponse(response)
    

    Note: you need to mark this thread as a daemon so that python doesn't wait for it to be joined before closing. Since you're spinning this off to be run after your code finishes this is a necessary step.

    Another option is to use some sort of task queue and send it off to be processed which you also say you're trying to do with asyncio. In a larger application that would be the better option.