6

我的烧瓶项目基于Flask-Cookiecutter,我需要异步发送电子邮件。

发送电子邮件的功能由Miguel 的教程配置,同步发送工作正常,但我不知道如何修改它以异步发送。

我的应用程序.py

def create_app(config_object=ProdConfig):
    app = Flask(__name__)
    app.config.from_object(config_object)
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    return app

def register_extensions(app):
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    return None

我的观点.py

from flask import current_app

@async
def send_async_email(current_app, msg):
    with current_app.app_context():
        print('##### spustam async')
        mail.send(msg)


# Function for sending emails
def send_email(to, subject, template, **kwargs):
    msg = Message(subject, recipients=[to])
    msg.html = render_template('emails/' + template, **kwargs)
    send_async_email(current_app, msg)

view.py 中的路线

@blueprint.route('/mailer', methods=['GET', 'POST'])
def mailer():
    user = current_user.full_name
    send_email(('name@gmail.com'),
               'New mail', 'test.html',
               user=user)
    return "Mail has been send."

应用程序在我的本地主机中运行,它以命令开头:

python manage.py server

当我调用发送邮件的函数时,控制台中的输出是:

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

感谢您的任何回答。

4

3 回答 3

13

好的,我找到了我的问题的解决方案,我在这里为其他开发人员发布了它:

我创建文件:email.py,代码:

from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from .extensions import mail
from time import sleep    

def send_async_email(app, msg):
    with app.app_context():
        # block only for testing parallel thread
        for i in range(10, -1, -1):
            sleep(2)
            print('time:', i)
        print('====> sending async')
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(subject, recipients=[to])
    msg.html = render_template('emails/' + template, **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

我的观点.py:

...
from app.email import send_email
...

@blueprint.route('/mailer', methods=['GET', 'POST'])
def mailer():
    user = current_user.full_name
    send_email(('name@gmail.com'),
               'New mail', 'test.html',
               user=user)
    return "Mail has been send."

当我调用http://localhost:5000/mailer时,它开始倒计时,几秒钟后发送邮件。

于 2016-10-30T12:26:50.217 回答
4

将电子邮件发送功能移动到后台线程:

from threading import Thread

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

def send_email(to, subject, template, **kwargs):
       msg = Message(subject, recipients=[to])
       msg.html = render_template('emails/' + template, **kwargs)
       thr = Thread(target=send_async_email,args=[app,msg])
       thr.start()
       return thr
于 2016-10-30T11:23:14.800 回答
4

您可以移出app = Flask(__name__)应用程序工厂并将其放置在模块级别。这允许您将应用程序实例及其应用程序上下文传递到您的线程中以发送电子邮件。您可能需要更改其他领域的一些导入以防止循环依赖,但这应该不会太糟糕。

这是一个如何使用 Flask-Mail 和 Flask-RESTful 执行此操作的示例。它还展示了如何使用 pytest 进行测试。

from flask import Flask

from .extensions import mail
from .endpoints import register_endpoints
from .settings import ProdConfig

# app context needs to be accessible at the module level
# for the send_message.send_
app = Flask(__name__)


def create_app(config=ProdConfig):
    """ configures and returns the the flask app """
    app.config.from_object(config)

    register_extensions()
    register_endpoints(app)

    return app


def register_extensions():
    """ connects flask extensions to the app """
    mail.init_app(app)

在您发送电子邮件的模块中,您将拥有如下内容:

from flask_mail import Message

from app import app
from app import mail
from utils.decorators import async_task


def send_email(subject, sender, recipients, text_body, html_body=None, **kwargs):
    app.logger.info("send_email(subject='{subject}', recipients=['{recp}'], text_body='{txt}')".format(sender=sender, subject=subject, recp=recipients, txt=text_body))
    msg = Message(subject, sender=sender, recipients=recipients, **kwargs)
    msg.body = text_body
    msg.html = html_body

    app.logger.info("Message(to=[{m.recipients}], from='{m.sender}')".format(m=msg))
    _send_async_email(app, msg)


@async_task
def _send_async_email(flask_app, msg):
    """ Sends an send_email asynchronously
    Args:
        flask_app (flask.Flask): Current flask instance
        msg (Message): Message to send
    Returns:
        None
    """
    with flask_app.app_context():
        mail.send(msg)


(2019 年评论)

注意:我是在几年前发布的,我觉得在应用程序工厂之外实例化烧瓶对象并不理想。该send_email函数需要一个烧瓶实例才能工作,但您可以在该函数中实例化一个新的烧瓶应用程序(不要忘记您的配置)。

我想这current_app也可能有效,但我觉得这可能会产生副作用,因为它需要在当前应用程序上下文中创建一个新的应用程序上下文,这似乎是错误的,但可能会起作用。

一个不错的选择:研究celery并使用RabbitMQ作为后端。
对于较大的应用程序或容量,您可能会考虑通过消息代理(如 RabbitMQ)将电子邮件的邮件解耦到不同的应用程序。查看事件驱动设计模式。如果您有多个需要邮件服务的应用程序,这可能会很有吸引力。如果您的服务需要支持审计日志、交付恢复等,这可能会很好。

于 2017-02-05T00:28:15.657 回答