Python
  • Intro.
  • Catalogue
  • Chapter 1: Introduction to Python
  • Chapter 2: Python Syntax and Fundamentals
    • Chapter: Variables and Data Types in Python
  • Chapter 3: Control Flow
  • Chapter 4: Functions
  • Chapter 5: Data Structures
  • Chapter 6: Object-Oriented Programming (OOP)
  • Chapter 7: Modules and Packages
  • Chapter 8: File Handling
  • Chapter 9: Error and Exception Handling
  • Chapter 10: Working with Databases
  • Chapter 11: Iterators and Generators
  • Chapter 12: Decorators and Context Managers
  • Chapter 13: Concurrency and Parallelism
  • Chapter 14: Testing and Debugging
  • Chapter 15: Web Development with Python
  • Chapter 16: Data Science and Machine Learning with Python
  • Chapter 17: Working with APIs
  • Chapter 18: Automation with Python
  • Chapter 19: Python and Cloud/DevOps
  • Chapter 20: Python and IoT
  • Appendices
Powered by GitBook
On this page

Chapter 15: Web Development with Python

Web development is one of the most popular applications of Python. Frameworks like Flask and Django make it easy to build robust web applications and APIs. This chapter provides an overview of these frameworks and introduces key concepts for web development.

Flask: A Lightweight Web Framework

Flask is a microframework that provides the essentials for building web applications without additional overhead.

Installing Flask

pip install flask

Creating a Basic Flask App

from flask import Flask

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(debug=True)
  • @app.route("/"): Defines the URL path for the route.

  • app.run(debug=True): Runs the development server with debugging enabled.

Handling Routes and Parameters

@app.route("/greet/<name>")
def greet(name):
    return f"Hello, {name}!"

Django: A Full-Featured Web Framework

Django is a high-level framework that includes built-in support for databases, authentication, and more.

Installing Django

pip install django

Creating a Django Project

  1. Start a project:

    django-admin startproject myproject
  2. Navigate to the project directory and run the server:

    cd myproject
    python manage.py runserver

Creating a Django App

  1. Create an app:

    python manage.py startapp myapp
  2. Register the app in INSTALLED_APPS (in settings.py):

    INSTALLED_APPS = [
        'myapp',
    ]
  3. Define a view in myapp/views.py:

    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello, Django!")
  4. Map the view to a URL in myapp/urls.py:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.home, name='home'),
    ]
  5. Include the app's URL configuration in myproject/urls.py:

    from django.urls import include, path
    
    urlpatterns = [
        path('', include('myapp.urls')),
    ]

Building REST APIs

REST (Representational State Transfer) APIs allow communication between client and server applications.

Flask API Example

from flask import Flask, jsonify, request

app = Flask(__name__)

data = ["item1", "item2", "item3"]

@app.route("/api/items", methods=["GET"])
def get_items():
    return jsonify(data)

@app.route("/api/items", methods=["POST"])
def add_item():
    new_item = request.json.get("item")
    data.append(new_item)
    return jsonify({"message": "Item added", "items": data})

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

Django API Example with Django REST Framework

  1. Install Django REST Framework:

    pip install djangorestframework
  2. Add it to INSTALLED_APPS:

    INSTALLED_APPS = [
        'rest_framework',
    ]
  3. Define a serializer in myapp/serializers.py:

    from rest_framework import serializers
    
    class ItemSerializer(serializers.Serializer):
        name = serializers.CharField(max_length=100)
  4. Define a view in myapp/views.py:

    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    class ItemView(APIView):
        def get(self, request):
            return Response(["item1", "item2", "item3"])
    
        def post(self, request):
            return Response({"message": "Item added", "item": request.data})
  5. Add a URL mapping in myapp/urls.py:

    from django.urls import path
    from .views import ItemView
    
    urlpatterns = [
        path('api/items/', ItemView.as_view(), name='item-list'),
    ]

Templates in Flask and Django

Both frameworks support templates for rendering HTML dynamically.

Flask Template Example

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html", title="Welcome")
  • templates/home.html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>Welcome to Flask!</h1>
    </body>
    </html>

Django Template Example

  • Create a template in myapp/templates/myapp/home.html:

    <!DOCTYPE html>
    <html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>Welcome to Django!</h1>
    </body>
    </html>
  • Update the view in myapp/views.py:

    from django.shortcuts import render
    
    def home(request):
        return render(request, 'myapp/home.html', {"title": "Welcome"})

Exercises

Exercise 1:

Create a Flask application with routes for displaying a list of items and adding a new item.

Solution:

from flask import Flask, jsonify, request

app = Flask(__name__)
data = []

@app.route("/items", methods=["GET"])
def get_items():
    return jsonify(data)

@app.route("/items", methods=["POST"])
def add_item():
    item = request.json.get("item")
    data.append(item)
    return jsonify({"message": "Item added", "items": data})

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

Exercise 2:

Create a Django project and app to display a "Hello, World!" message on the homepage.

Solution:

  1. Create a Django project and app (helloapp).

  2. Define a view in helloapp/views.py:

    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello, World!")
  3. Map the view in helloapp/urls.py and include it in the project URL configuration.

Best Practices

  1. Use virtual environments to isolate project dependencies.

  2. Keep your code organized using the MVC (Model-View-Controller) pattern.

  3. Secure your web applications with proper input validation and error handling.

  4. Use environment variables for sensitive data like API keys and database credentials.

  5. Follow REST principles when designing APIs.

In the next chapter, we will explore data science and machine learning with Python, including libraries like numpy, pandas, and scikit-learn.

PreviousChapter 14: Testing and DebuggingNextChapter 16: Data Science and Machine Learning with Python

Last updated 5 months ago