Python Web Development:
Flask vs Django & REST APIs
A comprehensive Q&A guide covering micro vs full-stack frameworks, building RESTful APIs, and production best practices.
What is Flask?
Flask is a lightweight, micro web framework for Python, designed for simplicity and flexibility. It provides the essentials for building web applications and APIs without imposing strict structure, making it ideal for small to medium projects. Flask is based on the Werkzeug WSGI toolkit and Jinja2 templating engine, allowing developers to extend it with extensions as needed.
Key Features:
- Minimalist core with easy routing (
@app.route). - Built-in development server and debugger.
- Support for templates, forms, and blueprints for modular apps.
- Extensions for authentication, ORM (e.g., SQLAlchemy), and REST APIs (e.g., Flask-RESTful).
Use Case
Prototyping APIs, simple web apps, or microservices.
Pros
Fast to learn, flexible, lightweight.
Cons
Requires more manual setup for complex features compared to full-stack frameworks.
Can you give an example of a basic Flask application?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "<h1>Welcome to Flask!</h1>"
@app.route('/hello/<name>')
def hello(name):
return f"<h1>Hello, {name}!</h1>"
if __name__ == "__main__":
app.run(debug=True)
python flask_basic.py; access http://localhost:5000 in a browser. debug=True enables auto-reloading and error pages.What is Django?
Django is a high-level, full-stack web framework for Python that encourages rapid development and clean, pragmatic design. It follows the "batteries-included" philosophy, providing built-in features for ORM, authentication, admin interface, and more. Django is based on the MTV (Model-Template-View) pattern and is suitable for large-scale applications.
Key Features:
- ORM for database abstraction.
- Admin interface for data management.
- URL routing, forms, and templating (Django Template Language).
- Security features (e.g., CSRF protection, SQL injection prevention).
- Apps for modular development.
Use Case
Complex web apps like CMSs or e-commerce sites.
Pros
Robust, scalable, secure out-of-the-box.
Cons
Steeper learning curve due to its comprehensiveness.
Can you give an example of a basic Django application?
# Setup:
# pip install Django
# django-admin startproject myproject
# python manage.py runserver
# myproject/urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('hello/<str:name>/', views.hello, name='hello'),
]
# myproject/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("<h1>Welcome to Django!</h1>")
def hello(request, name):
return HttpResponse(f"<h1>Hello, {name}!</h1>")
python manage.py runserver; access http://localhost:8000 in a browser.What are RESTful APIs, and how do you build them with Python?
RESTful APIs (Representational State Transfer) are stateless, HTTP-based interfaces for accessing resources using standard methods. They follow principles like uniform interface and resource identification via URLs.
Key Concepts:
- Resources: Identified by URLs (e.g.,
/users/1). - HTTP Methods: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
- Status Codes: 200 (OK), 201 (Created), 404 (Not Found), etc.
- Formats: Typically JSON for data exchange.
- Flask: Use
@app.routewith HTTP methods; extensions like Flask-RESTful for advanced features. - Django: Use Django REST Framework (DRF) for serializers, views, and routing.
Can you give an example of a RESTful API with Flask and Django?
Flask REST API:
from flask import Flask, jsonify, request
app = Flask(__name__)
employees = [
{"id": 1, "name": "Krishna", "salary": 60000},
{"id": 2, "name": "Kristal", "salary": 55000}
]
@app.route('/employees', methods=['GET'])
def get_employees():
return jsonify(employees), 200
@app.route('/employees/<int:emp_id>', methods=['GET'])
def get_employee(emp_id):
emp = next((e for e in employees if e['id'] == emp_id), None)
if emp:
return jsonify(emp), 200
return jsonify({"error": "Employee not found"}), 404
@app.route('/employees', methods=['POST'])
def add_employee():
new_emp = request.get_json()
new_emp['id'] = len(employees) + 1
employees.append(new_emp)
return jsonify(new_emp), 201
if __name__ == "__main__":
app.run(debug=True)
Django REST Framework (DRF):
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('employees/', views.EmployeeList.as_view(), name='employee-list'),
path('employees/<int:pk>/', views.EmployeeDetail.as_view(), name='employee-detail'),
]
# views.py
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
employees = [
{"id": 1, "name": "Krishna", "salary": 60000},
{"id": 2, "name": "Kristal", "salary": 55000}
]
class EmployeeList(APIView):
def get(self, request):
return Response(employees)
def post(self, request):
new_emp = request.data
new_emp['id'] = len(employees) + 1
employees.append(new_emp)
return Response(new_emp, status=status.HTTP_201_CREATED)
class EmployeeDetail(APIView):
def get(self, request, pk):
emp = next((e for e in employees if e['id'] == pk), None)
if emp:
return Response(emp)
return Response({"error": "Employee not found"}, status=status.HTTP_404_NOT_FOUND)
Flask vs Django + Common Mistakes & Best Practices
Framework Comparison:
| Aspect | Flask | Django |
|---|---|---|
| Type | Micro framework | Full-stack framework |
| Philosophy | Flexible, minimal | Batteries-included |
| Best For | APIs, microservices, small apps | Large, complex web apps |
| ORM | Via extensions (SQLAlchemy) | Built-in Django ORM |
| Admin Panel | Not included | Built-in |
| Learning Curve | Gentle | Steeper |
Common Mistakes:
- Flask: Not using blueprints for large apps, leading to monolithic code.
- Flask: Ignoring error handling, causing 500 errors.
- Django: Overusing admin interface for production without customization.
- Django: Not configuring URLs properly, causing 404 errors.
- REST APIs: Not validating input data, risking security issues.
- General: Hardcoding configurations instead of using environment variables.
Best Practices:
- Use virtual environments and
.envfiles for secrets. - Follow framework conventions (blueprints in Flask, apps in Django).
- Implement proper error handling and logging.
- Validate and sanitize all input data.
- Use version control and deploy with gunicorn/uwsgi + nginx.