Skip to content

Commit 070b2df

Browse files
committed
format
1 parent a877430 commit 070b2df

File tree

1 file changed

+111
-39
lines changed

1 file changed

+111
-39
lines changed

source/integrations/flask-celery-integration.txt

Lines changed: 111 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,38 @@ Tutorial: Flask and Celery Integration
2121
Overview
2222
--------
2323

24-
In this tutorial, you can learn how to use MongoDB, Flask, and Celery to build a newsletter platform. This application allows users to subscribe to newsletters, and administrators to manage and send batch emails asynchronously.
24+
In this tutorial, you can learn how to use MongoDB, Flask, and Celery to build a
25+
newsletter platform. This application allows users to subscribe to newsletters,
26+
and administrators to manage and send batch emails asynchronously.
2527

2628
Flask
2729
~~~~~
2830

2931
Flask is a lightweight web application framework with built-in configuration and
3032
convention defaults that provide consistency to developers across projects. For
31-
more information, see the `Flask webpage <https://flask.palletsprojects.com/en/stable/>`__.
33+
more information, see the `Flask webpage
34+
<https://flask.palletsprojects.com/en/stable/>`__.
3235

3336
Celery
3437
~~~~~~
3538

36-
Celery is an open-source distributed task queue that handles large volumes of messages efficiently. It supports asynchronous processing and task scheduling. For more information, see the `Celery webpage <https://docs.celeryq.dev/en/main/index.html>`__.
39+
Celery is an open-source distributed task queue that handles large volumes of
40+
messages efficiently. It supports asynchronous processing and task scheduling.
41+
For more information, see the `Celery webpage
42+
<https://docs.celeryq.dev/en/main/index.html>`__.
3743

3844
Tutorial
3945
--------
4046

41-
This tutorial creates a modified version of the sample application in the :github:`Newsletter Platform with JavaScript, Flask, and MongoDB sample project </mercybassey/newsletter-javascript-flask-mongodb>` GitHub repository.
47+
This tutorial creates a modified version of the sample application in the
48+
:github:`Newsletter Platform with JavaScript, Flask, and MongoDB sample project
49+
</mercybassey/newsletter-javascript-flask-mongodb>` GitHub repository.
4250

4351
Prerequisites
4452
~~~~~~~~~~~~~
4553

46-
Ensure that you have the following components installed and set up before you start this tutorial:
54+
Ensure that you have the following components installed and set up before you
55+
start this tutorial:
4756

4857
- A MongoDB cluster. We recommend that you use Atlas. To learn how
4958
to create an Atlas cluster, see the
@@ -52,7 +61,8 @@ Ensure that you have the following components installed and set up before you st
5261
- A database named ``newsletter`` in your cluster. For more information, see
5362
the :atlas:`Create a Database </atlas-ui/databases/#create-a-database>` page
5463
in the Atlas guide.
55-
- `RabbitMQ <https://www.rabbitmq.com/docs/download>`__ to use as a message broker for Celery.
64+
- `RabbitMQ <https://www.rabbitmq.com/docs/download>`__ to use as a message
65+
broker for Celery.
5666
- `Gmail <www.gmail.com>`__ to use as an SMTP server. For more information about
5767
SMTP servers, see the :wikipedia:`Simple Mail Transfer Protocol
5868
<Simple_Mail_Transfer_Protocol>` Wikipedia page.
@@ -65,8 +75,10 @@ Setup
6575
:style: connected
6676

6777
.. step:: Create your project directory and structure
68-
69-
The name of your project directory is ``newsletter``. Create your directory and navigate to it by running the following commands in terminal:
78+
79+
The name of your project directory is ``newsletter``. Create your
80+
directory and navigate to it by running the following commands in
81+
terminal:
7082

7183
.. code-block:: bash
7284

@@ -80,7 +92,8 @@ Setup
8092
MongoDB connection details, mail server configuration, Celery broker
8193
connection, and any other environment-specific variables
8294
- ``tasks.py``: Defines background tasks to send emails asynchronously
83-
- ``routes.py``: Defines the routes (URLs) that your application responds to
95+
- ``routes.py``: Defines the routes (URLs) that your application responds
96+
to
8497

8598
We recommend structuring your application to separate concerns, which can
8699
make the application modular and more maintainable.
@@ -104,8 +117,10 @@ Setup
104117

105118
Your application depends on the following libraries:
106119

