|
| 1 | +======================================================================== |
| 2 | +Building a Scalable Newsletter Platform with Flask, MongoDB, and Celery |
| 3 | +======================================================================== |
| 4 | + |
| 5 | +.. contents:: On this page |
| 6 | + :local: |
| 7 | + :backlinks: none |
| 8 | + :depth: 2 |
| 9 | + :class: singlecol |
| 10 | + |
| 11 | +.. facet:: |
| 12 | + :name: genre |
| 13 | + :values: tutorial |
| 14 | + |
| 15 | +.. meta:: |
| 16 | + :keywords: flask, celery, integration, code example |
| 17 | + |
| 18 | +Overview |
| 19 | +-------- |
| 20 | + |
| 21 | +In this tutorial, you can build a newsletter platform using Flask, MongoDB, and |
| 22 | +Celery. This application allows users to subscribe to newsletters, and |
| 23 | +administrators to manage and send batch emails asynchronously. |
| 24 | + |
| 25 | +Tutorial |
| 26 | +-------- |
| 27 | + |
| 28 | +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. |
| 29 | + |
| 30 | +Prerequisites |
| 31 | +~~~~~~~~~~~~~ |
| 32 | + |
| 33 | +Ensure you have the following components installed and set up before you start |
| 34 | +this tutorial: |
| 35 | + |
| 36 | +- :ref:`MongoDB <pymongo-get-started-download-and-install>`: For data storage. |
| 37 | +- `RabbitMQ <https://www.rabbitmq.com/docs/download>`__: As the message broker for Celery. |
| 38 | +- `Gmail <www.gmail.com>`__: For sending emails via SMTP. |
| 39 | +- `Python 3.8 or later <https://www.python.org/downloads/>`__ |
| 40 | + |
| 41 | +Set-up |
| 42 | +~~~~~~ |
| 43 | + |
| 44 | + |
| 45 | +.. procedure:: |
| 46 | + :style: connected |
| 47 | + |
| 48 | + .. step:: Install the required Python packages. |
| 49 | + |
| 50 | + Run the following ``pip`` command in your terminal: |
| 51 | + |
| 52 | + .. code-block:: bash |
| 53 | + |
| 54 | + pip install Flask Flask-Mail pymongo celery |
| 55 | + |
| 56 | + .. step:: Create directory structure. |
| 57 | + |
| 58 | + We recommend structuring your application to separate concerns, which can |
| 59 | + make the application modular and more maintainable. |
| 60 | + |
| 61 | + In your project directory, create the following directories and files: |
| 62 | + |
| 63 | + .. code-block:: none |
| 64 | + |
| 65 | + newsletter/ |
| 66 | + ├── app.py |
| 67 | + ├── config.py |
| 68 | + ├── routes.py |
| 69 | + ├── tasks.py |
| 70 | + ├── templates/ |
| 71 | + │ ├── admin.html |
| 72 | + │ └── subscribe.html |
| 73 | + ├── static/ |
| 74 | + └── styles.css |
| 75 | + |
| 76 | +Configure Your Application |
| 77 | +~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 78 | + |
| 79 | +In ``config.py``, define the necessary configurations by adding the following code: |
| 80 | + |
| 81 | +.. code-block:: python |
| 82 | + |
| 83 | + import os |
| 84 | + |
| 85 | + class Config: |
| 86 | + CELERY_BROKER_URL = 'amqp://guest:guest@localhost//' |
| 87 | + RESULT_BACKEND = 'mongodb://localhost:27017/celery_results' |
| 88 | + MAIL_SERVER = 'smtp.gmail.com' |
| 89 | + MAIL_PORT = 587 |
| 90 | + MAIL_USE_TLS = True |
| 91 | + MAIL_USERNAME = os.getenv('MAIL_USERNAME') |
| 92 | + MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') |
| 93 | + MAIL_DEFAULT_SENDER = os.getenv('MAIL_DEFAULT_SENDER') |
| 94 | + ALLOWED_IPS = ['127.0.0.1'] |
| 95 | + MONGO_URI = 'mongodb://localhost:27017/newsletter' |
| 96 | + |
| 97 | +Ensure that your Gmail credentials (``MAIL_USERNAME`` and ``MAIL_PASSWORD``) and |
| 98 | +default sender email (``MAIL_DEFAULT_SENDER``) are set in your environment variables. |
| 99 | + |
| 100 | +Initialize Flask, MongoDB, and Celery |
| 101 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 102 | + |
| 103 | +In ``app.py``, initialize Flask, MongoDB, and Celery by adding the following code: |
| 104 | + |
| 105 | +.. code-block:: python |
| 106 | + |
| 107 | + from flask import Flask |
| 108 | + from flask_mail import Mail |
| 109 | + from pymongo import MongoClient |
| 110 | + from celery import Celery |
| 111 | + from config import Config |
| 112 | + |
| 113 | + app = Flask(__name__) |
| 114 | + app.config.from_object(Config) |
| 115 | + |
| 116 | + mail = Mail(app) |
| 117 | + client = MongoClient(app.config['MONGO_URI']) |
| 118 | + db = client.get_database() |
| 119 | + |
| 120 | + celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) |
| 121 | + celery.conf.update(app.config) |
| 122 | + |
| 123 | + from routes import * |
| 124 | + from tasks import * |
| 125 | + |
| 126 | +Define Your Routes |
| 127 | +~~~~~~~~~~~~~~~~~~ |
| 128 | + |
| 129 | +In ``routes.py``, define the necessary routes by adding the following code: |
| 130 | + |
| 131 | +.. code-block:: python |
| 132 | + |
| 133 | + from flask import render_template, request, jsonify, abort |
| 134 | + from app import app, db |
| 135 | + from tasks import send_emails |
| 136 | + |
| 137 | + @app.before_request |
| 138 | + def limit_remote_addr(): |
| 139 | + if 'X-Forwarded-For' in request.headers: |
| 140 | + remote_addr = request.headers['X-Forwarded-For'].split(',')[0] |
| 141 | + else: |
| 142 | + remote_addr = request.remote_addr |
| 143 | + |
| 144 | + if request.endpoint == 'admin' and remote_addr not in app.config['ALLOWED_IPS']: |
| 145 | + abort(403) |
| 146 | + |
| 147 | + @app.route('/') |
| 148 | + def home(): |
| 149 | + return render_template('subscribe.html') |
| 150 | + |
| 151 | + @app.route('/admin') |
| 152 | + def admin(): |
| 153 | + return render_template('admin.html') |
| 154 | + |
| 155 | + @app.route('/subscribe', methods=['POST']) |
| 156 | + def subscribe(): |
| 157 | + email = request.form['email'] |
| 158 | + if db.users.find_one({'email': email}): |
| 159 | + |
| 160 | +After you complete these steps, you have a working application that |
| 161 | +uses MongoDB, Flask and Celery to manage a newsletter system. |
| 162 | + |
| 163 | +More Resources |
| 164 | +-------------- |
| 165 | + |
| 166 | +For more information about Flask and Celery integration, see the following |
| 167 | +resources: |
| 168 | + |
| 169 | +- `Flask <https://flask.palletsprojects.com>`__ |
| 170 | +- `Flask Mail <https://pypi.org/project/Flask-Mail/#files>`__ |
| 171 | +- `Celery <https://docs.celeryq.dev/en/stable/>`__ |
0 commit comments