Web Development (Flask, Django, FastAPI Basics)
Build modern web backends in Python. Compare lightweight Flask routes, robust Django models, and fast asynchronous APIs in FastAPI.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is Flask and how do you create a basic Flask application?
Flask is a lightweight, micro web framework for building web applications in Python. It's easy to learn and perfect for small to medium-sized applications.
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# Basic route
@app.route('/')
def hello():
return 'Hello, World!'
# Route with parameter
@app.route('/user/<name>')
def greet_user(name):
return f'Hello, {name}!'
# POST request
@app.route('/submit', methods=['POST'])
def submit():
data = request.get_json()
return jsonify({'message': f'Received: {data}'})
# Render HTML template
@app.route('/index')
def index():
return render_template('index.html', title='Home')
# Running the application
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
# HTTP Methods
@app.route('/api/data', methods=['GET', 'POST', 'PUT', 'DELETE'])
def handle_data():
if request.method == 'GET':
return jsonify({'data': 'Sample data'})
elif request.method == 'POST':
return jsonify({'status': 'Created'}), 201
elif request.method == 'PUT':
return jsonify({'status': 'Updated'}), 200
elif request.method == 'DELETE':
return jsonify({'status': 'Deleted'}), 204
Q2. What is Django and what is the Django project structure?
Django is a full-featured, batteries-included web framework for rapid development and clean design. It follows MVT (Model-View-Template) architecture.
myproject/
manage.py # Command-line tool
myproject/
__init__.py
settings.py # Project settings
urls.py # URL routing
wsgi.py # WSGI application
asgi.py # ASGI application
myapp/
migrations/
__init__.py
0001_initial.py
__init__.py
models.py # Database models
views.py # View logic
urls.py # App-level routing
forms.py # Form definitions
tests.py # Unit tests
admin.py # Admin interface
templates/
myapp/
index.html
static/
css/
style.css
js/
script.js
# Example models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
# Example views.py
from django.shortcuts import render
from .models import User
def user_list(request):
users = User.objects.all()
return render(request, 'myapp/users.html', {'users': users})
# Example urls.py
from django.urls import path
from . import views
urlpatterns = [
path('users/', views.user_list, name='user_list'),
]
# Commands
# python manage.py startproject myproject
# python manage.py startapp myapp
# python manage.py makemigrations
# python manage.py migrate
# python manage.py runserver
Q3. What is FastAPI and what are its advantages?
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
# Request model
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
class User(BaseModel):
id: int
username: str
email: str
# GET request
@app.get('/')
async def read_root():
return {'message': 'Hello World'}
# GET with parameter
@app.get('/items/{item_id}')
async def read_item(item_id: int):
return {'item_id': item_id}
# GET with query parameter
@app.get('/users/')
async def read_users(skip: int = 0, limit: int = 10):
return {'skip': skip, 'limit': limit}
# POST request
@app.post('/items/')
async def create_item(item: Item):
return item
# PUT request
@app.put('/items/{item_id}')
async def update_item(item_id: int, item: Item):
return {'item_id': item_id, 'item': item}
# DELETE request
@app.delete('/items/{item_id}')
async def delete_item(item_id: int):
return {'deleted': item_id}
# Path and query parameters combined
@app.get('/users/{user_id}/items/{item_id}')
async def read_user_item(user_id: int, item_id: int, q: str = None):
return {'user_id': user_id, 'item_id': item_id, 'q': q}
# Error handling
@app.get('/users/{user_id}')
async def read_user(user_id: int):
if user_id < 1:
raise HTTPException(status_code=400, detail='Invalid user ID')
return {'user_id': user_id}
# Running: uvicorn main:app --reload
Q4. How do you handle routing and URL patterns in web frameworks?
# Flask routing
from flask import Flask
app = Flask(__name__)
# Basic route
@app.route('/home')
def home():
return 'Home Page'
# Route with parameters
@app.route('/user/<username>')
def user(username):
return f'User: {username}'
# Route with multiple parameters
@app.route('/post/<int:post_id>')
def post(post_id):
return f'Post ID: {post_id}'
# HTTP methods
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
return 'Form submitted'
return 'Submit form'
# Django URL patterns
from django.urls import path, re_path
from . import views
urlpatterns = [
path('home/', views.home, name='home'),
path('user/<str:username>/', views.user, name='user'),
path('post/<int:post_id>/', views.post, name='post'),
re_path(r'^article/(?P<year>[0-9]{4})/$', views.article),
]
# FastAPI routing
from fastapi import FastAPI
app = FastAPI()
@app.get('/home')
async def home():
return {'page': 'Home'}
@app.get('/user/{username}')
async def user(username: str):
return {'username': username}
@app.get('/post/{post_id}')
async def post(post_id: int):
return {'post_id': post_id}
@app.post('/submit')
async def submit(data: dict):
return {'status': 'submitted', 'data': data}
# URL parameter types
# - str: String (default)
# - int: Integer
# - float: Float
# - path: Path including '/'
# - uuid: UUID
# - bool: Boolean
Q5. How do you work with templates in web frameworks?
# Flask templates with Jinja2
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name, age=25)
# hello.html template
# <h1>Hello, {{ name }}!</h1>
# <p>Age: {{ age }}</p>
#
# {% if age >= 18 %}
# <p>You are an adult</p>
# {% else %}
# <p>You are a minor</p>
# {% endif %}
#
# {% for item in items %}
# <p>{{ item }}</p>
# {% endfor %}
# Django templates
from django.shortcuts import render
def view(request):
context = {'name': 'John', 'items': [1, 2, 3]}
return render(request, 'template.html', context)
# template.html
# <h1>Hello, {{ name }}</h1>
#
# {% for item in items %}
# <p>{{ item }}</p>
# {% endfor %}
#
# {% load static %}
# <link rel="stylesheet" href="{% static 'css/style.css' %}">
# Template inheritance
# base.html
# <!DOCTYPE html>
# <html>
# {% block content %}
# {% endblock %}
# </html>
#
# child.html
# {% extends 'base.html' %}
#
# {% block content %}
# <h1>Child content</h1>
# {% endblock %}
# FastAPI with Jinja2
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from starlette.requests import Request
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
templates = Jinja2Templates(directory='templates')
@app.get('/items/{id}')
async def read_item(request: Request, id: str):
return templates.TemplateResponse('item.html', {'request': request, 'id': id})
Q6. How do you work with databases using ORM in web frameworks?
# Django ORM
from django.db import models
from django.utils import timezone
class User(models.Model):
username = models.CharField(max_length=100, unique=True)
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.username
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# Using Django ORM
from .models import User, Post
# Create
user = User.objects.create(username='john', email='john@example.com')
# Read
user = User.objects.get(id=1)
users = User.objects.all()
users = User.objects.filter(is_active=True)
# Update
user.email = 'newemail@example.com'
user.save()
# Delete
user.delete()
# Relationships
post = Post.objects.create(title='My Post', content='Content', author=user)
posts = user.posts.all()
# QuerySet operations
users = User.objects.filter(is_active=True).order_by('-created_at')
count = User.objects.filter(is_active=True).count()
# SQLAlchemy with Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app = Flask(__name__)
db.init_app(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True)
email = db.Column(db.String(100), unique=True)
# Using SQLAlchemy
user = User(username='john', email='john@example.com')
db.session.add(user)
db.session.commit()
user = User.query.filter_by(username='john').first()
users = User.query.all()
user.delete()
db.session.commit()
Q7. How do you implement authentication and authorization?
# Django authentication
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(username=username, password=password)
return redirect('login')
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
def logout_view(request):
logout(request)
return redirect('login')
@login_required(login_url='login')
def dashboard(request):
return render(request, 'dashboard.html')
# Flask authentication with Flask-Login
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
@app.route('/login', methods=['POST'])
def login():
data = request.json
user = User.query.filter_by(username=data['username']).first()
if user and check_password_hash(user.password, data['password']):
login_user(user)
return jsonify({'status': 'logged in'})
@app.route('/dashboard')
@login_required
def dashboard():
return jsonify({'user': current_user.username})
# FastAPI JWT authentication
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthCredentials
from jose import JWTError, jwt
security = HTTPBearer()
def verify_token(credentials: HTTPAuthCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, 'secret_key', algorithms=['HS256'])
return payload
except JWTError:
raise HTTPException(status_code=401, detail='Invalid token')
@app.get('/protected')
async def protected(payload = Depends(verify_token)):
return {'user': payload}
Q8. How do you build RESTful APIs with Python frameworks?
# Flask-RESTful
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
class TodoItem(Resource):
def get(self, id):
return {'id': id, 'task': 'Sample task'}
def post(self, id):
parser = reqparse.RequestParser()
parser.add_argument('task', type=str, required=True)
args = parser.parse_args()
return {'id': id, 'task': args['task']}, 201
def put(self, id):
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)
args = parser.parse_args()
return {'id': id, 'task': args['task']}, 200
def delete(self, id):
return {'status': 'deleted', 'id': id}, 204
api.add_resource(TodoItem, '/todos/<int:id>')
# Django REST Framework
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Todo
from .serializers import TodoSerializer
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
@action(detail=False, methods=['get'])
def recent(self, request):
recent = Todo.objects.order_by('-created_at')[:5]
serializer = self.get_serializer(recent, many=True)
return Response(serializer.data)
# FastAPI with Pydantic
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class TodoCreate(BaseModel):
title: str
description: str = None
class Todo(TodoCreate):
id: int
todos_db = []
@app.get('/todos')
async def get_todos():
return todos_db
@app.get('/todos/{todo_id}')
async def get_todo(todo_id: int):
return next((t for t in todos_db if t['id'] == todo_id), None)
@app.post('/todos', response_model=Todo)
async def create_todo(todo: TodoCreate):
new_todo = {'id': len(todos_db) + 1, **todo.dict()}
todos_db.append(new_todo)
return new_todo
@app.put('/todos/{todo_id}')
async def update_todo(todo_id: int, todo: TodoCreate):
for t in todos_db:
if t['id'] == todo_id:
t.update(todo.dict())
return t
@app.delete('/todos/{todo_id}')
async def delete_todo(todo_id: int):
global todos_db
todos_db = [t for t in todos_db if t['id'] != todo_id]
return {'status': 'deleted'}
Q9. What is middleware and how do you use it?
# Flask middleware
from flask import Flask, request, g
import time
app = Flask(__name__)
# Request/response hook
@app.before_request
def before_request():
g.start_time = time.time()
print(f'Request: {request.method} {request.path}')
@app.after_request
def after_request(response):
duration = time.time() - g.start_time
print(f'Response: {response.status_code} ({duration:.2f}s)')
return response
# Custom middleware
class TimingMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
start = time.time()
result = self.app(environ, start_response)
duration = time.time() - start
print(f'Request took {duration:.2f}s')
return result
app.wsgi_app = TimingMiddleware(app.wsgi_app)
# Django middleware
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f'Processing request: {request.path}')
response = self.get_response(request)
print(f'Generating response with status {response.status_code}')
return response
# In settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'myapp.middleware.CustomMiddleware',
]
# FastAPI middleware
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
import time
app = FastAPI()
class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
response.headers['X-Process-Time'] = str(duration)
return response
app.add_middleware(TimingMiddleware)
# CORS middleware
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:3000'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*'],
)
Q10. How do you deploy Python web applications to production?
# Using Gunicorn (WSGI server)
# Install: pip install gunicorn
# Run: gunicorn -w 4 -b 0.0.0.0:8000 app:app
# or for Django: gunicorn myproject.wsgi:application
# Nginx configuration (reverse proxy)
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# Supervisor (process manager)
[program:myapp]
command=gunicorn -w 4 -b 0.0.0.0:8000 app:app
directory=/home/user/myapp
autostart=true
autorestart=true
# Environment variables (.env)
DATABASE_URL=postgresql://user:password@localhost:5432/db
SECRET_KEY=your-secret-key
DEBUG=False
# Using python-dotenv
from dotenv import load_dotenv
import os
load_dotenv()
db_url = os.getenv('DATABASE_URL')
# Docker deployment
# Dockerfile
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ['gunicorn', '-b', '0.0.0.0:8000', 'app:app']
# docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- '8000:8000'
environment:
- DATABASE_URL=postgresql://...
db:
image: postgres
environment:
- POSTGRES_PASSWORD=password
# Heroku deployment
# Procfile
web: gunicorn myproject.wsgi:application
# AWS deployment
# Using Elastic Beanstalk
eb init myapp
eb create production
eb deploy
# PythonAnywhere deployment
# Upload files via web interface
# Configure WSGI file
# Set up virtual environment
Web Development (Flask, Django, FastAPI Basics)
Build modern web backends in Python. Compare lightweight Flask routes, robust Django models, and fast asynchronous APIs in FastAPI.
What is Flask and how do you create a basic Flask application?
Flask is a lightweight, micro web framework for building web applications in Python. It's easy to learn and pe...
What is Django and what is the Django project structure?
Django is a full-featured, batteries-included web framework for rapid development and clean design. It follows...
What is FastAPI and what are its advantages?
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List app = FastA...
How do you handle routing and URL patterns in web frameworks?
# Flask routing from flask import Flask app = Flask(__name__) # Basic route @app.route('/home') def home():...
How do you work with templates in web frameworks?
# Flask templates with Jinja2 from flask import Flask, render_template app = Flask(__name__) @app.route('/he...
How do you work with databases using ORM in web frameworks?
# Django ORM from django.db import models from django.utils import timezone class User(models.Model): use...
How do you implement authentication and authorization?
# Django authentication from django.contrib.auth import authenticate, login, logout from django.contrib.auth.m...
How do you build RESTful APIs with Python frameworks?
# Flask-RESTful from flask import Flask from flask_restful import Api, Resource, reqparse app = Flask(__name_...
What is middleware and how do you use it?
# Flask middleware from flask import Flask, request, g import time app = Flask(__name__) # Request/response...
How do you deploy Python web applications to production?
# Using Gunicorn (WSGI server) # Install: pip install gunicorn # Run: gunicorn -w 4 -b 0.0.0.0:8000 app:app #...