Python 想用新线程装饰电子邮件发送吗
我一心想装饰这个功能。 帮我找出问题所在。 装饰师:Python 想用新线程装饰电子邮件发送吗,python,multithreading,flask,Python,Multithreading,Flask,我一心想装饰这个功能。 帮我找出问题所在。 装饰师: def sync(f): def wrapper(*args, **kwargs): thr = Thread(target=f, args=args, kwargs=kwargs) thr.start() return wrapper 发送功能: def send_email(subject, sender, recipients, text_body, html_body): ""
def sync(f):
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kwargs=kwargs)
thr.start()
return wrapper
发送功能:
def send_email(subject, sender, recipients, text_body, html_body):
""" Build and send e-mail with the provided parameters."""
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
mail.send(msg)
@sync
def send_confirmation_email(recipient, app = current_app):
"""Send registration email to the provided recipient."""
subject = 'Account confirmation e-mail'
sender = 'some.mail.for.testing@domain.com'
recipients = [recipient]
activation, deletion = confirmation_links(recipient) #construct hashed links
text_body = render_template('confirmation_email.txt',
activation = activation,
deletion = deletion)
html_body = render_template('confirmation_email.html',
activation = activation,
deletion = deletion)
send_email(subject, sender, recipients, text_body, html_body)
视图功能:
@app.route('/signup', methods = ['GET', 'POST'])
def signup():
form = SignupForm()
if form.validate_on_submit():
send_confirmation_email(recipient = form.email.data)
return redirect(url_for('activate'))
else:
return render_template('signup.html',
title = 'Sign Up',
form = form)
问题在于,电子邮件不是通过active decorator@sync
发送的。
当我删除@sync
装饰器时,一切都正常,当然,没有线程。
而app
在重定向之前等待几秒钟。
任何帮助都会有帮助。谢谢。该渲染模板
功能需要一个
当send\u confirmation\u email
功能在单独的线程中运行时,没有为render\u模板
设置应用程序上下文
您可以使用app.app\u context()
解决此问题:
你也可以考虑使用类似于的方法来代替芹菜。。这是处理这样一个问题的更正确的方法。。这是一个伟大的梦想example@brunsgaard,谢谢你的链接。这是我正在创建的一个小应用程序,线程只使用一次。我同意芹菜是一种很好的做法。事实上,在我的应用程序中实现你的答案时出了问题。邮件没有发送。最后,我通过创建一个函数来解决这个问题,该函数只接收msg(message)并发送消息,然后调用同步装饰器<代码>app.app_context()
我没有使用,但是这些信息和帮助非常有价值+1.
@sync
def send_confirmation_email(recipient):
"""Send registration email to the provided recipient."""
with app.app_context():
subject = 'Account confirmation e-mail'
sender = 'some.mail.for.testing@domain.com'
recipients = [recipient]
activation, deletion = confirmation_links(recipient) #construct hashed links
text_body = render_template('confirmation_email.txt',
activation = activation,
deletion = deletion)
html_body = render_template('confirmation_email.html',
activation = activation,
deletion = deletion)
send_email(subject, sender, recipients, text_body, html_body)