R
R
Roman Morozov2018-12-06 16:45:15
Python
Roman Morozov, 2018-12-06 16:45:15

What doesn't the app like when it starts sending mail with an asynchronous method?

Good afternoon, tell me how to solve the problem with Flask-Mail:
Here is the error code:

Exception in thread Thread-14:
Traceback (most recent call last):
  File "C:\Users\roman\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\roman\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Работа\Git\LD-Web\LD-Site\app\controllers\mail.py", line 10, in send_async_email
    mail.send(msg)
AttributeError: module 'app.mail' has no attribute 'send'

mail.py code
from threading import Thread
from flask_mail import Message
from app import app
from app import mail


def send_async_email(application, msg):
    with application.app_context():
        mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body, attachments=None, sync=False):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    if attachments:
        for attachment in attachments:
            msg.attach(*attachment)
    if sync:
        mail.send(msg)
    else:
        Thread(target=send_async_email, args=(app, msg)).start()

__init__
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from flask_login import LoginManager
from flask_mail import Mail
from flask_moment import Moment
from config import Config
from app.database.database import init_db
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os

db = SQLAlchemy()
session = Session()
moment = Moment()
login = LoginManager()
mail = Mail()

login.login_view = 'login'


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    session.init_app(app)
    db.init_app(app)
    login.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    return app


app = create_app()


from .views import *
from .models import *

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wirehead, 2019-02-05
@wirehead

It looks like the issue is: with application .app_context()
Try this:

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question