107-
- `Flask <https://flask.palletsprojects.com/en/stable/>`__ for handling the web server and routing
108-
- `Flask Mail <https://pypi.org/project/Flask-Mail/>`__ for sending emails from your application
120+
- `Flask <https://flask.palletsprojects.com/en/stable/>`__ for handling
121+
the web server and routing
122+
- `Flask Mail <https://pypi.org/project/Flask-Mail/>`__ for sending emails
123+
from your application
109124
- :ref:`{+driver-short+} <pymongo-get-started-download-and-install>`
110125
- `Celery <https://docs.celeryq.dev/en/stable/>`__ to manage tasks, such
111126
as sending batch emails
@@ -117,7 +132,8 @@ Setup
117132
different versions of libraries for different projects. Before running
118133
any ``pip`` commands, ensure that your ``virtualenv`` is active.
119134

120-
Run the following ``pip`` command in your terminal to install the dependencies:
135+
Run the following ``pip`` command in your terminal to install the
136+
dependencies:
121137

122138
.. code-block:: bash
123139

@@ -126,13 +142,15 @@ Setup
126142
Configure Your Application
127143
~~~~~~~~~~~~~~~~~~~~~~~~~~
128144

129-
The ``config.py`` file contains the settings and credentials to perform the following actions:
145+
The ``config.py`` file contains the settings and credentials to perform the
146+
following actions:
130147

131148
- Connect Celery to RabbitMQ as its message broker
132149
- Configure Flask-Mail to use Gmail as its SMTP server
133150
- Connect your application to your MongoDB server
134151

135-
Define the necessary configurations by adding the following code to your ``config.py`` file:
152+
Define the necessary configurations by adding the following code to your
153+
``config.py`` file:
136154

137155
.. code-block:: python
138156

@@ -150,22 +168,37 @@ Define the necessary configurations by adding the following code to your ``confi
150168
CELERY_BROKER_URL = 'amqp://guest:guest@localhost//'
151169
RESULT_BACKEND = MONGO_URI + '/celery_results'
152170

153-
You must provide your Gmail credentials and email (``MAIL_USERNAME``, ``MAIL_PASSWORD``, and ``MAIL_DEFAULT_SENDER``) to enable your application to send emails. For security purposes, we recommend that you generate an app password to use, rather than using your primary password. For more information, see the `App Password settings <https://myaccount.google.com/apppasswords>`__ in your Google Account.
171+
You must provide your Gmail credentials and email (``MAIL_USERNAME``,
172+
``MAIL_PASSWORD``, and ``MAIL_DEFAULT_SENDER``) to enable your application to
173+
send emails. For security purposes, we recommend that you generate an app
174+
password to use, rather than using your primary password. For more information,
175+
see the `App Password settings <https://myaccount.google.com/apppasswords>`__ in
176+
your Google Account.
154177

155-
You must also provide a connection string to set into the ``MONGO_URI`` environment variable. For more information see the :ref:`Create a Connection String <pymongo-get-started-connection-string>` section of this guide.
178+
You must also provide a connection string to set into the ``MONGO_URI``
179+
environment variable. For more information see the :ref:`Create a Connection
180+
String <pymongo-get-started-connection-string>` section of this guide.
156181

157-
The provided Celery broker URL (``CELERY_BROKER_URL``) specifies RabbitMQ as its broker, but you can customize this URL to support other implementations. For more information, see the `Broker Settings <https://docs.celeryq.dev/en/stable/userguide/configuration.html#broker-settings>`__ section of the Celery documentation.
182+
The provided Celery broker URL (``CELERY_BROKER_URL``) specifies RabbitMQ as its
183+
broker, but you can customize this URL to support other implementations. For
184+
more information, see the `Broker Settings
185+
<https://docs.celeryq.dev/en/stable/userguide/configuration.html#broker-settings>`__
186+
section of the Celery documentation.
158187

159-
The ``ALLOWED_IPS`` list is used to control access to the :guilabel:`Send Newsletter` page. The rest of the variables configure the Flask and Celery components.
188+
The ``ALLOWED_IPS`` list is used to control access to the :guilabel:`Send
189+
Newsletter` page. The rest of the variables configure the Flask and Celery
190+
components.
160191

161192
Initialize Flask, MongoDB, and Celery
162193
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163194

164-
The ``app.py`` file initializes and configures the core components of the Flask application. It performs the following tasks:
195+
The ``app.py`` file initializes and configures the core components of the Flask
196+
application. It performs the following tasks:
165197

