I built the same app 3 times | Which Python Framework is best? Django vs Flask vs FastAPI

4 min read 1 year ago
Published on Aug 04, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial guides you through building a simple to-do app using three popular Python web frameworks: Flask, FastAPI, and Django. Each framework has its strengths and weaknesses, and by the end of this tutorial, you will have hands-on experience with each, enabling you to make an informed decision for your next Python project.

Chapter 1: Flask

Flask is a lightweight and beginner-friendly framework that's perfect for small to medium-sized applications. Follow these steps to create your to-do app using Flask.

Step 1: Set Up Your Environment

  • Create a virtual environment and activate it.
  • Install Flask and Flask-SQLAlchemy:
    pip install Flask Flask-SQLAlchemy
    

Step 2: Create Your Flask App

  1. Create a new file named app.py.
  2. Import necessary classes and functions:
    from flask import Flask, render_template, request, redirect
    from flask_sqlalchemy import SQLAlchemy
    

Step 3: Configure Your Database

  • Set up the database path (e.g., SQLite):
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
    db = SQLAlchemy(app)
    

Step 4: Define Your Data Model

  • Create a ToDo model:
    class ToDo(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(200), nullable=False)
        complete = db.Column(db.Boolean, default=False)
    

Step 5: Create Routes

  • Add routes for home, adding, updating, and deleting to-dos:
    @app.route('/')
    def home():
        todos = ToDo.query.all()
        return render_template('base.html', todos=todos)
    
    @app.route('/add', methods=['POST'])
    def add_todo():
        title = request.form.get('title')
        new_todo = ToDo(title=title)
        db.session.add(new_todo)
        db.session.commit()
        return redirect('/')
    
    @app.route('/update/<int:id>')
    def update_todo(id):
        todo = ToDo.query.get(id)
        todo.complete = not todo.complete
        db.session.commit()
        return redirect('/')
    
    @app.route('/delete/<int:id>')
    def delete_todo(id):
        todo = ToDo.query.get(id)
        db.session.delete(todo)
        db.session.commit()
        return redirect('/')
    

Step 6: Create Templates

  • Create a templates folder and a base.html file with a simple HTML form and display logic using Jinja2 templating.

Step 7: Run Your Flask App

  • Set environment variables and run:
    export FLASK_APP=app.py
    export FLASK_ENV=development
    flask run
    

Chapter 2: FastAPI

FastAPI is known for its speed and built-in features like automatic documentation and type validation. Follow these steps to build your to-do app with FastAPI.

Step 1: Set Up Your Environment

  • Create a new virtual environment and activate it.
  • Install FastAPI and an ASGI server (Uvicorn):
    pip install fastapi uvicorn python-multipart sqlalchemy jinja2
    

Step 2: Create Your FastAPI App

  1. Create three files: app.py, models.py, and database.py.
  2. In app.py, import FastAPI and create an app instance:
    from fastapi import FastAPI, Depends, Request
    from fastapi.templating import Jinja2Templates
    from sqlalchemy.orm import Session
    

Step 3: Define Your Data Model

  • In models.py, define your ToDo class:
    from sqlalchemy import Column, Integer, String, Boolean
    from database import Base
    
    class ToDo(Base):
        __tablename__ = 'todos'
        id = Column(Integer, primary_key=True, index=True)
        title = Column(String, index=True)
        complete = Column(Boolean, default=False)
    

Step 4: Create Database Session

  • In database.py, set up your database configuration and session creation.

Step 5: Create Routes

  • Add routes in app.py for home, adding, updating, and deleting to-dos:
    @app.get("/")
    async def read_todos(request: Request, db: Session = Depends(get_db)):
        todos = db.query(ToDo).all()
        return templates.TemplateResponse("base.html", {"request": request, "todos": todos})
    
    @app.post("/add")
    async def create_todo(title: str, db: Session = Depends(get_db)):
        new_todo = ToDo(title=title)
        db.add(new_todo)
        db.commit()
        return RedirectResponse(url='/', status_code=303)
    

Step 6: Run Your FastAPI App

  • Start the server using Uvicorn:
    uvicorn app:app --reload
    

Chapter 3: Django

Django is a full-stack framework that provides a lot of built-in features. Follow these steps to create your to-do app with Django.

Step 1: Set Up Your Environment

  • Create a virtual environment and activate it.
  • Install Django:
    pip install django
    

Step 2: Create Your Django Project

  • Start a new project:
    django-admin startproject todo_app
    cd todo_app
    python manage.py startapp todo_list
    

Step 3: Add Your App to Settings

  • Add the todo_list app to the INSTALLED_APPS in settings.py.

Step 4: Define Your Data Model

  • Create a ToDo model in todo_list/models.py:
    from django.db import models
    
    class ToDo(models.Model):
        title = models.CharField(max_length=200)
        complete = models.BooleanField(default=False)
    

Step 5: Create Views and URL Patterns

  • Define views in todo_list/views.py and set up URLs in todo_list/urls.py.

Step 6: Create and Apply Migrations

  • Run the following commands:
    python manage.py makemigrations
    python manage.py migrate
    

Step 7: Create an Admin User

  • Create a superuser for the admin panel:
    python manage.py createsuperuser
    

Step 8: Start the Django Server

  • Run your Django app:
    python manage.py runserver
    

Conclusion

In this tutorial, you learned how to build a simple to-do app using Flask, FastAPI, and Django. Each framework offers unique advantages, so consider your project's requirements and your familiarity with each tool when making your choice. You can find the complete code for each app on GitHub, linked in the video description. Happy coding!