From 88514c1e70b5a811eb71964ba9f0afb749e4b1d4 Mon Sep 17 00:00:00 2001 From: tmeissner Date: Sun, 21 Oct 2018 00:18:21 +0200 Subject: [PATCH] Chapter 6: Asynchronous emails (6b) --- hello.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/hello.py b/hello.py index ba94a04..3dc6f3d 100644 --- a/hello.py +++ b/hello.py @@ -1,4 +1,5 @@ import os +from threading import Thread from flask import Flask, render_template, session, redirect, url_for from flask_bootstrap import Bootstrap from flask_moment import Moment @@ -53,12 +54,19 @@ class User(db.Model): return '' % self.username +def send_async_email(app, msg): + with app.app_context(): + mail.send(msg) + + def send_email(to, subject, template, **kwargs): msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) - mail.send(msg) + thr = Thread(target=send_async_email, args=[app, msg]) + thr.start() + return thr class NameForm(FlaskForm):