Deployment Docker, Heroku, AWS

Python Web Development: Flask vs Django

Python Web Development: Flask vs Django

Build your first web app with Python!

Option 1: Flask (Microframework)

Ideal for: Small apps, APIs, and projects needing flexibility.

1. Setup

pip install flask

2. Minimal Flask App

# app.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask! 🚀"

if __name__ == "__main__":
    app.run(debug=True)

3. Run the App

flask run
# Visit http://localhost:5000

4. Add Templates & Dynamic Routing

Folder Structure:

my_flask_app/
├── app.py
├── templates/
│    └── index.html
└── static/
     └── style.css

app.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html", name="Alex")

@app.route("/user/")
def user_profile(username):
    return f"Welcome, {username}!"

templates/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Option 2: Django (Batteries-Included)

Ideal for: Larger apps with built-in ORM, admin panel, and scalability.

1. Setup

pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp myapp

2. Create a Simple Blog

Define Model (myapp/models.py):

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Run Migrations:

python manage.py makemigrations
python manage.py migrate

Create View (myapp/views.py):

from django.shortcuts import render
from .models import Post

def home(request):
    posts = Post.objects.all()
    return render(request, "myapp/home.html", {"posts": posts})

Add Template (myapp/templates/myapp/home.html):

<!DOCTYPE html>
<html>
<head>
    <title>Django Blog</title>
</head>
<body>
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
        <p>{{ post.content }}</p>
    {% endfor %}
</body>
</html>

Configure URLs (myapp/urls.py):

from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
]

Include in Main URLs (myproject/urls.py):

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("myapp.urls")),
]

Run the Server:

python manage.py runserver
# Visit http://localhost:8000

Real-World Examples

Flask: Weather App

@app.route("/weather")
def weather():
    city = request.args.get("city", "London")
    # Call weather API here
    return render_template("weather.html", city=city)

Django: Admin Panel

Register models in myapp/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Access at http://localhost:8000/admin.

Key Differences

Feature Flask Django
Complexity Lightweight, flexible Opinionated, feature-rich
ORM Optional (SQLAlchemy) Built-in
Admin Interface Requires extensions Built-in
Use Case APIs, microservices Full-stack apps, CMS, e-commerce

Common Mistakes

  • Flask: Forgetting render_template() or misconfiguring routes.
  • Django: Not running migrations after model changes.
  • Both: Not using virtual environments.

Best Practices

  • Use Virtual Environments:
  • python -m venv venv
    source venv/bin/activate  # Linux/Mac
    venv\Scripts\activate     # Windows
  • Security:
    • Never run DEBUG=True in production (Django).
    • Sanitize user inputs to prevent SQL injection.
  • Project Structure:
    • Flask: Separate routes, models, and templates.
    • Django: Follow the "apps" modular structure.

Next Steps

  • Add Databases:
    • Flask: Use SQLAlchemy or Flask-SQLAlchemy.
    • Django: Use built-in ORM.
  • User Authentication:
    • Flask: Flask-Login.
    • Django: Built-in django.contrib.auth.
  • Deploy:
    • Platforms: Heroku, AWS, PythonAnywhere.

Which to Choose?

  • Flask: Simple APIs, microservices, or custom projects.
  • Django: Blogs, e-commerce, or apps needing admin/ORM out-of-the-box.

Post a Comment

Previous Post Next Post