July 2019
Beginner to intermediate
302 pages
9h 38m
English
Doing an asynchronous execution with the threading package is very simple. Just add the following code to my_app/catalog/views.py:
from threading import Thread
def send_mail(message):
with app.app_context():
mail.send(message)
# Replace the line below in create_category()
# mail.send(message)
# by
t = Thread(target=send_mail, args=(message,))t.start()
As you can see, the sending of an email happens in a new thread, which sends the message as a parameter to the newly created method. We need to create a new send_mail() method because our email templates contain url_for, which can only be executed inside an application context; this won't be available in the newly created thread by default. It provides the flexibility of starting ...