166198
- Creates a Flask application and loads configuration constants
167199
- Initializes a Flask-Mail instance with the app's mail server settings
168-
- Connects to the ``newsletter`` MongoDB database by using the {+driver-short+} driver
200+
- Connects to the ``newsletter`` MongoDB database by using the {+driver-short+}
201+
driver
169202
- Creates a Celery instance configured with the Flask app and your chosen broker
170203

171204
Initialize Flask, MongoDB, and Celery by adding the following code to your
@@ -202,15 +235,32 @@ Initialize Flask, MongoDB, and Celery by adding the following code to your
202235
Create a Celery Task
203236
~~~~~~~~~~~~~~~~~~~~
204237

205-
The Celery task uses the components instantiated in your ``app.py`` file to send a newsletter email to subscribers.
206-
207-
The ``@celery.task()`` decorator registers the function as a Celery task. Setting ``bind=True`` means the function receives the task instance as the ``self`` argument, which allows it to access Celery task methods and metadata. For more information about tasks, see the `celery.app.task <https://docs.celeryq.dev/en/stable/reference/celery.app.task.html>`__ API documentation.
208-
209-
Since this task runs outside of Flask's HTTP request cycle, you must manually provide application context by wrapping the email logic in a ``with app.app_context()`` block. This gives Flask access to other components like the Flask-Mail ``mail`` instance and the {+driver-short+} connection to your ``newsletter`` MongoDB database.
210-
211-
This method loops through the list of ``subscribers``, creates an email using the Flask-Mail ``Message`` class, and then sends it to each user by using the ``mail`` object. After each email is sent, it logs the delivery by inserting a document into your MongoDB ``deliveries`` collection to record that the message was sent. Each email operation is wrapped in a ``try`` block to ensure that in the case of an error, the failure is logged and the database is not updated with a false delivery record.
212-
213-
Define your ``send_emails()`` method by adding the following code to your ``tasks.py`` file:
238+
The Celery task uses the components instantiated in your ``app.py`` file to send
239+
a newsletter email to subscribers.
240+
241+
The ``@celery.task()`` decorator registers the function as a Celery task.
242+
Setting ``bind=True`` means the function receives the task instance as the
243+
``self`` argument, which allows it to access Celery task methods and metadata.
244+
For more information about tasks, see the `celery.app.task
245+
<https://docs.celeryq.dev/en/stable/reference/celery.app.task.html>`__ API
246+
documentation.
247+
248+
Since this task runs outside of Flask's HTTP request cycle, you must manually
249+
provide application context by wrapping the email logic in a ``with
250+
app.app_context()`` block. This gives Flask access to other components like the
251+
Flask-Mail ``mail`` instance and the {+driver-short+} connection to your
252+
``newsletter`` MongoDB database.
253+
254+
This method loops through the list of ``subscribers``, creates an email using
255+
the Flask-Mail ``Message`` class, and then sends it to each user by using the
256+
``mail`` object. After each email is sent, it logs the delivery by inserting a
257+
document into your MongoDB ``deliveries`` collection to record that the message
258+
was sent. Each email operation is wrapped in a ``try`` block to ensure that in
259+
the case of an error, the failure is logged and the database is not updated with
260+
a false delivery record.
261+
262+
Define your ``send_emails()`` method by adding the following code to your
263+
``tasks.py`` file:
214264

215265
.. code-block:: python
216266

@@ -236,19 +286,30 @@ Define your ``send_emails()`` method by adding the following code to your ``task
236286
print("Email sent")
237287

238288
except Exception as e:
239-
print(f"Failed to send email to {subscriber['email']}: {str(e)}")
289+
print(f"Failed to send email to {subscriber['email']}: {str(e)}")
240290

241291
return {'result': 'All emails sent'}
242292

243293

244294
Define Your Routes
245295
~~~~~~~~~~~~~~~~~~
246296

247-
In Flask, the ``@app.route()`` decorator assigns a URL path to a specific function. In the following code, it is used to define the root (``/``), ``/admin``, ``/subscribe``, and ``/send-newsletters`` routes. The optional ``methods`` parameter is used in some cases to define a list of allowable HTTP methods.
297+
In Flask, the ``@app.route()`` decorator assigns a URL path to a specific
298+
function. In the following code, it is used to define the root (``/``),
299+
``/admin``, ``/subscribe``, and ``/send-newsletters`` routes. The optional
300+
``methods`` parameter is used in some cases to define a list of allowable HTTP
301+
methods.
248302

