2

My question is basically the Python version of this question:

code structure:

def save(request):
    if request.method == 'POST':
        ...
        email_obj.save()  # write data into database

        # the below sendmail step takes too long to finish
        # how to execute it without waiting for it to finish
        # then immediately run the last step: return render(request, 'success.html')
        sendmail(email_obj)  # 

        return render(request, 'success.html')
J.W
  • 671
  • 7
  • 23
  • How long is too long?? Yes, it's legitimate to want to send mail asynchronously.. but.. unless you're generating some very complex report then emailing it, it shouldn't take more than a second or two.. usually less. If you're communicating with a remote smtp server that's slow, you may want to run a local relayhost (eg. postfix) which will accept your mail quickly and then forward it without holding you back... – little_birdie May 10 '22 at 23:30

1 Answers1

1

You can employ threading to achieve this. Your code will look something like this -

import threading

def save(request):
if request.method == 'POST':
    ...
    email_obj.save()  # write data into database

    # the below sendmail step takes too long to finish
    # how to execute it without waiting for it to finish
    # then immediately run the last step: return render(request, 'success.html')
    # This will create a thread for the function and asynchronously execute it
    email_thread = threading.Thread(target=sendmail, name="Email Thread", args=email_obj)
    email_thread.start() 

    return render(request, 'success.html')