Skip to Content
Flask Framework Cookbook - Second Edition
book

Flask Framework Cookbook - Second Edition

by Shalabh Aggarwal
July 2019
Beginner to intermediate
302 pages
9h 38m
English
Packt Publishing
Content preview from Flask Framework Cookbook - Second Edition

How to do it...

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Writing a Web Application with Flask

Writing a Web Application with Flask

Doug Farrell
Mastering Flask

Mastering Flask

Jack Stouffer

Publisher Resources

ISBN: 9781789951295Supplemental Content