我正在使用Flask-Mail扩展程序从我的Flask应用程序发送电子邮件。它同步运行send()方法,我必须等到它发送消息。如何让它在后台运行?
答案 0 :(得分:7)
它不是那么复杂 - 您需要在另一个线程中发送邮件,因此您不会阻止主线程。但有一个技巧。
这是我的代码,它呈现模板,创建邮件正文,并允许同步和异步发送它:
<强> mail_sender.py 强>
import threading
from flask import render_template, copy_current_request_context, current_app
from flask_mail import Mail, Message
mail = Mail()
def create_massege(to_email, subject, template, from_email=None, **kwargs):
if not from_email:
from_email = current_app.config['ROBOT_EMAIL']
if not to_email:
raise ValueError('Target email not defined.')
body = render_template(template, site_name=current_app.config['SITE_NAME'], **kwargs)
subject = subject.encode('utf-8')
body = body.encode('utf-8')
return Message(subject, [to_email], body, sender=from_email)
def send(to_email, subject, template, from_email=None, **kwargs):
message = create_massege(to_email, subject, template, from_email, **kwargs)
mail.send(message)
def send_async(to_email, subject, template, from_email=None, **kwargs):
message = create_massege(to_email, subject, template, from_email, **kwargs)
@copy_current_request_context
def send_message(message):
mail.send(message)
sender = threading.Thread(name='mail_sender', target=send_message, args=(message,))
sender.start()
请注意@copy_current_request_context
装饰者。这是必需的,因为Flask-Mail内部使用请求上下文。如果我们将在新线程中运行它,将错过上下文。我们可以使用@copy_current_request_context
来阻止这个装饰功能 - 当调用函数时,Flask将推送上下文。
要使用此代码,您还需要使用Flask应用程序初始化mail
对象:
<强> run.py 强>
app = Flask('app')
mail_sender.mail.init_app(app)
答案 1 :(得分:1)
使用Flask-Executor。完全披露,我亲自写出来解决了这个确切的问题。
为什么?
是这样的:
from flask import Flask, current_app
from flask_executor import Executor
from flask_mail import Mail, Message
app = Flask(__name__)
# Set email server/auth configuration in app.config[]
executor = Executor(app)
mail = Mail(app)
def send_email(to, subject, message_text, message_html):
msg = Message(subject, sender=current_app.config['MAIL_USERNAME'], recipients=[to])
msg.body = message_text
msg.html = message_html
mail.send(msg)
@app.route('/signup')
def signup():
# My signup form logic
future = executor.submit(send_email, 'recipient@example.com', 'My subject', 'My text message', '<b>My HTML message</b>')
print(future.result())
return 'ok'
if __name__ == '__main__':
app.run()
基本上,您像运行常规内联逻辑一样编写send_email
函数,然后将其提交给执行程序。无论您发送多少封电子邮件,都将运行执行程序中定义的最大线程数(默认为5 * CPU内核),并且对send_email
的请求中的任何溢出都将排队。
总体而言,您的代码可以保持整洁,您无需为要运行的每个异步函数编写一堆包装器代码。
答案 2 :(得分:0)
我想简化Marboni的代码,所以看看这里。
import threading
from flask import copy_current_request_context
from flask_mail import Message
from app import app, mail
def create_message(recipient, subject, body):
if not recipient:
raise ValueError('Target email not defined.')
subject = subject.encode('utf-8')
body = body.encode('utf-8')
return Message(subject, [recipient], body, sender=app.config['MAIL_USERNAME'] or "groundifly@gmail.com")
def send_async(recipient, subject, body):
message = create_message(recipient, subject, body)
@copy_current_request_context
def send_message(message):
mail.send(message)
sender = threading.Thread(name='mail_sender', target=send_message, args=(message,))
sender.start()