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

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

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

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

我的应用程序.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."

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

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.

感谢您的回答。

最佳答案

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

我创建文件: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它开始倒计时,几秒钟后邮件发送。

关于python - Flask-Mail - 基于 Flask-Cookiecutter 异步发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40326651/

相关文章:

python - 为什么像 asyncio.call_later 这样的延迟调用有不超过一天的限制?

c++ - c 或 c++ 中是否有类似 subprocess.getoutput() 的函数或方法?

python - 导入错误 : No module named psycopg2 after install

python - 无法使用 Pandas DataFrame 对象上的循环获得正确的 DataFrame 形状(行*列)

python-3.x - 在切片上使用递归进行错误的冒泡排序;列表最终没有排序

python - 比较和打印嵌套循环中的元素

python - 带有开发服务器和 uwsgi 的 Flask,config.from_object()

python - 使用 Flask/Python 索引超出范围

python - 需要有关 ID3 实现和要使用的数据类型的建议

python - 检查 numpy 数组是否全部非负的最佳方法