gpt4 book ai didi

python - flask_mail 消息实例不是 JSON 可序列化的

转载 作者:行者123 更新时间:2023-11-28 21:43:27 26 4
gpt4 key购买 nike

我正在尝试运行这个非常简单的 flask/celery 应用程序:

  @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

最佳答案

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)

关于python - flask_mail 消息实例不是 JSON 可序列化的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42237218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com