python - flask send_grid asynchronous email -


i have adapted asynchronous email example of miquel grindberg's book (highly recommended) flask use flask_sendgrid. however, code leads exception in thread. works fine first time app runs, breaks second time.

grindberg example:

def send_async_email(app, msg):     app.app_context():         mail.send(msg)   def send_email(to, subject, template, **kwargs):     app = current_app._get_current_object()     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)     thr = thread(target=send_async_email, args=[app, msg])     thr.start()     return thr 

my translation using flask_sendgrid.

def send_async_email(app, **kwargs):     app.app_context():         sendgrid.send_email(**kwargs)   def send_email(to, subject, template, **kwargs):     app = current_app._get_current_object()     html = __flask.render_template(template + '.html', **kwargs)      msg = {'html': html,'subject': subject, 'to_email': to}      thr = thread(target=send_async_email, args=(app,), kwargs=msg)     thr.start()     return thr 

grindberg's example works fine google account. however, use sendgrid offload app's emailing. need create async myself or handled sendgrid api? if not, wrong code?

to handle requests concurrently can run flask with:

app.run(threaded=true) 

by default flask runs 1 thread subsequent requests blocked until thread becomes available. in production, you'll want wsgi container gunicorn manage workers , threads.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -