|
| 1 | +.. _pymongo-fastapi: |
| 2 | +.. original URL: https://www.mongodb.com/developer/products/mongodb/python-flask-celery-newsletter/ |
| 3 | + |
| 4 | +====================================== |
| 5 | +Tutorial: Flask and Celery Integration |
| 6 | +====================================== |
| 7 | + |
| 8 | +.. contents:: On this page |
| 9 | + :local: |
| 10 | + :backlinks: none |
| 11 | + :depth: 2 |
| 12 | + :class: singlecol |
| 13 | + |
| 14 | +.. facet:: |
| 15 | + :name: genre |
| 16 | + :values: tutorial |
| 17 | + |
| 18 | +.. meta:: |
| 19 | + :keywords: flask, celery, integration, code example |
| 20 | + |
| 21 | +Overview |
| 22 | +-------- |
| 23 | + |
| 24 | +In this tutorial, you can build a newsletter platform using Flask, MongoDB, and |
| 25 | +Celery. This application allows users to subscribe to newsletters, and |
| 26 | +administrators to manage and send batch emails asynchronously. |
| 27 | + |
| 28 | +Tutorial |
| 29 | +-------- |
| 30 | + |
| 31 | +You can find the completed sample app for this tutorial in the :github:`Newsletter Platform with JavaScript, Flask, and MongoDB sample project </mercybassey/newsletter-javascript-flask-mongodb>` GitHub repository. |
| 32 | + |
| 33 | +Prerequisites |
| 34 | +~~~~~~~~~~~~~ |
| 35 | + |
| 36 | +Ensure you have the following components installed and set up before you start |
| 37 | +this tutorial: |
| 38 | + |
| 39 | +- :ref:`MongoDB <pymongo-get-started-create-deployment>` |
| 40 | +- `RabbitMQ <https://www.rabbitmq.com/docs/download>`__ (message broker for Celery) |
| 41 | +- `Gmail <www.gmail.com>`__ (to use as an SMTP) |
| 42 | +- `Python 3.8 or later <https://www.python.org/downloads/>`__ |
| 43 | + |
| 44 | +Set-up |
| 45 | +~~~~~~ |
| 46 | + |
| 47 | +.. procedure:: |
| 48 | + :style: connected |
| 49 | + |
| 50 | + .. step:: Install the required Python packages. |
| 51 | + |
| 52 | + Your application depends on the following libraries: |
| 53 | + |
| 54 | + - `Flask <https://flask.palletsprojects.com/en/stable/>`__ for handling the web server and routing |
| 55 | + - `Flask Mail <https://pypi.org/project/Flask-Mail/>`__ for sending emails from your application |
| 56 | + - :ref:`{+driver-long+} <pymongo-get-started-download-and-install>` |
| 57 | + - `Celery <https://docs.celeryq.dev/en/stable/>`__ to manage tasks, such |
| 58 | + as sending batch emails |
| 59 | + |
| 60 | + Run the following ``pip`` command in your terminal to install the dependencies: |
| 61 | + |
| 62 | + .. code-block:: bash |
| 63 | + |
| 64 | + pip install Flask Flask-Mail pymongo celery |
| 65 | + |
| 66 | + .. step:: Create directory structure. |
| 67 | + |
| 68 | + We recommend structuring your application to separate concerns, which can |
| 69 | + make the application modular and more maintainable. |
| 70 | + |
| 71 | + In your project directory, create the following structure: |
| 72 | + |
| 73 | + .. code-block:: none |
| 74 | + |
| 75 | + newsletter/ |
| 76 | + ├── app.py |
| 77 | + ├── config.py |
| 78 | + ├── routes.py |
| 79 | + ├── tasks.py |
| 80 | + ├── templates/ |
| 81 | + │ ├── admin.html |
| 82 | + │ └── subscribe.html |
| 83 | + ├── static/ |
| 84 | + └── styles.css |
| 85 | + |
| 86 | +Configure Your Application |
| 87 | +~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 88 | + |
| 89 | +Define the necessary configurations by adding the following code to your |
| 90 | +``config.py`` file: |
| 91 | + |
| 92 | +.. code-block:: python |
| 93 | + |
| 94 | + import os |
| 95 | + |
| 96 | + class Config: |
| 97 | + CELERY_BROKER_URL = 'amqp://guest:guest@localhost//' |
| 98 | + RESULT_BACKEND = 'mongodb://localhost:27017/celery_results' |
| 99 | + MAIL_SERVER = 'smtp.gmail.com' |
| 100 | + MAIL_PORT = 587 |
| 101 | + MAIL_USE_TLS = True |
| 102 | + MAIL_USERNAME = os.getenv('MAIL_USERNAME') |
| 103 | + MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') |
| 104 | + MAIL_DEFAULT_SENDER = os.getenv('MAIL_DEFAULT_SENDER') |
| 105 | + ALLOWED_IPS = ['127.0.0.1'] |
| 106 | + MONGO_URI = 'mongodb://localhost:27017/newsletter' |
| 107 | + |
| 108 | +Ensure that your Gmail credentials (``MAIL_USERNAME`` and ``MAIL_PASSWORD``) and |
| 109 | +default sender email (``MAIL_DEFAULT_SENDER``) are set in your environment variables. |
| 110 | + |
| 111 | +Initialize Flask, MongoDB, and Celery |
| 112 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 113 | + |
| 114 | +Initialize Flask, MongoDB, and Celery by adding the following code to your |
| 115 | +``app.py`` file: |
| 116 | + |
| 117 | +.. code-block:: python |
| 118 | + |
| 119 | + from flask import Flask |
| 120 | + from flask_mail import Mail |
| 121 | + from pymongo import MongoClient |
| 122 | + from celery import Celery |
| 123 | + from config import Config |
| 124 | + |
| 125 | + app = Flask(__name__) |
| 126 | + app.config.from_object(Config) |
| 127 | + |
| 128 | + mail = Mail(app) |
| 129 | + client = MongoClient(app.config['MONGO_URI']) |
| 130 | + db = client.get_database() |
| 131 | + |
| 132 | + celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) |
| 133 | + celery.conf.update(app.config) |
| 134 | + |
| 135 | + from routes import * |
| 136 | + from tasks import * |
| 137 | + |
| 138 | +Ensure that your connection string (``MONGOD_URI``) and broker url |
| 139 | +(``CELERY_BROKER_URL``) are set in your environment variables. For more in |
| 140 | +formation see the :ref:`Create a Connection String |
| 141 | +<pymongo-get-started-connection-string>` section of this guide and the `Broker Settings |
| 142 | +<https://docs.celeryq.dev/en/stable/userguide/configuration.html#broker-settings>`__ |
| 143 | +section of the Celery documentation. |
| 144 | + |
| 145 | +Define Your Routes |
| 146 | +~~~~~~~~~~~~~~~~~~ |
| 147 | + |
| 148 | +Define the necessary routes by adding the following code to your ``routes.py`` file: |
| 149 | + |
| 150 | +.. code-block:: python |
| 151 | + |
| 152 | + from flask import render_template, request, jsonify, abort |
| 153 | + from app import app, db |
| 154 | + from tasks import send_emails |
| 155 | + |
| 156 | + @app.before_request |
| 157 | + def limit_remote_addr(): |
| 158 | + if 'X-Forwarded-For' in request.headers: |
| 159 | + remote_addr = request.headers['X-Forwarded-For'].split(',')[0] |
| 160 | + else: |
| 161 | + remote_addr = request.remote_addr |
| 162 | + |
| 163 | + if request.endpoint == 'admin' and remote_addr not in app.config['ALLOWED_IPS']: |
| 164 | + abort(403) |
| 165 | + |
| 166 | + @app.route('/') |
| 167 | + def home(): |
| 168 | + return render_template('subscribe.html') |
| 169 | + |
| 170 | + @app.route('/admin') |
| 171 | + def admin(): |
| 172 | + return render_template('admin.html') |
| 173 | + |
| 174 | + @app.route('/subscribe', methods=['POST']) |
| 175 | + def subscribe(): |
| 176 | + email = request.form['email'] |
| 177 | + if db.users.find_one({'email': email}): |
| 178 | + |
| 179 | +After you complete these steps, you will have a working application that |
| 180 | +uses MongoDB, Flask and Celery to manage a newsletter platform. |
| 181 | + |
| 182 | +Testing the Platform |
| 183 | +~~~~~~~~~~~~~~~~~~~~ |
| 184 | + |
| 185 | +To test your application, run the following ``flask`` command in the terminal: |
| 186 | + |
| 187 | +.. procedure:: |
| 188 | + :style: connected |
| 189 | + |
| 190 | + .. step:: Start Your Application |
| 191 | + |
| 192 | + .. code-block:: bash |
| 193 | + |
| 194 | + flask --app app run |
| 195 | + |
| 196 | + In another terminal, start the celery worker: |
| 197 | + |
| 198 | + .. code-block:: bash |
| 199 | + |
| 200 | + celery -A app.celery worker --loglevel=info |
| 201 | + |
| 202 | + .. step:: Create a Subscriber |
| 203 | + |
| 204 | + Navigate to ``localhost:5000`` in your browser to open the |
| 205 | + :guilabel:`Subscribe to our Newsletter` page. The following image shows |
| 206 | + the subscriber webpage: |
| 207 | + |
| 208 | + .. image:: /includes/integrations/celery-subscriber-page.png |
| 209 | + :alt: Screenshot of browser and subscriber page |
| 210 | + |
| 211 | + Enter the subscriber information and click :guilabel:`Subscribe`. |
| 212 | + |
| 213 | + To confirm that you created a new subscriber, run the following code in |
| 214 | + your terminal to open a MongoDB Shell instance and view your collections: |
| 215 | + |
| 216 | + .. code-block:: shell |
| 217 | + |
| 218 | + mongosh |
| 219 | + show dbs |
| 220 | + use newsletter |
| 221 | + show collections |
| 222 | + |
| 223 | + .. step:: Dispatch a Newsletter |
| 224 | + |
| 225 | + Navigate to ``localhost:5000/admin`` in your browser to open the |
| 226 | + :guilabel:`Send Newsletter` page. The following image shows the admin |
| 227 | + webpage: |
| 228 | + |
| 229 | + .. image:: /includes/integrations/celery-admin-page.png |
| 230 | + :alt: Screenshot of browser and admin |
| 231 | + |
| 232 | + Enter the newsletter details and click :guilabel:`Send`. |
| 233 | + |
| 234 | + Your Celery worker log will display an ``Email sent`` log entry, as |
| 235 | + shown in the following image: |
| 236 | + |
| 237 | + .. code-block:: bash |
| 238 | + |
| 239 | + [2024-06-06 13:34:37,304: WARNING/ForkPoolWorker-4] Email sent |
| 240 | + [2024-06-06 13:34:37,305: INFO/ForkPoolWorker-4] Task tasks.send_emails[b119bb9e-b2ef-4c85-b048-ca96e0e60ae1] succeeded in 17.155154566993588s: {'result': 'All emails sent'} |
| 241 | + |
| 242 | + You can also see your newsletter deliverable by running the following |
| 243 | + command in your MongoDB Shell to review your collections: |
| 244 | + |
| 245 | + .. code-block:: shell |
| 246 | + |
| 247 | + newsletter> show collections |
| 248 | + deliveries |
| 249 | + subscribers |
| 250 | + newsletter> |
| 251 | + |
| 252 | + .. step:: Review Your Sent Newsletter |
| 253 | + |
| 254 | + Run the following commands in your MongoDB Shell to your previously sent |
| 255 | + newsletters, also called ``deliveries``: |
| 256 | + |
| 257 | + .. code-block:: shell |
| 258 | + |
| 259 | + db.deliveries.find().pretty() |
| 260 | + |
| 261 | +Next Steps |
| 262 | +~~~~~~~~~~ |
| 263 | + |
| 264 | +This application demonstrates how to handle asynchronous tasks efficiently, |
| 265 | +manage subscriber data, and send batch emails. You can further enhance this |
| 266 | +platform by integrating analytics, customizing email templates, and implementing |
| 267 | +automated responses. |
| 268 | + |
| 269 | +More Resources |
| 270 | +-------------- |
| 271 | + |
| 272 | +For more information about to components used in this tutorial, see the following |
| 273 | +resources: |
| 274 | + |
| 275 | +- `Flask <https://flask.palletsprojects.com>`__ |
| 276 | +- `Flask Mail <https://pypi.org/project/Flask-Mail/#files>`__ |
| 277 | +- `Celery <https://docs.celeryq.dev/en/stable/>`__ |
| 278 | +- :mdb-shell:`MongoDB Shell <>` |
| 279 | + |
| 280 | +For support or to contribute to the MongoDB Community, see the `MongoDB Developer Community <https://www.mongodb.com/community/>`__. |
0 commit comments