249-
The ``@app.before_request()`` method sets a function to run before every request. In this case, the function provides some basic security by limiting access to the ``admin`` page to IP addresses listed in the ``ALLOWED_IPS`` parameter defined in the ``config.py`` file. Specifically, access is only allowed for the ``localhost``.
303+
The ``@app.before_request()`` method sets a function to run before every
304+
request. In this case, the function provides some basic security by limiting
305+
access to the ``admin`` page to IP addresses listed in the ``ALLOWED_IPS``
306+
parameter defined in the ``config.py`` file. Specifically, access is only
307+
allowed for the ``localhost``.
250308

251-
The root and ``/admin`` routes render pages using the ``render_template()`` method. The ``/subscribe`` and ``/send-newsletters`` routes access request parameters in ``request.form[]`` to execute commands, and then return HTTP responses.
309+
The root and ``/admin`` routes render pages using the ``render_template()``
310+
method. The ``/subscribe`` and ``/send-newsletters`` routes access request
311+
parameters in ``request.form[]`` to execute commands, and then return HTTP
312+
responses.
252313

253314
Define your routes by adding the following code to your ``routes.py`` file:
254315

@@ -314,12 +375,17 @@ application in this file.
314375
Create Your Pages
315376
~~~~~~~~~~~~~~~~~
316377

317-
The HTML files in the ``templates`` directory define the user interface, and are written using standard HTML. Since this application uses asynchronous HTTP requests, the scripts in these files use :wikipedia:`Fetch API calls <XMLHttpRequest#Fetch_alternative>`. These scripts also handle timeouts and errors.
378+
The HTML files in the ``templates`` directory define the user interface, and are
379+
written using standard HTML. Since this application uses asynchronous HTTP
380+
requests, the scripts in these files use :wikipedia:`Fetch API calls
381+
<XMLHttpRequest#Fetch_alternative>`. These scripts also handle timeouts and
382+
errors.
318383

319384
Subscribe Page
320385
```````````````
321386

322-
Copy the following code into your ``subscribe.html`` file to create your :guilabel:`Subscribe to Newsletter` page.
387+
Copy the following code into your ``subscribe.html`` file to create your
388+
:guilabel:`Subscribe to Newsletter` page.
323389

324390
.. code-block:: html
325391

@@ -439,7 +505,8 @@ Copy the following code into your ``admin.html`` file to create your
439505
Format Your Pages
440506
~~~~~~~~~~~~~~~~~
441507

442-
You can apply a style sheet to your templates by adding the following code to the ``styles.css`` file:
508+
You can apply a style sheet to your templates by adding the following code to
509+
the ``styles.css`` file:
443510

444511
.. code-block:: css
445512

@@ -522,7 +589,8 @@ You can apply a style sheet to your templates by adding the following code to th
522589
Test the Application
523590
~~~~~~~~~~~~~~~~~~~~
524591

525-
After you complete the previous steps, you have a working application that uses MongoDB, Flask, and Celery to manage a newsletter platform.
592+
After you complete the previous steps, you have a working application that uses
593+
MongoDB, Flask, and Celery to manage a newsletter platform.
526594

527595
You can use the following steps to test your application:
528596

@@ -600,7 +668,10 @@ You can use the following steps to test your application:
600668
Next Steps
601669
~~~~~~~~~~
602670

603-
This application demonstrates how to integrate a Flask application with the Celery task queue to manage subscriber data, and send batch emails. You can further enhance this platform by integrating analytics, customizing email templates, and implementing automated responses.
671+
This application demonstrates how to integrate a Flask application with the
672+
Celery task queue to manage subscriber data, and send batch emails. You can
673+
further enhance this platform by integrating analytics, customizing email
674+
templates, and implementing automated responses.
604675

605676
More Resources
606677
--------------
@@ -612,4 +683,5 @@ For more information about the components used in this tutorial, see the followi
612683
- `Celery <https://docs.celeryq.dev/en/stable/>`__
613684
- `RabbitMQ <https://www.rabbitmq.com/docs/download>`__
614685

615-
To find support or to contribute to the MongoDB community, see the `MongoDB Developer Community <https://www.mongodb.com/community/>`__ page.
686+
To find support or to contribute to the MongoDB community, see the `MongoDB
687+
Developer Community <https://www.mongodb.com/community/>`__ page.

0 commit comments

Comments
 (0)