我正在尝试运行这个非常简单的烧瓶/芹菜应用程序:
@celery.task
def send_async_email(msg):
with app.app_context():
mail.send(msg)
@celery.task(bind=True)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html', email=session.get('email', ''))
email = request.form['email']
session['email'] = email
msg = Message('Hello from Flask',
recipients=[request.form['email']])
msg.body = 'This is a test email sent from a background Celery task.'
print type(msg)
print dir(msg)
print 'msg.send'
print msg.send
print 'msg'
print msg
if request.form['submit'] == 'Send':
send_async_email.delay(msg)
flash('Sending email to {0}'.format(email))
else:
return redirect(url_for('index'))
但它不起作用,因为这个Message类的实例不是json serializable,似乎不是这样的:
msg.send
<bound method Message.send of <flask_mail.Message object at 0x7ffa94cd0290>>
msg
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Hello from Flask
From: flask@example.com
EncodeError: <flask_mail.Message object at 0x7ffa94cd0290> is not JSON serializable
答案 0 :(得分:4)
Celery要求通过代理传递的对象可以直接序列化。 flask_mail.Message
个对象不是。您应该更改send_async_email(msg)
的方法签名以接受简单的JSON兼容对象。也就是说,原始字符串,int,那些字典或类似的东西。然后,您应该在该方法中移动Message
的所有逻辑(从实例化到发送)。
例如:
@celery.task
def send_async_email(message_details):
with app.app_context():
msg = Message(message_details['subject'],
message_details['recipients'])
msg.body = message_details['body']
print type(msg)
print dir(msg)
print 'msg.send'
print msg.send
print 'msg'
print msg
mail.send(msg)
答案 1 :(得分:2)
我发现只需设置序列化并添加更改默认就像魅力一样。
app.config.update(
accept_content=['json','pickle']
)
然后,
@celery.task(serializer='pickle')
def send_async_email(msg):
答案 2 :(得分:-1)
您可以尝试将您的刻录邮件版本降级为0.9.0。
您可以使用此命令执行此操作:
pip uninstall Flask-Mail
pip install Flask-Mail==0.9.0