Flask-Mail - 基于Flask-Cookiecutter异步发送电子邮件

时间:2016-10-30 06:44:18

标签: python python-3.x flask flask-mail

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

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

我的app.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

我的view.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."

应用程序在我的localhost中运行,它以命令开头:

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.

感谢您的回答。

3 个答案:

答案 0 :(得分:4)

好的,我找到了我的问题的解决方案,我在这里发布给其他开发者:

我使用代码创建文件: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

我的view.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时,它会开始倒计时,并在几秒后发送邮件。

答案 1 :(得分:4)

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

这是使用Flask-Mail和Flask-RESTful的example of how you can do this。它还展示了如何使用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评论)

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

我猜想current_app也可能有效,但我认为可能会产生副作用,因为它需要在当前应用程序上下文中创建一个新的应用程序上下文,看起来是错误的,但可能会有效。< / p>

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

答案 2 :(得分:2)

将电子邮件发送功能移至后台主题:

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
相关问题