📖 Scenario: You are building a simple Flask web app that sends emails. To keep the app responsive, you want to send emails asynchronously, so the user does not wait for the email to be sent before getting a response.
🎯 Goal: Build a Flask app that sends an email asynchronously using a background thread.
📋 What You'll Learn
Create a Flask app with a route to send email
Set up a function to send email
Use a background thread to send email asynchronously
Return a response immediately after starting the email thread
💡 Why This Matters
🌍 Real World
Web applications often need to send emails like confirmations or notifications without making users wait. Sending emails asynchronously improves user experience by keeping the app responsive.
💼 Career
Understanding asynchronous tasks in web frameworks like Flask is essential for backend developers to build scalable and user-friendly applications.
Progress0 / 4 steps
1
Set up Flask app and email data
Create a Flask app instance called app and a dictionary called email_data with keys recipient, subject, and body having values 'user@example.com', 'Welcome', and 'Hello from Flask!' respectively.
Flask
Hint
Use Flask(__name__) to create the app. Define email_data as a dictionary with the exact keys and values.
2
Create a config variable for email sender
Add a variable called sender_email and set it to 'noreply@example.com' to represent the sender's email address.
Flask
Hint
Just create a variable sender_email and assign the exact string.
3
Define the async email sending function
Define a function called send_email that takes recipient, subject, and body as parameters. Inside, simulate sending email by importing time and calling time.sleep(2) to mimic delay. Then print f"Email sent to {recipient} with subject {subject}".
Flask
Hint
Use def send_email(recipient, subject, body):. Inside, import time and call time.sleep(2). Then print the message with f-string.
4
Create route to send email asynchronously
Import threading. Create a Flask route @app.route('/send') with a function send. Inside, start a new thread with target send_email and arguments email_data['recipient'], email_data['subject'], email_data['body']. Start the thread and return the string 'Email is being sent!' immediately.
Flask
Hint
Import threading. Use @app.route('/send') and define send(). Create a thread with threading.Thread(target=send_email, args=(...)), start it, and return the message.
Practice
(1/5)
1. What is the main benefit of sending emails asynchronously in a Flask app?
easy
A. Emails are sent faster than synchronous sending
B. It automatically retries sending emails on failure
C. The app remains responsive and does not wait for the email to send
D. It encrypts emails for security
Solution
Step 1: Understand synchronous vs asynchronous sending
Synchronous sending blocks the app until the email is sent, causing delays.
Step 2: Identify async sending advantage
Async sending lets the app continue running while the email sends in the background.
Final Answer:
The app remains responsive and does not wait for the email to send -> Option C
Quick Check:
Async sending = app stays responsive [OK]
Hint: Async means non-blocking, so app stays fast [OK]
Common Mistakes:
Thinking async sends emails faster
Assuming async retries automatically
Confusing async with encryption
2. Which of the following is the correct way to start a new thread for async email sending in Flask?
easy
A. threading.Thread(send_email()).start()
B. threading.Thread(target=send_email).start()
C. threading.Thread(target=send_email())
D. threading.Thread(send_email).run()
Solution
Step 1: Identify correct threading syntax
The target argument must be the function name without calling it (no parentheses).
Step 2: Check method to start thread
Use .start() to run the thread asynchronously, not .run().
Final Answer:
threading.Thread(target=send_email).start() -> Option B
Quick Check:
Use target=function and call .start() [OK]
Hint: Pass function name to target, call .start() to run thread [OK]
Common Mistakes:
Calling the function inside target argument
Using .run() instead of .start()
Missing target keyword
3. Given this Flask async email code snippet, what will be printed?
from threading import Thread
from flask import Flask, current_app
app = Flask(__name__)
def send_async_email(app, msg):
with app.app_context():
print(f"Sending email to {msg['to']}")
def send_email(msg):
Thread(target=send_async_email, args=(app, msg)).start()
msg = {'to': 'user@example.com'}
send_email(msg)
medium
A. Sending email to {'to': 'user@example.com'}
B. Error: app context missing
C. Nothing is printed
D. Sending email to user@example.com
Solution
Step 1: Understand app context usage
The send_async_email function uses app.app_context() to access Flask context safely in thread.
Step 2: Analyze print statement
It prints the 'to' value from msg dictionary, which is 'user@example.com'.
The send_async_email function lacks app.app_context(), so it may fail or behave unexpectedly.
Final Answer:
Missing Flask app context in thread -> Option A
Quick Check:
Threads need app context to access Flask safely [OK]
Hint: Always use app.app_context() inside threads [OK]
Common Mistakes:
Ignoring app context in threads
Confusing target function in Thread
Misunderstanding args format
5. You want to send an email asynchronously in Flask but also log the email sending status after it finishes. Which approach correctly combines async sending with logging?
hard
A. Use a thread with app context to send email, then log inside the same thread after sending
B. Send email synchronously, then start a thread to log status
C. Start two separate threads: one for sending email, one for logging, without app context
D. Send email asynchronously but log status immediately after starting the thread
Solution
Step 1: Understand async email sending with app context
Sending email in a thread requires app.app_context() to access Flask features safely.
Step 2: Combine logging after sending in same thread
Logging after sending inside the same thread ensures the status reflects actual completion.
Step 3: Evaluate other options
Logging before or in separate threads without context risks incorrect or missing info.
Final Answer:
Use a thread with app context to send email, then log inside the same thread after sending -> Option A
Quick Check:
Send and log in same app-context thread [OK]
Hint: Log after sending inside same app-context thread [OK]
Common Mistakes:
Logging before email is sent
Starting logging thread without app context
Separating send and log in different threads
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.