Learn Python Web Development: Flask, Django, and REST APIs - Textnotes

Learn Python Web Development: Flask, Django, and REST APIs


Build dynamic web applications using Python frameworks. Learn Flask, Django, and create REST APIs with Flask or Django REST Framework with practical examples.

Objective:

Build dynamic, data-driven web applications using Python frameworks, including routing, templates, forms, models, views, and RESTful APIs.

Topics and Examples:

1. Flask Basics: Routing, Templates, Forms

Flask is a lightweight Python web framework ideal for small to medium applications.

Example (Flask App):


from flask import Flask, render_template, request

app = Flask(__name__)

# Route
@app.route('/')
def home():
return "Welcome to Flask!"

# Route with template
@app.route('/hello/<name>')
def hello(name):
return render_template("hello.html", name=name)

# Route with form handling
@app.route('/form', methods=['GET', 'POST'])
def form():
if request.method == 'POST':
name = request.form['name']
return f"Hello, {name}!"
return render_template("form.html")

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

Template Example (hello.html):


<h1>Hello, {{ name }}!</h1>

2. Django Basics: Models, Views, Templates

Django is a full-featured Python web framework ideal for larger applications.

Steps:

  1. Create project:

django-admin startproject myproject
  1. Create app:

python manage.py startapp myapp

Example (Model):


from django.db import models

class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

Example (View):


from django.shortcuts import render
from .models import User

def user_list(request):
users = User.objects.all()
return render(request, 'user_list.html', {'users': users})

Example (Template user_list.html):


<h1>Users</h1>
<ul>
{% for user in users %}
<li>{{ user.name }} - {{ user.age }}</li>
{% endfor %}
</ul>

3. REST APIs with Flask / Django REST Framework

REST APIs allow applications to communicate over HTTP using JSON data.

Flask Example (Simple API):


from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/users', methods=['GET'])
def get_users():
users = [{"name": "Chinmaya", "age": 25}, {"name": "Rout", "age": 26}]
return jsonify(users)

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

Django REST Framework Example:


# serializers.py
from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'name', 'age']

# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
from .serializers import UserSerializer

class UserList(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)

URL mapping (urls.py):


from django.urls import path
from .views import UserList

urlpatterns = [
path('api/users/', UserList.as_view()),
]

This section covers all essential Python web development concepts, including building web applications with Flask and Django, handling routes, templates, forms, models, views, and creating REST APIs for modern web apps.