Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter

2024/12/9 21:08:58

My flask project is based on Flask-Cookiecutter and I need to send emails asynchronously.

Function for sending email was configured by Miguel’s Tutorial and sending synchronously works fine, but i don’t know, how I can modify it for sending asynchronously.

My app.py

def create_app(config_object=ProdConfig):app = Flask(__name__)app.config.from_object(config_object)register_extensions(app)register_blueprints(app)register_errorhandlers(app)return appdef register_extensions(app):assets.init_app(app)bcrypt.init_app(app)cache.init_app(app)db.init_app(app)login_manager.init_app(app)debug_toolbar.init_app(app)migrate.init_app(app, db)mail.init_app(app)return None

my view.py

from flask import current_app@async
def send_async_email(current_app, msg):with current_app.app_context():print('##### spustam async')mail.send(msg)# Function for sending emails
def send_email(to, subject, template, **kwargs):msg = Message(subject, recipients=[to])msg.html = render_template('emails/' + template, **kwargs)send_async_email(current_app, msg)

route in view.py

@blueprint.route('/mailer', methods=['GET', 'POST'])
def mailer():user = current_user.full_namesend_email(('[email protected]'),'New mail', 'test.html',user=user)return "Mail has been send."

Application run in my localhost and it's starting with command:

python manage.py server

When i call function for sending mail, output in console is:

RuntimeError: Working outside of application context.This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

Thanks for any answer.

Answer

Okay, i found solution for my question i posting it here for others developers:

I create file: email.py with code:

from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from .extensions import mail
from time import sleep    def send_async_email(app, msg):with app.app_context():# block only for testing parallel threadfor i in range(10, -1, -1):sleep(2)print('time:', i)print('====> sending async')mail.send(msg)def send_email(to, subject, template, **kwargs):app = current_app._get_current_object()msg = Message(subject, recipients=[to])msg.html = render_template('emails/' + template, **kwargs)thr = Thread(target=send_async_email, args=[app, msg])thr.start()return thr

my view.py:

...
from app.email import send_email
...@blueprint.route('/mailer', methods=['GET', 'POST'])
def mailer():user = current_user.full_namesend_email(('[email protected]'),'New mail', 'test.html',user=user)return "Mail has been send."

And when i call http://localhost:5000/mailer it starts countdown and after few seconds is mail sent.

https://en.xdnf.cn/q/72768.html

Related Q&A

Change text_factory in Django/sqlite

I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is fro…

Shuffle patches in image batch

I am trying to create a transform that shuffles the patches of each image in a batch. I aim to use it in the same manner as the rest of the transformations in torchvision: trans = transforms.Compose([t…

Python looping: idiomatically comparing successive items in a list

I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (Im using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering…

Geodesic buffering in python

Given land polygons as a Shapely MultiPolygon, I want to find the (Multi-)Polygon that represents the e.g. 12 nautical mile buffer around the coastlines.Using the Shapely buffer method does not work si…

jinja2 variables naming - Are variables naming restrictions the same as for Python variables?

I didt find it written explicitly in the docs.Are the naming rules the same as with Python variables?(eg: {{ a_variablelike_that }} doesnt work for example)

What does t /= d mean? Python and getting errors

// t: current time, b: begInnIng value, c: change In value, d: durationdef: easeOutQuad, swing: function (x, t, b, c, d) {//alert(jQuery.easing.default);return jQuery.easing[jQuery.easing.def](x, t, b,…

Python File Read + Write

I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with \t delineated columns and one row per line.I am trying to write a Python …

Uploading a file via pyCurl

I am trying to convert the following curl code into pycurl. I do not want to use requests. I need to use pycurl because requests is not fully working in my old python version.curl -X POST -H "Acce…

Speed up computation for Distance Transform on Image in Python

I would like to find the find the distance transform of a binary image in the fastest way possible without using the scipy package distance_trnsform_edt(). The image is 256 by 256. The reason I dont wa…

Prevent Kivy leaving debug messages

I have a simple a Kivy interface that also uses the terminal. Example code:import kivykivy.require(1.0.6)from kivy.app import App from kivy.uix.label import Labelclass MyApp(App):def build(self):return…