'Thread that calls function in a HTTP request throws RuntimeError: Working outside of application context
I have route within my Flask application that process a POST request and then sends an email to the client using the Flask-Mail library. I have the route returning a response to the client from checking the database before sending out an email. The email is sent from an individual thread, but I am getting this error thrown when trying to send out the email: RuntimeError: Working outside of application context.. I know that it is being thrown because the request was destroyed before the thread could process its tasks. However, I am not sure how exactly I should fix this error, especially when the route gets processed by a Blueprint.
routes.py:
from flask import request, Blueprint, redirect, render_template
from flask_app import mail, db
from flask_app.users.forms import Form
from flask_app.models import User
from flask_mail import Message
from threading import Thread
import os, re
users = Blueprint("users", __name__)
@users.route("/newsletter-subscribe", methods=["GET", "POST"])
def newsletter_subscribe():
form = Form()
if form.validate_on_submit():
user = User(name=form.name.data, email=form.email.data)
db.session.add(user)
db.session.commit()
thread_a = Compute(user, request.host_url)
thread_a.start()
return "Success"
return "Failure"
class Compute(Thread):
def __init__(self, user, host_url):
Thread.__init__(self)
self.host_url = host_url
self.user = user
def run(self):
send_welcome_email(self.user, self.host_url)
print("Finished")
def send_email(user, host_url):
with mail.connect() as con:
html = render_template("email.html", name=user.name, host_url=host_url)
subject = ""
msg = Message(
subject=subject,
recipients=[user.email],
html=html
)
con.send(msg)
Solution 1:[1]
Seeing that this question is over a year old, you may have solved this already, but I'll post this here for in case anyone else comes across it later.
I think the issue you're having is the same I had, where the send function needs the current flask app context.
You can try this within your send_email function:
Instead of:
con.send(msg)
Replace it with:
with app.app_context():
con.send(msg)
Just also make sure that you include your app in your includes section. Change this:
from flask_app import mail, db
To this:
from flask_app import app, mail, db
That should resolve the RuntimeError: Working outside of application context. issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KyleDev |
