Thread that calls function in a HTTP request throws RuntimeError: Working outside of application context

时光总嘲笑我的痴心妄想 提交于 2021-01-28 20:31:35

问题


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)

来源:https://stackoverflow.com/questions/63330734/thread-that-calls-function-in-a-http-request-throws-runtimeerror-working-outsid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!