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

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

Installing Django

Creating a Django Project

  1. Start a project:

  2. Navigate to the project directory and run the server:

Creating a Django App

  1. Create an app:

  2. Register the app in INSTALLED_APPS (in settings.py):

  3. Define a view in myapp/views.py:

  4. Map the view to a URL in myapp/urls.py:

  5. Include the app's URL configuration in myproject/urls.py:

Building REST APIs

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

Flask API Example

Django API Example with Django REST Framework

  1. Install Django REST Framework:

  2. Add it to INSTALLED_APPS:

  3. Define a serializer in myapp/serializers.py:

  4. Define a view in myapp/views.py:

  5. Add a URL mapping in myapp/urls.py:

Templates in Flask and Django

Both frameworks support templates for rendering HTML dynamically.

Flask Template Example

  • templates/home.html:

Django Template Example

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

  • Update the view in myapp/views.py:

Exercises

Exercise 1:

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

Solution:

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:

  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.

Last updated