<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fahim Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Fahim Ahmed on Medium]]></description>
        <link>https://medium.com/@fahimad?source=rss-e426a1e4223d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fIBe7oiC48s_Dmu4</url>
            <title>Stories by Fahim Ahmed on Medium</title>
            <link>https://medium.com/@fahimad?source=rss-e426a1e4223d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:42:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fahimad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Gunicorn vs Daphne vs Uvicorn: Which Should You Use for Django?]]></title>
            <link>https://medium.com/@fahimad/gunicorn-vs-daphne-vs-uvicorn-which-should-you-use-for-django-31afc0562ec7?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31afc0562ec7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 04:11:01 GMT</pubDate>
            <atom:updated>2026-07-17T04:11:01.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azhIKWo-MTToRdugxU8FJA.png" /></figure><blockquote><em>Choosing the right application server can significantly impact your Django application’s performance, scalability, and support for modern features like asynchronous views and WebSockets. In this article, we’ll compare </em><strong><em>Gunicorn</em></strong><em>, </em><strong><em>Daphne</em></strong><em>, and </em><strong><em>Uvicorn</em></strong><em>, explain their differences, and help you choose the right one for your next Django project.</em></blockquote><h3>Introduction</h3><p>When you’re ready to deploy a Django application, one of the first questions you’ll encounter is:</p><p><strong>Should I use Gunicorn, Daphne, or Uvicorn?</strong></p><p>If you’ve searched online, you’ve probably seen different recommendations:</p><ul><li>Some tutorials use <strong>Gunicorn</strong>.</li><li>Others recommend <strong>Uvicorn</strong>.</li><li>If you’re using Django Channels, you’ll often see <strong>Daphne</strong>.</li></ul><p>So which one is actually the right choice?</p><p>The answer depends on <strong>how your application works</strong>.</p><p>In this article, we’ll explore how each server works, compare their strengths and weaknesses, and discuss real-world production scenarios.</p><h3>Why Not Use runserver?</h3><p>Every Django developer starts with:</p><pre>python manage.py runserver</pre><p>This development server is convenient, but it is <strong>not designed for production</strong>.</p><p>The Django development server:</p><ul><li>Handles only basic development workloads.</li><li>Lacks production-level performance optimizations.</li><li>Doesn’t efficiently manage concurrent users.</li><li>Should never be exposed directly to the Internet.</li></ul><p>Instead, production deployments use dedicated application servers such as <strong>Gunicorn</strong>, <strong>Daphne</strong>, or <strong>Uvicorn</strong>.</p><h3>Understanding WSGI and ASGI</h3><p>Before comparing the servers, it’s important to understand two interfaces used by Python web applications.</p><h3>WSGI (Web Server Gateway Interface)</h3><p>WSGI has been the standard interface for Python web applications for many years.</p><p>A typical request flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2ILcAZYdaT-RATiL9A_Ag.png" /></figure><p>WSGI works exceptionally well for traditional request-response applications.</p><p>However, it was designed before features like WebSockets and asynchronous programming became common.</p><h3>ASGI (Asynchronous Server Gateway Interface)</h3><p>ASGI is the successor to WSGI.</p><p>It supports:</p><ul><li>Asynchronous views</li><li>WebSockets</li><li>Long-lived connections</li><li>HTTP streaming</li><li>Background communication</li></ul><p>The request flow becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bazz_Rhal-eKKdF6xyZm2w.png" /></figure><p>Since Django 3.0, ASGI has become a first-class citizen, allowing developers to build modern asynchronous applications.</p><h3>Gunicorn</h3><p>Gunicorn is probably the most widely used application server in the Django ecosystem.</p><p>It implements the <strong>WSGI</strong> specification and is known for its stability and simplicity.</p><p>Example:</p><pre>gunicorn config.wsgi:application</pre><h3>Advantages</h3><ul><li>Mature and battle-tested</li><li>Excellent performance for traditional Django applications</li><li>Simple configuration</li><li>Large community</li><li>Well documented</li><li>Works perfectly with Nginx</li></ul><h3>Limitations</h3><ul><li>No native WebSocket support</li><li>Doesn’t execute asynchronous Django views as true async</li><li>Designed primarily for synchronous workloads</li></ul><p>Gunicorn is an excellent choice for:</p><ul><li>Django REST APIs</li><li>Admin panels</li><li>E-commerce websites</li><li>CMS applications</li><li>Most business applications</li></ul><h3>Daphne</h3><p>Daphne is the official ASGI server developed by the Django Channels team.</p><p>It was specifically designed to support asynchronous communication in Django.</p><p>Example:</p><pre>daphne config.asgi:application</pre><p>Unlike Gunicorn, Daphne understands WebSockets and long-lived connections.</p><h3>Advantages</h3><ul><li>Native ASGI support</li><li>Built specifically for Django</li><li>Excellent integration with Django Channels</li><li>Supports HTTP and WebSockets</li></ul><h3>Limitations</h3><ul><li>Slightly slower than Uvicorn in many benchmarks</li><li>Smaller ecosystem</li><li>Primarily targeted at Django projects</li></ul><p>Daphne is commonly used when building:</p><ul><li>Chat applications</li><li>Live notifications</li><li>Online presence indicators</li><li>Real-time dashboards</li></ul><h3>Uvicorn</h3><p>Uvicorn is a lightweight ASGI server built for speed.</p><p>It is powered by <strong>uvloop</strong> and <strong>httptools</strong>, making it one of the fastest Python application servers available.</p><p>Example:</p><pre>uvicorn config.asgi:application</pre><p>Although Uvicorn is popular in the FastAPI ecosystem, it also works exceptionally well with Django’s ASGI interface.</p><h3>Advantages</h3><ul><li>Very fast</li><li>Native async support</li><li>Lightweight</li><li>Excellent performance</li><li>Supports WebSockets</li></ul><h3>Limitations</h3><ul><li>Requires an ASGI application</li><li>Less commonly used than Gunicorn in traditional Django deployments</li></ul><p>Uvicorn is an excellent choice for:</p><ul><li>Async Django applications</li><li>FastAPI</li><li>High-concurrency APIs</li><li>Streaming applications</li></ul><h3>Feature Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8Z1tI4XOXNpHnVZoyccRw.png" /></figure><h3>Which Server Should You Choose?</h3><h3>Traditional Django Website</h3><p>Examples:</p><ul><li>Company website</li><li>Blog</li><li>Admin dashboard</li><li>CRM</li><li>ERP</li><li>E-commerce</li></ul><p><strong>Recommendation:</strong> Gunicorn</p><p>Traditional request-response applications rarely need asynchronous capabilities. Gunicorn remains the simplest and most reliable option.</p><h3>Django REST Framework APIs</h3><p>Most REST APIs perform database operations and return JSON responses.</p><p>Unless your API relies heavily on asynchronous I/O, Gunicorn is usually sufficient.</p><p><strong>Recommendation:</strong> Gunicorn</p><h3>Django Channels</h3><p>If your project uses:</p><ul><li>Chat</li><li>Live notifications</li><li>Online users</li><li>Real-time messaging</li></ul><p>You’ll need ASGI.</p><p><strong>Recommendation:</strong> Daphne</p><h3>Async Django</h3><p>Suppose your application makes multiple external API requests, performs asynchronous file operations, or handles long-running network tasks.</p><p>Uvicorn allows Django’s async views to operate efficiently.</p><p><strong>Recommendation:</strong> Uvicorn</p><h3>FastAPI Projects</h3><p>FastAPI is built entirely around ASGI.</p><p><strong>Recommendation:</strong> Uvicorn</p><h3>Typical Production Architectures</h3><h3>Gunicorn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SxBzZNhfCBrbp0Dwsirig.png" /></figure><p>This is one of the most common production architectures for Django applications.</p><h3>Daphne</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1buJKTueSriuweDMsGGng.png" /></figure><p>Redis acts as the channel layer, enabling communication between different processes.</p><h3>Uvicorn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tu2iW4tNxN3VypUeGcPWfg.png" /></figure><p>This architecture is well suited for applications that benefit from asynchronous processing.</p><h3>My Recommendation</h3><p>After deploying numerous Django applications in production, here’s the approach I generally follow:</p><ul><li><strong>Gunicorn</strong> for traditional Django applications and REST APIs.</li><li><strong>Daphne</strong> when the project requires Django Channels and WebSockets.</li><li><strong>Uvicorn</strong> when the application makes extensive use of asynchronous views or when working with ASGI-first frameworks like FastAPI.</li></ul><p>Many developers assume they should always use ASGI because it’s newer, but that’s not necessarily true. If your application is primarily synchronous, Gunicorn remains an excellent and reliable choice.</p><p>The best server is the one that matches your application’s architecture — not simply the newest option.</p><h3>Final Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbZjpsABHgMWGnZS8c_4yg.png" /></figure><p>Choosing between Gunicorn, Daphne, and Uvicorn isn’t about which server is “better” — it’s about selecting the right tool for your application’s requirements.</p><p>If you’re building a standard Django website or REST API, <strong>Gunicorn</strong> remains the most stable and widely adopted solution.</p><p>If your application requires <strong>WebSockets</strong> or <strong>real-time communication</strong>, <strong>Daphne</strong> integrates seamlessly with Django Channels.</p><p>If you’re embracing <strong>asynchronous programming</strong> or building high-concurrency services, <strong>Uvicorn</strong> offers excellent performance and modern ASGI support.</p><p>Understanding these differences will help you design a deployment architecture that is both scalable and maintainable as your application grows.</p><p><strong>If you enjoyed this article, follow me for more practical Django, Python, and Cloud Infrastructure tutorials.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31afc0562ec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Django for Production: A Practical Guide with Docker & Docker Compose]]></title>
            <link>https://medium.com/@fahimad/dockerizing-django-for-production-a-practical-guide-with-docker-docker-compose-1d16866adb20?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d16866adb20</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 04:11:01 GMT</pubDate>
            <atom:updated>2026-07-14T04:11:01.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7mePuNLXcS6V3V7gPz-cA.png" /></figure><blockquote><strong><em>Stop saying “it works on my machine.”</em></strong><em> Learn how to package your Django application into portable containers that run consistently across development, staging, and production.</em></blockquote><h3>Introduction</h3><p>Deploying a Django application directly on a server can quickly become difficult to manage. Different Python versions, missing system packages, inconsistent dependencies, and environment-specific configurations often lead to deployment headaches.</p><p>Docker solves these problems by packaging your application and everything it needs into lightweight, portable containers. Whether you’re deploying to an AWS EC2 instance, a VPS, or your local development environment, the application behaves exactly the same.</p><p>In this article, we’ll build a production-ready Docker setup for Django using:</p><ul><li>Docker</li><li>Docker Compose</li><li>PostgreSQL</li><li>Gunicorn</li><li>Environment variables</li><li>Multi-stage project organization</li></ul><p>By the end, you’ll have a clean foundation that can later be extended with Nginx, Redis, Celery, and CI/CD pipelines.</p><h3>Why Docker?</h3><p>Without Docker, every deployment requires configuring the server manually.</p><p>You may need to:</p><ul><li>Install the correct Python version</li><li>Install PostgreSQL client libraries</li><li>Create virtual environments</li><li>Install dependencies</li><li>Configure environment variables</li><li>Resolve package conflicts</li></ul><p>Even small differences between development and production environments can introduce unexpected bugs.</p><p>Docker eliminates these inconsistencies by packaging your application into an isolated container.</p><p>Some key benefits include:</p><ul><li>Consistent environments</li><li>Easy onboarding for new developers</li><li>Reproducible deployments</li><li>Simplified dependency management</li><li>Easier CI/CD integration</li><li>Better scalability</li></ul><p>Instead of configuring servers repeatedly, you simply build an image and run it anywhere Docker is available.</p><h3>Project Structure</h3><p>Let’s start with a clean Django project.</p><pre>myproject/<br>│<br>├── app/<br>│   ├── manage.py<br>│   ├── requirements.txt<br>│   ├── config/<br>│   └── ...<br>│<br>├── Dockerfile<br>├── docker-compose.yml<br>├── .dockerignore<br>├── .env<br>└── README.md</pre><p>Keeping Docker-related files in the project root makes deployments much easier.</p><h3>Installing Docker</h3><p>Verify that Docker is installed.</p><pre>docker --version</pre><p>Verify Docker Compose.</p><pre>docker compose version</pre><p>If both commands return a version number, you’re ready to continue.</p><h3>Creating the Dockerfile</h3><p>The Dockerfile defines how Docker builds your application image.</p><pre>FROM python:3.12-slim<br><br>ENV PYTHONDONTWRITEBYTECODE=1<br>ENV PYTHONUNBUFFERED=1<br><br>WORKDIR /app<br><br>COPY app/requirements.txt .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY app .<br><br>EXPOSE 8000<br><br>CMD [&quot;gunicorn&quot;, &quot;config.wsgi:application&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;]</pre><p>Although this file is only a few lines long, each instruction has an important role.</p><h3>Choosing the Base Image</h3><pre>FROM python:3.12-slim</pre><p>Instead of installing Python manually, we start from the official Python image.</p><p>The slim variant keeps the final image significantly smaller than the standard Python image while including everything required to run most Django applications.</p><p>Smaller images mean:</p><ul><li>Faster downloads</li><li>Faster deployments</li><li>Reduced storage costs</li></ul><h3>Prevent Python Cache Files</h3><pre>ENV PYTHONDONTWRITEBYTECODE=1</pre><p>Python normally generates .pyc files.</p><p>Inside Docker containers, these files usually provide little benefit and unnecessarily increase image size.</p><p>Disabling them keeps the container cleaner.</p><h3>Disable Output Buffering</h3><pre>ENV PYTHONUNBUFFERED=1</pre><p>Without this setting, log messages may be buffered before appearing in Docker logs.</p><p>Enabling unbuffered output makes debugging much easier because logs appear immediately.</p><h3>Define the Working Directory</h3><pre>WORKDIR /app</pre><p>Every subsequent command executes inside this directory.</p><p>This keeps file paths consistent throughout the build process.</p><h3>Install Dependencies Efficiently</h3><pre>COPY app/requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt</pre><p>Notice that we copy only requirements.txt before copying the rest of the project.</p><p>This is intentional.</p><p>Docker builds images in layers.</p><p>If your application code changes but requirements.txt remains the same, Docker reuses the cached dependency layer instead of reinstalling every package.</p><p>This can reduce build times dramatically during development.</p><h3>Copy the Application</h3><pre>COPY app .</pre><p>Once dependencies are installed, copy the project source code into the container.</p><h3>Expose the Application Port</h3><pre>EXPOSE 8000</pre><p>This documents that the container listens on port <strong>8000</strong>.</p><p>It doesn’t publish the port by itself but helps other developers understand how the container should be run.</p><h3>Start Django with Gunicorn</h3><pre>CMD [&quot;gunicorn&quot;, &quot;config.wsgi:application&quot;, &quot;--bind&quot;, &quot;0.0.0.0:8000&quot;]</pre><p>Although Django’s development server is excellent during development, it should never be used in production.</p><p>Gunicorn is a production-grade WSGI server designed to handle multiple concurrent requests efficiently.</p><p>In later articles, we’ll place <strong>Nginx</strong> in front of Gunicorn to improve performance and serve static files.</p><h3>Ignoring Unnecessary Files</h3><p>Create a .dockerignore file.</p><pre>.git<br>.gitignore<br>venv<br>.env<br>__pycache__<br>*.pyc<br>*.sqlite3<br>media<br>staticfiles</pre><p>Just like .gitignore, this file prevents unnecessary files from being copied into the Docker image.</p><p>Benefits include:</p><ul><li>Smaller image size</li><li>Faster builds</li><li>Better security</li><li>Cleaner deployments</li></ul><h3>Building the Docker Image</h3><p>From the project root, run:</p><pre>docker build -t my-django-app .</pre><p>Docker will:</p><ol><li>Download the Python base image</li><li>Install dependencies</li><li>Copy your project</li><li>Create a reusable image</li></ol><p>If everything succeeds, you should see a message indicating the image was built successfully.</p><p>In the next part, we’ll use Docker Compose to orchestrate Django and PostgreSQL, configure environment variables, and prepare the application for a real production deployment.</p><h3>Running Multiple Services with Docker Compose</h3><p>A production Django application rarely runs as a single container. At a minimum, you’ll typically have:</p><ul><li>Django application</li><li>PostgreSQL database</li></ul><p>As your application grows, you might also add:</p><ul><li>Redis</li><li>Celery Worker</li><li>Celery Beat</li><li>Nginx</li><li>Flower</li></ul><p>Managing these containers individually would quickly become cumbersome. Docker Compose lets you define your entire application stack in a single configuration file.</p><p>Create a docker-compose.yml file in the project root.</p><pre>version: &quot;3.9&quot;<br>services:<br>  web:<br>    build: .<br>    container_name: django_app<br>    command: &gt;<br>      sh -c &quot;<br>      python manage.py migrate &amp;&amp;<br>      python manage.py collectstatic --noinput &amp;&amp;<br>      gunicorn config.wsgi:application --bind 0.0.0.0:8000&quot;<br>    volumes:<br>      - ./app:/app<br>    ports:<br>      - &quot;8000:8000&quot;<br>    env_file:<br>      - .env<br>    depends_on:<br>      - db<br>  db:<br>    image: postgres:16<br>    container_name: postgres_db<br>    restart: always<br>    environment:<br>      POSTGRES_DB: django_db<br>      POSTGRES_USER: django<br>      POSTGRES_PASSWORD: password<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>volumes:<br>  postgres_data:</pre><p>This configuration creates two services:</p><ul><li>web for the Django application</li><li>db for PostgreSQL</li></ul><p>Docker Compose automatically creates a private network, allowing the containers to communicate securely.</p><h3>Managing Environment Variables</h3><p>Never hardcode sensitive information such as:</p><ul><li>Secret keys</li><li>Database passwords</li><li>API tokens</li><li>Email credentials</li></ul><p>Instead, create a .env file.</p><pre>SECRET_KEY=your-secret-key<br>DEBUG=False<br>DB_NAME=django_db<br>DB_USER=django<br>DB_PASSWORD=password<br>DB_HOST=db<br>DB_PORT=5432</pre><p>Notice that the database host is simply db.</p><p>Docker Compose automatically resolves service names as hostnames, so you don’t need to know the container’s IP address.</p><h3>Reading Environment Variables in Django</h3><p>Install python-dotenv.</p><pre>pip install python-dotenv</pre><p>Then update settings.py.</p><pre>from pathlib import Path<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br><br>SECRET_KEY = os.getenv(&quot;SECRET_KEY&quot;)<br><br>DEBUG = os.getenv(&quot;DEBUG&quot;) == &quot;True&quot;<br><br>DATABASES = {<br>    &quot;default&quot;: {<br>        &quot;ENGINE&quot;: &quot;django.db.backends.postgresql&quot;,<br>        &quot;NAME&quot;: os.getenv(&quot;DB_NAME&quot;),<br>        &quot;USER&quot;: os.getenv(&quot;DB_USER&quot;),<br>        &quot;PASSWORD&quot;: os.getenv(&quot;DB_PASSWORD&quot;),<br>        &quot;HOST&quot;: os.getenv(&quot;DB_HOST&quot;),<br>        &quot;PORT&quot;: os.getenv(&quot;DB_PORT&quot;),<br>    }<br>}</pre><p>Your application can now run in different environments without modifying the source code. Only the .env file changes.</p><h3>Running Database Migrations Automatically</h3><p>A newly deployed container usually starts with an empty database.</p><p>Instead of manually running migrations after every deployment, Docker can execute them automatically during startup.</p><p>Notice the command section in docker-compose.yml.</p><pre>command: &gt;<br>  sh -c &quot;<br>  python manage.py migrate &amp;&amp;<br>  python manage.py collectstatic --noinput &amp;&amp;<br>  gunicorn config.wsgi:application --bind 0.0.0.0:8000&quot;</pre><p>This ensures:</p><ol><li>Database migrations are applied.</li><li>Static files are collected.</li><li>Gunicorn starts only after the previous steps succeed.</li></ol><p>For larger production environments, many teams execute migrations as a separate deployment step to avoid race conditions when multiple application instances start simultaneously.</p><h3>Persisting PostgreSQL Data</h3><p>Containers are ephemeral. If a database container is removed, all data inside it disappears unless a volume is used.</p><pre>volumes:<br>  postgres_data:</pre><pre>volumes:<br>  - postgres_data:/var/lib/postgresql/data</pre><p>Docker stores the database files outside the container, ensuring your data survives restarts and upgrades.</p><h3>Starting the Application</h3><p>Build and start the services.</p><pre>docker compose up --build</pre><p>To run them in the background:</p><pre>docker compose up -d</pre><p>Useful commands during development:</p><p>View logs:</p><pre>docker compose logs -f</pre><p>Stop all containers:</p><pre>docker compose down</pre><p>Rebuild after changes:</p><pre>docker compose up --build</pre><p>Open a shell inside the Django container:</p><pre>docker compose exec web bash</pre><p>Run Django management commands:</p><pre>docker compose exec web python manage.py createsuperuser</pre><p>These commands eliminate the need to install Python or Django directly on your local machine.</p><h3>Production Best Practices</h3><p>A Dockerized application is not automatically production-ready. Keep these practices in mind:</p><h3>Use Gunicorn Instead of runserver</h3><p>The Django development server is intended only for development and testing.</p><p>Use Gunicorn (or Daphne for ASGI applications) in production.</p><h3>Keep Images Small</h3><p>Choose lightweight base images such as:</p><pre>python:3.12-slim</pre><p>Avoid installing unnecessary packages that increase build time and image size.</p><h3>Keep Secrets Out of Images</h3><p>Never copy your .env file into the Docker image.</p><p>Environment-specific configuration should be injected when the container starts.</p><h3>Use Named Volumes</h3><p>Persist important data such as PostgreSQL files and uploaded media using Docker volumes.</p><h3>Pin Dependency Versions</h3><p>Avoid:</p><pre>Django</pre><p>Prefer:</p><pre>Django==5.2.4</pre><p>Pinned versions make deployments reproducible and reduce the risk of unexpected breakages.</p><h3>Separate Development and Production Configurations</h3><p>Many teams maintain:</p><pre>docker-compose.yml<br>docker-compose.dev.yml<br>docker-compose.prod.yml</pre><p>This allows different settings, volumes, ports, and debugging options without modifying the application code.</p><h3>What’s Next?</h3><p>Docker gives us a portable, repeatable deployment process, but there is still room for improvement.</p><p>In a typical production environment, you’ll place <strong>Nginx</strong> in front of Gunicorn to:</p><ul><li>Serve static files efficiently</li><li>Handle HTTPS termination</li><li>Compress responses</li><li>Cache static assets</li><li>Act as a reverse proxy</li></ul><p>You’ll also likely introduce:</p><ul><li>Redis for caching and task queues</li><li>Celery for background jobs</li><li>Automated CI/CD pipelines</li><li>Monitoring and logging tools</li></ul><p>These components build on the Docker foundation you’ve created here.</p><p>Docker has become a standard tool for modern Django deployments because it removes much of the friction between development and production.</p><p>By containerizing your application, you gain:</p><ul><li>Consistent environments</li><li>Faster deployments</li><li>Easier onboarding</li><li>Better scalability</li><li>Simpler dependency management</li></ul><p>Combined with Docker Compose, you can manage your application’s services as a cohesive stack rather than a collection of manually configured processes.</p><p>Once you’re comfortable with this setup, the next step is adding Nginx and deploying the stack to a cloud server such as AWS EC2, DigitalOcean, or Azure Virtual Machines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d16866adb20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Per-Object Permissions in Django with django-guardian]]></title>
            <link>https://medium.com/@fahimad/managing-per-object-permissions-in-django-with-django-guardian-3f21befb3b8d?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f21befb3b8d</guid>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 17:49:49 GMT</pubDate>
            <atom:updated>2026-07-10T17:49:49.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gL2HEIxo3pBuu0wVWOif0g.png" /></figure><p>In many Django applications, global permissions like “can view project” or “can delete task” aren’t enough. What if you need <strong>fine-grained, object-level control</strong>? For example:</p><blockquote><em>“Only the assigned reviewer should be able to approve a document.”</em></blockquote><p>Django’s built-in permission system doesn’t support per-object permissions out of the box, but that’s where <a href="https://github.com/django-guardian/django-guardian">django-guardian</a> shines.</p><p>This article walks you through a real-world setup for <strong>object-level permissions</strong>, covering:</p><ul><li>Installing and configuring django-guardian</li><li>Assigning per-object permissions</li><li>Checking them in views</li><li>Admin integration</li><li>Use cases and pitfalls</li></ul><h3>What Is Per-Object Permission?</h3><p>Instead of just asking:</p><blockquote><em>“Can this user edit </em>any<em> project?”</em></blockquote><p>You can ask:</p><blockquote><em>“Can this user edit </em>this specific project<em>?”</em></blockquote><p>This is useful for:</p><ul><li>Multi-user task apps (assignee access only)</li><li>Review/approval systems</li><li>Project management (team member visibility)</li><li>Document sharing with ACLs (Access Control Lists)</li></ul><h3>Step 1: Install &amp; Configure django-guardian</h3><pre>pip install django-guardian</pre><p>Then update your settings:</p><pre># settings.py<br><br>INSTALLED_APPS = [<br>    ...<br>    &#39;guardian&#39;,<br>]<br>AUTHENTICATION_BACKENDS = (<br>    &#39;django.contrib.auth.backends.ModelBackend&#39;,  # default<br>    &#39;guardian.backends.ObjectPermissionBackend&#39;,<br>)<br>ANONYMOUS_USER_ID = -1  # required for anonymous object-level access (optional)</pre><h3>Step 2: Model Setup</h3><p>Let’s say you have a Project model:</p><pre>from django.db import models<br>from django.contrib.auth.models import User<br><br><br>class Project(models.Model):<br>    name = models.CharField(max_length=255)<br>    owner = models.ForeignKey(User, on_delete=models.CASCADE)</pre><p>To support object-level permissions, declare:</p><pre>from guardian.mixins import GuardianUserMixin<br>from guardian.shortcuts import assign_perm<br><br><br>class Project(models.Model):<br>    ...<br>    class Meta:<br>        permissions = [<br>            (&quot;view_project&quot;, &quot;Can view project&quot;),<br>            (&quot;edit_project&quot;, &quot;Can edit project&quot;),<br>        ]</pre><h3>Step 3: Assign Object Permissions</h3><p>Now let’s assign a permission to a specific user:</p><pre>from guardian.shortcuts import assign_perm<br><br>assign_perm(&quot;view_project&quot;, user, project)     # allow viewing this project<br>assign_perm(&quot;edit_project&quot;, user, project)     # allow editing this project</pre><p>You can also assign to groups:</p><pre>assign_perm(&quot;edit_project&quot;, group, project)</pre><p>Revoke with:</p><pre>from guardian.shortcuts import remove_perm<br><br>remove_perm(&quot;edit_project&quot;, user, project)</pre><h3>Step 4: Check Object Permissions in Views</h3><p>Use user.has_perm() with the object:</p><pre>def view_project(request, project_id):<br>    project = get_object_or_404(Project, id=project_id)<br>    if not request.user.has_perm(&quot;view_project&quot;, project):<br>        return HttpResponseForbidden(&quot;Access denied.&quot;)</pre><p>In class-based views, override get_object() or dispatch():</p><pre>class ProjectDetailView(DetailView):<br>    model = Project<br><br>    def dispatch(self, request, *args, **kwargs):<br>        obj = self.get_object()<br>        if not request.user.has_perm(&quot;view_project&quot;, obj):<br>            return HttpResponseForbidden(&quot;Access denied.&quot;)<br>        return super().dispatch(request, *args, **kwargs)</pre><h3>Integrating with Django Admin</h3><p>Enable object-level permission checks in Django admin by subclassing GuardedModelAdmin:</p><pre>from guardian.admin import GuardedModelAdmin<br>from django.contrib import admin<br>from .models import Project<br><br><br>@admin.register(Project)<br>class ProjectAdmin(GuardedModelAdmin):<br>    pass</pre><p>Admins will now see an “Object Permissions” tab for each object.</p><h3>Advanced: DRF Integration</h3><p>Use the ObjectPermissionBackend in Django REST Framework like this:</p><pre>from guardian.shortcuts import get_objects_for_user<br><br><br>class ProjectViewSet(viewsets.ModelViewSet):<br>    serializer_class = ProjectSerializer<br>    def get_queryset(self):<br>        return get_objects_for_user(self.request.user, &#39;view_project&#39;, klass=Project)</pre><p>Or check per-object permissions in has_object_permission():</p><pre>class ProjectPermission(BasePermission):<br>    def has_object_permission(self, request, view, obj):<br>        return request.user.has_perm(&#39;view_project&#39;, obj)</pre><h3>Considerations</h3><ul><li><strong>You must declare object-level permissions manually</strong> in the model’s Meta.permissions.</li><li><strong>assign_perm does not affect global permissions</strong> — use user.user_permissions.add(...) for that.</li><li><strong>Be cautious with anonymous access</strong> — use ANONYMOUS_USER_ID carefully.</li><li><strong>Performance</strong> — large ACLs may slow down joins. Index foreign keys and benchmark as needed.</li></ul><h3>Testing</h3><p>Test permissions like so:</p><pre>def test_user_cannot_see_other_projects(client, user, other_project):<br>    client.force_login(user)<br>    response = client.get(f&quot;/projects/{other_project.id}/&quot;)<br>    assert response.status_code == 403<br><br><br>def test_user_can_edit_assigned_project(client, user, project):<br>    assign_perm(&quot;edit_project&quot;, user, project)<br>    client.force_login(user)<br>    response = client.post(f&quot;/projects/{project.id}/edit/&quot;, {&quot;name&quot;: &quot;Updated&quot;})<br>    assert response.status_code == 200</pre><h3>Use Cases in Real Life</h3><ul><li><strong>Education Platforms</strong> — Teachers can grade only their students.</li><li><strong>Legal Apps</strong> — Lawyers can view only their cases.</li><li><strong>Recruiting Tools</strong> — Hiring managers can access candidates from their department.</li><li><strong>CRM Systems</strong> — Sales reps see only their leads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Za8FdtiWpe92yoGY1dKCdw.png" /></figure><p>With django-guardian, you can build flexible and secure permission systems where each object has its own access rules, ideal for platforms with complex collaboration needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f21befb3b8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django with Daphne, Nginx, Celery & Redis]]></title>
            <link>https://python.plainenglish.io/deploying-django-with-daphne-nginx-celery-redis-5a878b02a34a?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a878b02a34a</guid>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[daphne]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 00:39:58 GMT</pubDate>
            <atom:updated>2025-06-02T00:39:58.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGzP-H6pd6NcAp_w_v2T0w.png" /></figure><p>If you’re running Django with <strong>WebSockets (via Daphne)</strong> and <strong>asynchronous tasks (via Celery)</strong> in a production Linux server, this step-by-step guide is for you.</p><h3>Stack Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*ayXOxDbHVJq8V6ELSqaAQQ.png" /></figure><h3>Directory Layout Example</h3><pre>/var/www/myproject/<br>├── manage.py<br>├── myproject/<br>├── apps/<br>├── static/<br>├── media/<br>├── venv/ <br>└── logs/</pre><h3>1. Django Setup</h3><ul><li>Install Python 3.10+</li><li>Create and activate a virtualenv:</li></ul><pre>python3 -m venv env<br>source env/bin/activate</pre><ul><li>Install dependencies:</li></ul><pre>pip install -r requirements.txt<br># Must include: daphne, channels, celery, redis</pre><ul><li>Collect static files:</li></ul><pre>python manage.py collectstatic</pre><h3>2. settings.py Essentials</h3><pre>ASGI_APPLICATION = &quot;myproject.asgi.application&quot;<br><br><br>CHANNEL_LAYERS = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;channels_redis.core.RedisChannelLayer&quot;,<br>        &quot;CONFIG&quot;: {<br>            &quot;hosts&quot;: [(&quot;127.0.0.1&quot;, 6379)],<br>        },<br>    },<br>}<br>CELERY_BROKER_URL = &quot;redis://127.0.0.1:6379/0&quot;<br>CELERY_RESULT_BACKEND = &quot;redis://127.0.0.1:6379/1&quot;</pre><h3>3. Running Daphne</h3><p>Create a systemd unit file for <strong>Daphne</strong>:</p><pre>sudo nano /etc/systemd/system/daphne.service</pre><pre>[Unit]<br>Description=Daphne Service<br>After=network.target<br><br>[Service]<br>User=www-data<br>Group=www-data<br>WorkingDirectory=/var/www/myproject<br>ExecStart=/var/www/myproject/venv/bin/daphne -u /tmp/daphne.sock myproject.asgi:application<br>Restart=always<br>[Install]<br>WantedBy=multi-user.target</pre><h3>4. Running Celery</h3><p>Create another unit for <strong>Celery</strong>:</p><pre>sudo nano /etc/systemd/system/celery.service</pre><pre>[Unit]<br>Description=Celery Worker<br>After=network.target<br><br>[Service]<br>User=www-data<br>Group=www-data<br>WorkingDirectory=/var/www/myproject<br>ExecStart=/var/www/myproject/venv/bin/celery -A myproject worker --loglevel=info<br>Restart=always<br>[Install]<br>WantedBy=multi-user.target</pre><h3>5. Nginx Configuration</h3><pre>sudo nano /etc/nginx/sites-available/myproject</pre><pre>server {<br>    listen 80;<br>    server_name yourdomain.com;<br><br>    location /static/ {<br>        alias /var/www/myproject/static/;<br>    }<br>    location /media/ {<br>        alias /var/www/myproject/media/;<br>    }<br>    location /ws/ {<br>        proxy_pass http://unix:/tmp/daphne.sock;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &quot;upgrade&quot;;<br>        proxy_set_header Host $host;<br>    }<br>    location / {<br>        proxy_pass http://127.0.0.1:8000;<br>        include proxy_params;<br>        proxy_redirect off;<br>    }<br>}</pre><p>Enable and reload:</p><pre>sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/<br>sudo nginx -t &amp;&amp; sudo systemctl reload nginx</pre><h3>6. Start Services</h3><pre>sudo systemctl start daphne<br>sudo systemctl enable daphne</pre><pre>sudo systemctl start celery<br>sudo systemctl enable celery</pre><h3>7. Security &amp; Maintenance Tips</h3><ul><li>Use <strong>UFW</strong> to restrict Redis to localhost</li><li>Set Restart=always in services for resilience</li><li>Use <strong>supervisor</strong> or <strong>systemd timers</strong> to monitor logs</li><li>Set up <strong>SSL</strong> using Let’s Encrypt (certbot)</li></ul><h3>You Now Have:</h3><ul><li>WebSocket support via Daphne</li><li>Async task processing via Celery</li><li>Reverse-proxy and static/media file handling with Nginx</li><li>Redis as a shared broker and channel layer</li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a878b02a34a" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/deploying-django-with-daphne-nginx-celery-redis-5a878b02a34a">Deploying Django with Daphne, Nginx, Celery &amp; Redis</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Presence System in Django with WebSockets (Track Online/Offline Users)]]></title>
            <link>https://medium.com/django-unleashed/presence-system-in-django-with-websockets-track-online-offline-users-9f68c83541db?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f68c83541db</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Wed, 28 May 2025 07:24:51 GMT</pubDate>
            <atom:updated>2025-05-28T07:24:51.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*85T255JvFmGKvlhN3B-odw.png" /></figure><p>In any real-time application — chat apps, collaboration tools, or live dashboards — <strong>knowing who is online</strong> adds a powerful social and interactive layer. In this guide, you’ll learn how to implement a <strong>presence system</strong> using <strong>Django Channels</strong>, <strong>WebSockets</strong>, and <strong>Redis</strong>.</p><h3>What You’ll Learn</h3><ul><li>How to track a user&#39;s online/offline status</li><li>How to store presence info in Redis</li><li>How to broadcast presence updates to other users</li></ul><h3>Prerequisites</h3><ul><li>Django (3.0+)</li><li>Django Channels</li><li>Redis (as channel layer)</li></ul><h3>Setup Recap</h3><p>Install dependencies:</p><pre>pip install channels channels_redis</pre><p>In settings.py:</p><pre>ASGI_APPLICATION = &quot;myproject.asgi.application&quot;<br><br><br>CHANNEL_LAYERS = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;channels_redis.core.RedisChannelLayer&quot;,<br>        &quot;CONFIG&quot;: {<br>            &quot;hosts&quot;: [(&quot;127.0.0.1&quot;, 6379)],<br>        },<br>    },<br>}</pre><h3>Routing</h3><p><strong>routing.py:</strong></p><pre>from django.urls import re_path<br>from . import consumers<br><br><br>websocket_urlpatterns = [<br>    re_path(r&#39;ws/presence/$&#39;, consumers.PresenceConsumer.as_asgi()),<br>]</pre><h3>Redis Key Design</h3><p>To track users, we’ll use Redis like this:</p><pre>presence:user:{user_id} = timestamp or “online”</pre><p>We can use TTL (time to live) or explicitly delete keys on disconnect.</p><h3>Consumer Logic</h3><p><strong>consumers.py:</strong></p><pre>import json<br>import time<br>from channels.generic.websocket import AsyncWebsocketConsumer<br>from channels.db import database_sync_to_async<br>from django.contrib.auth import get_user_model<br>import aioredis<br><br>User = get_user_model()<br><br>class PresenceConsumer(AsyncWebsocketConsumer):<br>    async def connect(self):<br>        if self.scope[&quot;user&quot;].is_anonymous:<br>            await self.close()<br>            return<br>        self.user = self.scope[&quot;user&quot;]<br>        await self.accept()<br>        await self.mark_user_online()<br>        # Notify others<br>        await self.channel_layer.group_send(<br>            &quot;online_users&quot;,<br>            {<br>                &quot;type&quot;: &quot;user.status&quot;,<br>                &quot;user_id&quot;: self.user.id,<br>                &quot;status&quot;: &quot;online&quot;<br>            }<br>        )<br>        await self.channel_layer.group_add(&quot;online_users&quot;, self.channel_name)<br>    <br>    async def disconnect(self, code):<br>        await self.mark_user_offline()<br>        await self.channel_layer.group_send(<br>            &quot;online_users&quot;,<br>            {<br>                &quot;type&quot;: &quot;user.status&quot;,<br>                &quot;user_id&quot;: self.user.id,<br>                &quot;status&quot;: &quot;offline&quot;<br>            }<br>        )<br>        await self.channel_layer.group_discard(&quot;online_users&quot;, self.channel_name)<br>    <br>    async def user_status(self, event):<br>        await self.send(text_data=json.dumps(event))<br>    <br>    async def mark_user_online(self):<br>        redis = await aioredis.from_url(https://medium.com/&quot;redis://localhost&quot;)<br>        await redis.set(f&quot;presence:user:{self.user.id}&quot;, &quot;online&quot;, ex=60)  # TTL to auto-expire<br>        await redis.close()<br>    <br>    async def mark_user_offline(self):<br>        redis = await aioredis.from_url(https://medium.com/&quot;redis://localhost&quot;)<br>        await redis.delete(f&quot;presence:user:{self.user.id}&quot;)<br>        await redis.close()</pre><h3>Frontend JavaScript</h3><pre>const socket = new WebSocket(&#39;ws://&#39; + window.location.host + &#39;/ws/presence/&#39;);<br><br>socket.onmessage = function(e) {<br>    const data = JSON.parse(e.data);<br>    const userId = data.user_id;<br>    const status = data.status;<br>    updatePresenceUI(userId, status);<br>};</pre><h3>Admin API for Online Users</h3><p>Create a simple DRF API to list all online users:</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>import redis<br><br><br>class OnlineUserList(APIView):<br>    def get(self, request):<br>        r = redis.Redis()<br>        keys = r.keys(&quot;presence:user:*&quot;)<br>        user_ids = [int(k.decode().split(&quot;:&quot;)[2]) for k in keys]<br>        return Response({&quot;online_user_ids&quot;: user_ids})</pre><h3>Security Tips</h3><ul><li>Require authenticated users for WebSocket connections.</li><li>Set TTL on Redis keys to handle abrupt disconnections.</li><li>Add reconnect logic on the frontend.</li></ul><h3>Going Further</h3><ul><li>Display last seen timestamps</li><li>Show online status in chat or profile list</li><li>Integrate presence into friend/relationship systems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f68c83541db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/presence-system-in-django-with-websockets-track-online-offline-users-9f68c83541db">Presence System in Django with WebSockets (Track Online/Offline Users)</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multitenant Permissions in Django: Client-Based Access Control]]></title>
            <link>https://medium.com/django-unleashed/multitenant-permissions-in-django-client-based-access-control-3af2fec01ebb?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af2fec01ebb</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Wed, 21 May 2025 19:25:30 GMT</pubDate>
            <atom:updated>2025-05-21T19:25:30.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBg70vDNQPQKpuSy8lOIng.png" /></figure><p>In multitenant SaaS applications, isolating data access per tenant (e.g. client, company, or organization) is crucial. This article explores how to implement <strong>client-based access control</strong> in Django, ensuring users can only access data belonging to their organization.</p><p>We will walk through real-world modeling, query restrictions, permission enforcement, middleware, and role-based layering with practical examples to secure your SaaS platform.</p><h3>Use Case: SaaS with Multiple Clients</h3><p>Imagine a platform where companies (clients) sign up, and each company has multiple users. These users should only access data owned by their respective companies.</p><p>Example:</p><ul><li>Company A and Company B both use your SaaS.</li><li>A user from Company A should not see Company B’s resources, even if they share the same resource type.</li></ul><p>Multitenancy in Django can be achieved in two major ways:</p><ul><li><strong>Shared Database with Discriminator Field</strong> (e.g. client_id) — simpler and widely used.</li><li><strong>Separate schemas or databases per tenant</strong> — more isolation is used in advanced setups.</li></ul><p>This article focuses on the shared database pattern for its simplicity and ease of maintenance.</p><h3>Core Concepts</h3><ol><li><strong>Tenant Isolation</strong><br> Every model must be scoped by a foreign key to Client, which serves as the tenant identifier. This prevents cross-client data leakage.</li><li><strong>Request Context Awareness</strong><br> Every request is associated with an authenticated user, and all data access should be scoped to request.user.client.</li><li><strong>Role-Based Access</strong><br> Permissions can be fine-tuned by assigning roles within a tenant, e.g. Admin, Manager, Staff. Roles determine the scope of access within the tenant’s data.</li><li><strong>Security-First Validation</strong><br> Do not rely on frontend submissions for client IDs. Enforce permissions and data ownership at the backend.</li><li><strong>Scalability through Middleware and Reusability</strong><br> Encapsulate tenant extraction logic in middleware, and permission logic in reusable classes.</li></ol><h3>Step-by-Step Implementation</h3><h3>1. Define the Models</h3><p>At the core of a multitenant system is the relationship between Client, User, and domain models such as Project, Invoice, Report, etc.</p><pre>class Client(models.Model):<br>    name = models.CharField(max_length=255)<br>    created_at = models.DateTimeField(auto_now_add=True)<br><br><br>class User(AbstractUser):<br>    client = models.ForeignKey(Client, on_delete=models.CASCADE)<br>    role = models.CharField(<br>        max_length=20,<br>        choices=[(&#39;admin&#39;, &#39;Admin&#39;), (&#39;manager&#39;, &#39;Manager&#39;), (&#39;staff&#39;, &#39;Staff&#39;)],<br>        default=&#39;staff&#39;<br>    )<br><br><br>class Project(models.Model):<br>    client = models.ForeignKey(Client, on_delete=models.CASCADE)<br>    name = models.CharField(max_length=255)<br>    owner = models.ForeignKey(User, on_delete=models.CASCADE)<br>    created_at = models.DateTimeField(auto_now_add=True)</pre><p>Add client to every critical model to tie them to their owner organization.</p><h3>2. Use Custom Permissions</h3><p>Start by creating a basic permission class that ensures the object being accessed belongs to the same client as the requesting user.</p><pre>from rest_framework.permissions import BasePermission<br><br><br>class IsSameClient(BasePermission):<br>    def has_object_permission(self, request, view, obj):<br>        return hasattr(obj, &#39;client&#39;) and obj.client == request.user.client</pre><p>Apply this permission class to views or override the queryset in viewsets to restrict access:</p><pre>class ProjectViewSet(viewsets.ModelViewSet):<br>    serializer_class = ProjectSerializer<br>    permission_classes = [IsAuthenticated, IsSameClient]<br><br>    def get_queryset(self):<br>        return Project.objects.filter(client=self.request.user.client)<br>    <br>    def perform_create(self, serializer):<br>        serializer.save(client=self.request.user.client, owner=self.request.user)</pre><h3>3. Admin and Role Logic</h3><p>Use roles to control privilege within the same tenant.</p><pre>class UserRole(models.TextChoices):<br>    ADMIN = &#39;admin&#39;, &#39;Admin&#39;<br>    MANAGER = &#39;manager&#39;, &#39;Manager&#39;<br>    STAFF = &#39;staff&#39;, &#39;Staff&#39;<br><br><br>class User(AbstractUser):<br>    client = models.ForeignKey(Client, on_delete=models.CASCADE)<br>    role = models.CharField(max_length=20, choices=UserRole.choices, default=UserRole.STAFF)</pre><p>Create a compound permission class:</p><pre>class IsClientAdminOrOwner(BasePermission):<br>    def has_object_permission(self, request, view, obj):<br>        return (<br>            obj.client == request.user.client and (<br>                request.user.role == UserRole.ADMIN or<br>                obj.owner == request.user<br>            )<br>        )</pre><p>Use role checks in serializers to allow certain fields to be modified only by admins:</p><pre>class ProjectSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Project<br>        fields = [&#39;id&#39;, &#39;name&#39;, &#39;owner&#39;, &#39;created_at&#39;]<br>        read_only_fields = [&#39;owner&#39;]<br>    <br>    def validate(self, attrs):<br>        if self.context[&#39;request&#39;].user.role != UserRole.ADMIN:<br>            raise serializers.ValidationError(&quot;Only admins can create projects.&quot;)<br>        return super().validate(attrs)</pre><h3>Middleware for Tenant Access</h3><p>For large applications, separating out the logic to determine tenant context improves code clarity.</p><pre>class ClientMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        if request.user.is_authenticated:<br>            request.tenant = request.user.client<br>        return self.get_response(request)</pre><h3>Serializers: Injecting Context</h3><p>Avoid exposing client in the serializer:</p><pre>class ProjectSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Project<br>        fields = [&#39;id&#39;, &#39;name&#39;, &#39;created_at&#39;]<br><br>    def create(self, validated_data):<br>        validated_data[&#39;client&#39;] = self.context[&#39;request&#39;].user.client<br>        validated_data[&#39;owner&#39;] = self.context[&#39;request&#39;].user<br>        return super().create(validated_data)</pre><h3>Best Practices</h3><ul><li><strong>Never trust user-submitted </strong><strong>client_id</strong> — always derive it from the authenticated user.</li><li><strong>Centralize permission logic</strong> — avoid duplicating access checks across views.</li><li><strong>Write shared mixins and base viewsets</strong> to encapsulate multitenant behavior.</li><li><strong>Document your permission model</strong> for better team collaboration.</li></ul><h3>Common Mistakes</h3><ul><li>❌ Forgetting to filter queryset by client.</li><li>❌ Accepting client_id in POST bodies.</li><li>❌ Missing role-based logic where needed (e.g. staff modifying others’ resources).</li><li>❌ Not testing cross-tenant access violations.</li></ul><h3>Testing Access Control</h3><p>Example test cases:</p><pre>def test_user_cannot_access_others_project(api_client, user_a, project_b):<br>    api_client.force_authenticate(user=user_a)<br>    response = api_client.get(f&#39;/api/projects/{project_b.id}/&#39;)<br>    assert response.status_code == 404<br><br>def test_admin_can_create_project(api_client, admin_user):<br>    api_client.force_authenticate(user=admin_user)<br>    data = {&#39;name&#39;: &#39;New Project&#39;}<br>    response = api_client.post(&#39;/api/projects/&#39;, data)<br>    assert response.status_code == 201</pre><p>Also, consider integration tests using tenant fixtures.</p><p>Multitenant permission management in Django ensures strong data isolation and secure access control across client organizations. Implementing it correctly requires:</p><ul><li>Consistent tenant-scoping of all data models</li><li>Permission classes that validate client ownership</li><li>Role-based access is layered on top of tenant logic</li><li>Middleware and reusable patterns to reduce repetition</li><li>Strong testing to verify proper isolation</li></ul><p>With these patterns, you can confidently scale your SaaS platform across multiple clients while maintaining privacy, security, and compliance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af2fec01ebb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/multitenant-permissions-in-django-client-based-access-control-3af2fec01ebb">Multitenant Permissions in Django: Client-Based Access Control</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[APIs with Custom Error Codes and Localization]]></title>
            <link>https://medium.com/@fahimad/apis-with-custom-error-codes-and-localization-a50525af9b7b?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a50525af9b7b</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 20:00:01 GMT</pubDate>
            <atom:updated>2024-12-25T20:00:01.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xl_bZP-UuuHLqaoFVUlDkA.png" /></figure><p>When building APIs for global applications, a standardized error-handling mechanism with custom error codes and localized messages enhances usability and helps developers diagnose issues quickly. This article will guide you through creating a robust error-handling framework in Django REST Framework (DRF), focusing on custom error codes and localization.</p><h3>Why Use Custom Error Codes and Localization?</h3><p><strong>1. Custom Error Codes</strong>:</p><ul><li>Provide unique identifiers for each error type.</li><li>Simplify debugging by offering structured, standardized error responses.</li><li>Useful for integrating APIs with third-party systems.</li></ul><p><strong>2. Localization</strong>:</p><ul><li>Improves user experience for global applications by displaying messages in the user’s language.</li><li>Helps comply with regional accessibility standards.</li></ul><h3>Key Components of Custom Error Handling</h3><ol><li><strong>Custom Error Codes</strong>: Unique codes to identify specific errors.</li><li><strong>Error Response Structure</strong>: Consistent format for all API errors.</li><li><strong>Localization</strong>: Dynamically load messages based on the user’s preferred language.</li></ol><h3>Step 1: Define a Standardized Error Format</h3><p>Design a format that includes:</p><ul><li><strong>Error Code</strong>: A unique identifier.</li><li><strong>Message</strong>: A human-readable description of the error.</li><li><strong>Details</strong>: Additional context (optional).</li></ul><p><strong>Example Error Response</strong>:</p><pre>{<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;AUTH_001&quot;,<br>        &quot;message&quot;: &quot;Invalid credentials&quot;,<br>        &quot;details&quot;: &quot;The provided username or password is incorrect.&quot;<br>    }<br>}</pre><h3>Step 2: Define Error Codes</h3><p>Create a Python module to store reusable error codes and messages.</p><pre># errors.py<br>ERRORS = {<br>    &quot;AUTH_001&quot;: &quot;Invalid credentials&quot;,<br>    &quot;AUTH_002&quot;: &quot;Account locked due to multiple failed login attempts&quot;,<br>    &quot;DATA_001&quot;: &quot;Invalid data format&quot;,<br>    &quot;DATA_002&quot;: &quot;Required fields are missing&quot;,<br>    &quot;PERM_001&quot;: &quot;Permission denied&quot;,<br>    &quot;SERVER_001&quot;: &quot;An unexpected error occurred. Please try again later.&quot;<br>}</pre><h3>Step 3: Implement a Custom Exception Handler</h3><p>Override DRF’s default exception handler to include error codes and localization.</p><pre># exception_handler.py<br>from rest_framework.views import exception_handler<br>from django.utils.translation import gettext as _<br>from .errors import ERRORS<br><br><br>def custom_exception_handler(exc, context):<br>    response = exception_handler(exc, context)<br>    if response is not None:<br>        # Default error details<br>        error_code = response.data.get(&#39;code&#39;, &#39;SERVER_001&#39;)<br>        message = _(ERRORS.get(error_code, &quot;An unexpected error occurred.&quot;))<br>        # Standardized response format<br>        response.data = {<br>            &quot;error&quot;: {<br>                &quot;code&quot;: error_code,<br>                &quot;message&quot;: message,<br>                &quot;details&quot;: response.data.get(&#39;detail&#39;, None)<br>            }<br>        }<br>    return response</pre><p>Update DRF settings to use this handler:</p><pre># settings.py<br>REST_FRAMEWORK = {<br>    &#39;EXCEPTION_HANDLER&#39;: &#39;myapp.exception_handler.custom_exception_handler&#39;,<br>}</pre><h3>Step 4: Localize Error Messages</h3><p>Django supports localization using <strong>gettext</strong>.</p><p><strong>1. Mark Strings for Translation</strong>: Use _() to mark strings for translation in the ERRORS dictionary:</p><pre>from django.utils.translation import gettext_lazy as _<br><br><br>ERRORS = {<br>    &quot;AUTH_001&quot;: _(&quot;Invalid credentials&quot;),<br>    &quot;AUTH_002&quot;: _(&quot;Account locked due to multiple failed login attempts&quot;),<br>    &quot;DATA_001&quot;: _(&quot;Invalid data format&quot;),<br>    &quot;DATA_002&quot;: _(&quot;Required fields are missing&quot;),<br>    &quot;PERM_001&quot;: _(&quot;Permission denied&quot;),<br>    &quot;SERVER_001&quot;: _(&quot;An unexpected error occurred. Please try again later.&quot;)<br>}</pre><p><strong>2. Generate Translation Files</strong>:</p><pre>python manage.py makemessages -l es  # Example: Spanish</pre><p><strong>3. Add Translations</strong>: Edit the locale/&lt;language_code&gt;/LC_MESSAGES/django.po file with the translations:</p><pre>msgid &quot;Invalid credentials&quot;<br>msgstr &quot;Credenciales inválidas&quot;<br><br>msgid &quot;Permission denied&quot;<br>msgstr &quot;Permiso denegado&quot;</pre><p><strong>4. Compile Translations</strong>:</p><pre>python manage.py compilemessages</pre><p><strong>5. Set User Language</strong>: Detect and set the language in a middleware or view based on user preferences:</p><pre>from django.utils import translation<br><br><br>def set_language_from_request(request):<br>    lang = request.headers.get(&#39;Accept-Language&#39;, &#39;en&#39;)<br>    translation.activate(lang)</pre><h3>Step 5: Define Custom Exceptions</h3><p>Create reusable custom exceptions with error codes and optional details.</p><pre># exceptions.py<br>from rest_framework.exceptions import APIException<br><br><br>class CustomAPIException(APIException):<br>    def __init__(self, code, details=None):<br>        self.code = code<br>        self.details = details<br>        super().__init__(detail={&quot;code&quot;: code, &quot;details&quot;: details})</pre><h3>Step 6: Use Custom Exceptions in Views</h3><p>Raise exceptions with appropriate error codes and details in your views.</p><pre># views.py<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from .exceptions import CustomAPIException<br><br><br>class LoginView(APIView):<br>    def post(self, request):<br>        username = request.data.get(&quot;username&quot;)<br>        password = request.data.get(&quot;password&quot;)<br><br>        if not username or not password:<br>            raise CustomAPIException(&quot;DATA_002&quot;, &quot;Username and password are required.&quot;)<br><br>        if username != &quot;admin&quot; or password != &quot;password&quot;:<br>            raise CustomAPIException(&quot;AUTH_001&quot;)<br><br>        return Response({&quot;message&quot;: &quot;Login successful&quot;})</pre><h3>Step 7: Testing the API</h3><p><strong>Default Language</strong>: Request:</p><pre>POST /login<br>Content-Type: application/json<br><br>{<br>    &quot;username&quot;: &quot;user&quot;,<br>    &quot;password&quot;: &quot;wrongpass&quot;<br>}</pre><p>Response:</p><pre>{<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;AUTH_001&quot;,<br>        &quot;message&quot;: &quot;Invalid credentials&quot;,<br>        &quot;details&quot;: null<br>    }<br>}</pre><p><strong>Localized Message</strong>: With Accept-Language: es (Spanish header):</p><pre>{<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;AUTH_001&quot;,<br>        &quot;message&quot;: &quot;Credenciales inválidas&quot;,<br>        &quot;details&quot;: null<br>    }<br>}</pre><h3>Benefits of This Approach</h3><p><strong>1. Consistency</strong>:</p><ul><li>A standardized error format improves API usability.</li><li>Easier for developers to parse and debug errors.</li></ul><p><strong>2. Localization</strong>:</p><ul><li>Ensures a better user experience for global audiences.</li><li>Supports compliance with accessibility and localization standards.</li></ul><p><strong>3. Scalability</strong>:</p><ul><li>New error codes and translations can be added easily without disrupting existing functionality.</li></ul><p><strong>4. Integration-Friendly</strong>:</p><ul><li>Third-party integrators can rely on structured error codes for automation and monitoring.</li></ul><h3>Best Practices</h3><ol><li><strong>Document Error Codes</strong>: Maintain a detailed reference for all error codes in your API documentation.</li><li><strong>Log Errors</strong>: Log all errors server-side for monitoring and debugging.</li><li><strong>Avoid Overloading Clients</strong>: Provide concise error details without exposing sensitive information.</li><li><strong>Test for Localization</strong>: Test your API with different languages to ensure accurate and complete translations.</li></ol><p>By implementing custom error codes and localization, you can make your REST APIs more user-friendly, developer-centric, and globally accessible. This approach improves the API’s usability and supports seamless integration with third-party systems, paving the way for scalable and robust applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a50525af9b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encrypt Sensitive Data in Django REST APIs]]></title>
            <link>https://medium.com/@fahimad/encrypt-sensitive-data-in-django-rest-apis-0e092a8efe84?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e092a8efe84</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 19:42:34 GMT</pubDate>
            <atom:updated>2024-12-17T19:43:13.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRxnoNRKUO44BEYAdVhVJg.png" /></figure><p>With increasing concerns about data privacy, securing sensitive data in REST APIs has become critical. Whether it’s <strong>data in transit</strong> (moving between client and server) or <strong>data at rest</strong> (stored in databases or files), implementing proper encryption and security measures ensures compliance with regulations like GDPR, HIPAA, and PCI-DSS.</p><p>This article explains how to secure sensitive data in REST APIs by using <strong>TLS</strong>, <strong>field-level encryption</strong>, <strong>secure headers</strong>, and other best practices.</p><h3>1. Securing Data in Transit</h3><p>Data in transit refers to data actively being transferred between the client (e.g., browser, mobile app) and server. Without protection, it’s susceptible to interception (e.g., <strong>man-in-the-middle attacks</strong>).</p><h4>A. Use HTTPS with TLS</h4><ul><li>Use <strong>TLS (Transport Layer Security)</strong> to encrypt HTTP requests and responses.</li><li>Always enforce HTTPS to protect sensitive data like tokens, passwords, and user details.</li></ul><p><strong>Steps to Enable HTTPS</strong>:</p><ol><li>Obtain an SSL/TLS certificate (e.g., from <strong>Let’s Encrypt</strong>).</li><li>Configure your server (Nginx, Apache) to enforce HTTPS:</li></ol><pre>server {<br>    listen 443 ssl;<br>    server_name example.com;<br><br>    ssl_certificate /path/to/fullchain.pem;<br>    ssl_certificate_key /path/to/privkey.pem;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:8000;<br>        proxy_set_header X-Forwarded-Proto https;<br>    }<br>}</pre><p>3. Redirect HTTP to HTTPS using a 301 redirect:</p><pre>server {<br>    listen 80;<br>    server_name example.com;<br>    return 301 https://$host$request_uri;<br>}</pre><p><strong>Key Best Practices</strong>:</p><ul><li>Use <strong>TLS 1.2</strong> or higher.</li><li>Avoid weak ciphers or outdated SSL/TLS protocols.</li><li>Regularly test your SSL configuration using tools like SSL Labs.</li></ul><h4>B. Use Secure Headers</h4><p>Secure HTTP headers protect API communication by mitigating security risks like XSS, CSRF, and clickjacking.</p><p><strong>Common Secure Headers</strong>:</p><p><strong>1. Strict-Transport-Security</strong> (HSTS): Ensures all future requests use HTTPS.</p><pre>Strict-Transport-Security: max-age=31536000; includeSubDomains; preload</pre><p><strong>2. Content-Security-Policy (CSP)</strong>: Mitigates XSS attacks by restricting resources that can be loaded.</p><pre>Content-Security-Policy: default-src &#39;self&#39;;</pre><p><strong>3. X-Content-Type-Options</strong>: Prevents MIME-sniffing attacks.</p><pre>X-Content-Type-Options: nosniff</pre><p><strong>4. X-Frame-Options</strong>: Prevents clickjacking attacks.</p><pre>X-Frame-Options: DENY</pre><p><strong>In Django</strong>, you can use the django-secure package or middleware to add these headers:</p><pre># settings.py<br>SECURE_CONTENT_TYPE_NOSNIFF = True<br>SECURE_BROWSER_XSS_FILTER = True<br>SECURE_HSTS_SECONDS = 31536000<br>SECURE_SSL_REDIRECT = True</pre><h3>2. Securing Data at Rest</h3><p>Data at rest refers to stored data in databases, files, or backups. Encrypting it protects against unauthorized access if servers or databases are compromised.</p><h4>A. Field-Level Encryption</h4><p>For sensitive fields like passwords, credit card numbers, or personal information, use <strong>field-level encryption</strong>.</p><p><strong>1. Installing Required Libraries</strong>: Use Django’s cryptography library for encryption:</p><pre>pip install cryptography</pre><p><strong>2. Encrypting Sensitive Fields</strong>:</p><pre>from cryptography.fernet import Fernet<br>from django.db import models<br>import base64<br>import os<br><br># Generate a key for encryption (store securely)<br>key = Fernet.generate_key()<br>cipher = Fernet(key)<br><br>class SecureModel(models.Model):<br>    encrypted_field = models.TextField()<br><br>    def set_sensitive_data(self, raw_data):<br>        encrypted_data = cipher.encrypt(raw_data.encode())<br>        self.encrypted_field = encrypted_data.decode()<br><br>    def get_sensitive_data(self):<br>        decrypted_data = cipher.decrypt(self.encrypted_field.encode())<br>        return decrypted_data.decode()</pre><p><strong>3. Using the SecureModel</strong>:</p><pre>instance = SecureModel()<br>instance.set_sensitive_data(&quot;secret_info&quot;)<br>instance.save()<br><br>print(instance.get_sensitive_data())  # Outputs: secret_info</pre><p><strong>Key Notes</strong>:</p><ul><li>Securely store encryption keys using environment variables or tools like AWS KMS, HashiCorp Vault, or Azure Key Vault.</li><li>Avoid hardcoding keys in source code.</li></ul><h4>B. Database-Level Encryption</h4><p>Many modern databases (e.g., PostgreSQL, MySQL) offer <strong>Transparent Data Encryption (TDE)</strong> to encrypt data automatically.</p><p><strong>PostgreSQL Example</strong>: Enable encryption by configuring <strong>pgcrypto</strong> for column-level encryption:</p><pre>CREATE EXTENSION pgcrypto;<br><br>INSERT INTO secure_table (data) <br>VALUES (pgp_sym_encrypt(&#39;Sensitive Data&#39;, &#39;encryption_key&#39;));</pre><h3>3. Secure API Authentication</h3><p><strong>1. Token-Based Authentication</strong>:</p><ul><li>Use <strong>JWT (JSON Web Token)</strong> or OAuth2 for secure stateless authentication.</li><li>Use strong, short-lived tokens and refresh tokens.</li></ul><p><strong>2. Encrypt Tokens</strong>: Store tokens securely and transmit them using HTTPS. Only store sensitive tokens in cookies or local storage with proper security.</p><p><strong>3. Rotate Keys Regularly</strong>: Implement periodic token key rotation for long-running APIs.</p><h3>4. Prevent Data Leakage</h3><p><strong>1. Mask Sensitive Data</strong>: Mask or redact sensitive fields in API responses:</p><pre>{<br>    &quot;credit_card&quot;: &quot;**** **** **** 1234&quot;,<br>    &quot;ssn&quot;: &quot;XXX-XX-6789&quot;<br>}</pre><p><strong>2. Validate Output</strong>: Ensure sensitive fields are never accidentally exposed in logs, errors, or responses.</p><p><strong>3. Use Serializer-Level Control in Django</strong>:</p><pre>from rest_framework import serializers<br>from .models import SecureModel<br><br>class SecureSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = SecureModel<br>        exclude = [&#39;encrypted_field&#39;]  # Prevent sending encrypted data in API responses</pre><h3>5. Secure Backups</h3><ul><li>Encrypt backups of your database and files.</li><li>Use secure storage solutions (e.g., AWS S3 with encryption enabled).</li><li>Limit access to backup files to authorized users only.</li></ul><h3>6. Logging and Monitoring</h3><ul><li>Mask sensitive data in logs:</li></ul><pre>import logging<br><br>logging.basicConfig(level=logging.INFO)<br>sensitive_data = &quot;1234-5678-9101-1121&quot;<br>logging.info(&quot;Received data: %s&quot;, &quot;****-****-****-1121&quot;)</pre><ul><li>Use monitoring tools to detect unauthorized access or suspicious activity.</li></ul><p>Encrypting sensitive data in REST APIs is essential for protecting user information, maintaining compliance, and ensuring trust. By securing <strong>data in transit</strong> with TLS and HTTPS, <strong>data at rest</strong> using encryption, and employing secure API authentication mechanisms, you can safeguard your application against breaches and leaks. Always implement these techniques with proper key management, logging, and monitoring to stay ahead of potential threats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e092a8efe84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Django Applications on AWS EC2]]></title>
            <link>https://medium.com/@fahimad/deploy-django-applications-on-aws-ec2-142d968253e3?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/142d968253e3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 14:39:09 GMT</pubDate>
            <atom:updated>2024-12-06T14:39:09.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X966UOKz42QNutBTBQ5_2g.png" /></figure><p>Deploying Django applications on <strong>AWS EC2 (Elastic Compute Cloud)</strong> can seem daunting for beginners, but it’s a powerful and scalable way to host your web applications. This guide walks you through deploying a Django project on AWS EC2, covering all the necessary steps, including server setup, installing dependencies, and configuring the production application.</p><h3>Prerequisites</h3><ol><li><strong>AWS Account</strong>: Create an account at <a href="https://aws.amazon.com/">AWS</a>.</li><li><strong>Django Application</strong>: A Django project ready for deployment.</li><li><strong>Basic Command Line Knowledge</strong>: Familiarity with Linux commands.</li><li><strong>Domain Name (Optional)</strong>: Ensure you have a domain ready for a custom domain setup.</li></ol><h3>Step 1: Launch an EC2 Instance</h3><p><strong>Log in to AWS Console</strong>:</p><ul><li>Navigate to the <strong>EC2 Dashboard</strong>.</li></ul><p><strong>Launch an Instance</strong>:</p><ul><li><strong>Choose an Amazon Machine Image (AMI):</strong> Select <strong>Ubuntu Server 22.04 LTS</strong> (or any preferred Linux distribution).</li><li><strong>Choose an Instance Type:</strong> The <strong>t2.micro</strong> (free tier eligible) is sufficient for beginners.</li><li><strong>Configure Instance Details:</strong> Leave default settings unless you require advanced configurations.</li><li><strong>Add Storage:</strong> Assign at least <strong>8GB</strong> for storage.</li><li><strong>Configure Security Group:</strong> Add rules to allow <strong>SSH (port 22)</strong>, <strong>HTTP (port 80)</strong>, and <strong>HTTPS (port 443)</strong>.</li></ul><p><strong>Key Pair</strong>:</p><ul><li>Create or use an existing key pair to connect to the instance securely.</li><li>Download the private key (.pem file).</li></ul><p><strong>Launch</strong>: Click <strong>Launch Instance</strong> and wait for the instance to initialize.</p><h3>Step 2: Connect to Your EC2 Instance</h3><p><strong>Locate Public IP</strong>: In the EC2 dashboard, find the public IP address of your instance.</p><p><strong>Connect via SSH</strong>: Run the following command in your terminal:</p><pre>ssh -i path_to_key.pem ubuntu@your_instance_ip</pre><p>Replace path_to_key.pem with the path to your private key file and your_instance_ip with the instance&#39;s public IP.</p><h3>Step 3: Update the Server and Install Required Software</h3><p><strong>Update Packages</strong>:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y</pre><h4><strong>Install Required Software</strong>:</h4><p><strong>Python3 and Pip</strong>:</p><pre>sudo apt install python3 python3-pip -y</pre><p><strong>Git</strong>:</p><pre>sudo apt install git -y</pre><p><strong>Virtual Environment</strong>:</p><pre>sudo pip3 install virtualenv</pre><p><strong>Nginx</strong>:</p><pre>sudo apt install nginx -y</pre><p><strong>Gunicorn</strong>:</p><pre>pip install gunicorn</pre><h3>Step 4: Deploy Your Django Application</h3><p><strong>Clone Your Repository</strong>:</p><pre>git clone https://github.com/your_username/your_project.git <br>cd your_project</pre><p><strong>Set Up a Virtual Environment</strong>:</p><pre>virtualenv venv source venv/bin/activate</pre><p><strong>Install Dependencies</strong>:</p><pre>pip install -r requirements.txt</pre><p><strong>Collect Static Files</strong>:</p><pre>python manage.py collectstatic</pre><p><strong>Run Database Migrations</strong>:</p><pre>python manage.py migrate</pre><p><strong>Test Your Application</strong>:</p><pre>python manage.py runserver 0.0.0.0:8000</pre><ol><li>Visit http://your_instance_ip:8000 to verify the application is running.</li></ol><h3>Step 5: Configure Gunicorn</h3><p>Gunicorn serves your Django application and integrates with Nginx.</p><ol><li><strong>Create a Gunicorn Service</strong>:</li></ol><pre>sudo nano /etc/systemd/system/gunicorn.service</pre><p><strong>Add the Following Configuration</strong>:</p><pre>[Unit]<br>Description=gunicorn daemon<br>After=network.target<br><br>[Service]<br>User=ubuntu<br>Group=www-data<br>WorkingDirectory=/home/ubuntu/your_project<br>ExecStart=/home/ubuntu/your_project/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/your_project/your_project.sock your_project.wsgi:application<br><br>[Install]<br>WantedBy=multi-user.target</pre><p><strong>Start Gunicorn</strong>:</p><pre>sudo systemctl start gunicorn <br>sudo systemctl enable gunicorn</pre><h3>Step 6: Configure Nginx</h3><p>Nginx acts as a reverse proxy to handle requests and serve static files.</p><p><strong>Create a New Nginx Configuration</strong>:</p><pre>sudo nano /etc/nginx/sites-available/your_project</pre><p><strong>Add the Following Configuration</strong>:</p><pre>server {<br>    listen 80;<br>    server_name your_instance_ip; <br>    # server_name example.com; # to serve it in your domain<br><br>    location = /favicon.ico { access_log off; log_not_found off; }<br>    location /static/ {<br>        root /home/ubuntu/your_project;<br>    }<br><br>    location / {<br>        include proxy_params;<br>        proxy_pass http://unix:/home/ubuntu/your_project/your_project.sock;<br>    }<br>}</pre><p><strong>Enable the Configuration</strong>:</p><pre>sudo ln -s /etc/nginx/sites-available/your_project /etc/nginx/sites-enabled <br>sudo nginx -t <br>sudo systemctl restart nginx</pre><p><strong>Test the Setup</strong>: Visit http://your_instance_ip to confirm your application is live.</p><h3>Step 7: Secure Your Application with HTTPS (Optional)</h3><p><strong>Install Certbot</strong>:</p><pre>sudo apt install certbot python3-certbot-nginx -y</pre><p><strong>Generate an SSL Certificate</strong>:</p><pre>sudo certbot --nginx -d your_domain_name</pre><p><strong>Renew Certificates Automatically</strong>: Certbot automatically sets up renewal, but you can test it:</p><pre>sudo certbot renew --dry-run</pre><h3>Step 8: Monitor and Maintain Your Application</h3><ul><li><strong>Monitor Logs</strong>:</li></ul><pre>sudo journalctl -u gunicorn sudo tail -f /var/log/nginx/access.log</pre><ul><li><strong>Update Packages</strong>: Regularly update Python libraries and system packages.</li><li><strong>Scale Your Application</strong>: Use AWS Load Balancers and Auto Scaling for increased traffic.</li></ul><p>Deploying Django applications on AWS EC2 provides full control and scalability. This guide covered setting up an EC2 instance, configuring Django with Gunicorn and Nginx, and optionally securing your application with HTTPS. While EC2 deployment requires effort compared to managed platforms, it offers unmatched flexibility and customization, making it a valuable skill for developers building robust web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142d968253e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resilient APIs: Retry Logic, Circuit Breakers, and Fallback Mechanisms]]></title>
            <link>https://medium.com/@fahimad/resilient-apis-retry-logic-circuit-breakers-and-fallback-mechanisms-cfd37f523f43?source=rss-e426a1e4223d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd37f523f43</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <dc:creator><![CDATA[Fahim Ahmed]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 14:12:12 GMT</pubDate>
            <atom:updated>2024-12-02T14:12:12.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQN_mlFXC-mOwZUqMGwoZw.png" /></figure><p>APIs often depend on external services, such as third-party APIs, databases, or microservices. These dependencies can fail or become slow due to network issues, high traffic, or outages. To ensure your APIs remain robust and user-friendly during such failures, you can implement resilience patterns like <strong>retry logic</strong>, <strong>circuit breakers</strong>, and <strong>fallback mechanisms</strong>.</p><p>This article provides an overview of these patterns, explains their importance, and offers practical examples to implement them in your Django REST Framework (DRF) APIs.</p><h4>Why API Resilience Matters</h4><p>Resilient APIs improve:</p><ol><li><strong>User Experience</strong>: By reducing downtime and providing fallback responses, resilient APIs prevent user frustration.</li><li><strong>Stability</strong>: Circuit breakers and retries protect your system from cascading failures and overloading during outages.</li><li><strong>Reliability</strong>: APIs that gracefully handle failures are trusted by clients and third-party integrations.</li></ol><h4>Key Patterns for Building Resilient APIs</h4><h4>1. Retry Logic</h4><p>Retry logic involves reattempting a failed operation, such as an HTTP request, after a certain interval. This is useful when failures are temporary, such as network timeouts or rate-limiting errors.</p><p><strong>Implementing Retry Logic in Python</strong></p><p>Use the tenacity library to implement retry logic in Python:</p><p><strong>Installation</strong>:</p><pre>pip install tenacity</pre><p><strong>Example</strong>:</p><pre>from tenacity import retry, stop_after_attempt, wait_exponential<br>import requests<br><br><br>@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=10))<br>def fetch_data():<br>    response = requests.get(&quot;https://api.example.com/data&quot;)<br>    response.raise_for_status()  # Raise an exception for 4xx/5xx responses<br>    return response.json()<br><br><br># Usage<br>try:<br>    data = fetch_data()<br>    print(&quot;Data fetched successfully:&quot;, data)<br>except Exception as e:<br>    print(&quot;Failed after retries:&quot;, e)</pre><p><strong>Key Parameters</strong>:</p><ul><li>stop_after_attempt(3): Retry up to 3 times.</li><li>wait_exponential: Wait exponentially (e.g., 1s, 2s, 4s) between retries.</li></ul><h4>2. Circuit Breakers</h4><p>A circuit breaker is a design pattern that prevents excessive load on failing systems. It temporarily “opens” after a series of failures, blocking further requests until the system recovers.</p><p>Implementing Circuit Breakers with pybreaker</p><p><strong>Installation</strong>:</p><pre>pip install pybreaker</pre><p><strong>Example</strong>:</p><pre>import requests<br>from pybreaker import CircuitBreaker<br><br><br># Define a circuit breaker<br>circuit_breaker = CircuitBreaker(fail_max=3, reset_timeout=60)<br>@circuit_breaker<br>def fetch_data():<br>    response = requests.get(&quot;https://api.example.com/data&quot;)<br>    response.raise_for_status()<br>    return response.json()<br><br><br># Usage<br>try:<br>    data = fetch_data()<br>    print(&quot;Data fetched successfully:&quot;, data)<br>except CircuitBreaker.Error:<br>    print(&quot;Circuit breaker is open. Please try again later.&quot;)<br>except Exception as e:<br>    print(&quot;Request failed:&quot;, e)</pre><p><strong>How It Works</strong>:</p><ol><li>After 3 consecutive failures (fail_max=3), the circuit breaker opens.</li><li>It remains open for 60 seconds (reset_timeout=60) before allowing limited test requests.</li></ol><h4>3. Fallback Mechanisms</h4><p>Fallback mechanisms provide an alternative response when a dependent service fails. This could be returning cached data, a default value, or an error message.</p><p>Example: Fallback to Cached Data</p><p>Use Django’s caching framework to serve cached data when a request to an external service fails.</p><p><strong>View Example</strong>:</p><pre>from django.core.cache import cache<br>import requests<br>from django.http import JsonResponse<br><br><br>def fetch_data_with_fallback():<br>    cache_key = &quot;external_data&quot;<br>    cached_data = cache.get(cache_key)<br>    if cached_data:<br>        return cached_data  # Return cached data if available<br>    try:<br>        response = requests.get(&quot;https://api.example.com/data&quot;, timeout=5)<br>        response.raise_for_status()<br>        data = response.json()<br>        # Cache the fetched data for 15 minutes<br>        cache.set(cache_key, data, 60 * 15)<br>        return data<br>    except requests.RequestException:<br>        return {&quot;message&quot;: &quot;Service unavailable. Serving fallback data.&quot;}<br><br><br>def external_data_view(request):<br>    data = fetch_data_with_fallback()<br>    return JsonResponse(data)</pre><p><strong>Advantages</strong>:</p><ul><li>Ensures users receive some response even during outages.</li><li>Reduces API downtime perception by clients.</li></ul><h4>Combining Patterns for Robust APIs</h4><p>To maximize resilience, combine retry logic, circuit breakers, and fallback mechanisms. For example:</p><ol><li><strong>Retry Logic</strong>: Retry failed requests a few times before considering the operation a failure.</li><li><strong>Circuit Breaker</strong>: Stop retrying when failures reach a certain threshold.</li><li><strong>Fallback Mechanism</strong>: Return cached or default data if both retries and circuit breakers fail.</li></ol><h4>Real-World Use Case</h4><h4>Scenario:</h4><p>A REST API depends on a third-party weather API to fetch current weather data.</p><ol><li>Use <strong>retry logic</strong> to handle temporary timeouts or rate limits.</li><li>Use a <strong>circuit breaker</strong> to block requests to the weather API after repeated failures.</li><li>Use a <strong>fallback mechanism</strong> to serve cached weather data during outages.</li></ol><p><strong>Implementation Example</strong>:</p><pre>from tenacity import retry, stop_after_attempt, wait_exponential<br>from pybreaker import CircuitBreaker<br>from django.core.cache import cache<br>from django.http import JsonResponse<br>import requests<br><br><br># Retry Logic<br>@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10))<br>def fetch_weather_data():<br>    response = requests.get(&quot;https://api.weather.com/v1/current&quot;, timeout=5)<br>    response.raise_for_status()<br>    return response.json()<br><br><br># Circuit Breaker<br>circuit_breaker = CircuitBreaker(fail_max=5, reset_timeout=120)<br><br><br>@circuit_breaker<br>def get_weather_data():<br>    return fetch_weather_data()<br><br><br># View with Fallback<br>def weather_view(request):<br>    cache_key = &quot;weather_data&quot;<br>    cached_data = cache.get(cache_key)<br>    if cached_data:<br>        return JsonResponse(cached_data)<br>    try:<br>        data = get_weather_data()<br>        cache.set(cache_key, data, 60 * 15)  # Cache for 15 minutes<br>        return JsonResponse(data)<br>    except CircuitBreaker.Error:<br>        return JsonResponse({&quot;error&quot;: &quot;Service temporarily unavailable. Please try again later.&quot;}, status=503)<br>    except Exception as e:<br>        return JsonResponse({&quot;error&quot;: &quot;An error occurred&quot;, &quot;details&quot;: str(e)}, status=500</pre><h4>Best Practices for Resilient APIs</h4><ol><li><strong>Identify Critical Dependencies</strong>: Focus on external services or components that significantly impact your API’s functionality.</li><li><strong>Use Exponential Backoff for Retries</strong>: Avoid overwhelming failing services by gradually increasing retry intervals.</li><li><strong>Monitor Circuit Breaker Status</strong>: Log circuit breaker events to monitor failures and recovery.</li><li><strong>Implement Graceful Degradation</strong>: Serve fallback responses or reduced functionality during outages.</li><li><strong>Test Failure Scenarios</strong>: Simulate failures to ensure your retry, circuit breaker, and fallback mechanisms work as expected.</li></ol><p>Building resilient APIs ensures your applications remain robust and user-friendly even when dependencies fail. By implementing <strong>retry logic</strong>, <strong>circuit breakers</strong>, and <strong>fallback mechanisms</strong>, you can gracefully handle failures and provide a seamless experience for your users.</p><p><strong>Key Takeaways</strong>:</p><ul><li><strong>Retry Logic</strong> handles transient failures by reattempting operations.</li><li><strong>Circuit Breakers</strong> prevent cascading failures and reduce load on failing systems.</li><li><strong>Fallback Mechanisms</strong> provide alternative responses to ensure continuity.</li></ul><p>These patterns, when combined, create a reliable API that clients can trust, even under challenging conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd37f523f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>