2

我正在尝试运行这个非常简单的烧瓶/芹菜应用程序:

  @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 可序列化的,似乎并非如此:

    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
4

3 回答 3

3

Celery 要求通过代理传递的对象可以直接序列化。flask_mail.Message对象不是。您应该更改方法签名send_async_email(msg)以接受简单的 JSON 兼容对象。也就是说,原始字符串、整数、这些的字典或类似的东西。然后,您应该在该方法内移动所有逻辑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)
于 2017-02-20T10:00:35.810 回答
2

我发现通过简单地设置序列化并添加更改默认值就像一个魅力。

app.config.update(
accept_content=['json','pickle']
)

然后,

@celery.task(serializer='pickle')
def send_async_email(msg):
于 2017-06-27T22:33:00.300 回答
0

您可以尝试将您的烧瓶邮件版本降级到 0.9.0。

您可以使用以下命令执行此操作:

pip uninstall Flask-Mail
pip install Flask-Mail==0.9.0
于 2017-02-19T19:20:45.883 回答