21

Day 21: Web Development Basics

Chapter 21 • Advanced

60 min

Web development with Python allows you to create dynamic websites and web applications. Python has excellent frameworks for web development.

What is Web Development?

Web development involves creating websites and web applications that run on the internet. It includes both frontend (what users see) and backend (server-side logic).

Python Web Frameworks:

  • Flask - Lightweight and flexible micro-framework
  • Django - Full-featured web framework
  • FastAPI - Modern, fast framework for APIs
  • Pyramid - Flexible, scalable framework
  • Bottle - Simple micro-framework

Web Development Concepts:

  • HTTP - Protocol for web communication
  • REST API - Representational State Transfer
  • JSON - JavaScript Object Notation for data exchange
  • CRUD - Create, Read, Update, Delete operations
  • MVC - Model-View-Controller architecture

Flask Basics:

  • Routes - URL patterns that trigger functions
  • Templates - HTML files with dynamic content
  • Request handling - Process incoming data
  • Response generation - Send data back to client
  • Static files - CSS, JavaScript, images

Benefits of Python Web Development:

  • Rapid Development - Quick to build and deploy
  • Large Community - Lots of resources and libraries
  • Scalable - Can handle large applications
  • Versatile - Frontend and backend capabilities

Hands-on Examples

Basic Flask Application

# Install Flask: pip install flask
from flask import Flask, render_template, request, jsonify

# Create Flask app
app = Flask(__name__)

# Route for home page
@app.route('/')
def home():
    return "Welcome to Python Web Development!"

# Route with parameters
@app.route('/user/<name>')
def user(name):
    return f"Hello, {name}!"

# Route for API endpoint
@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
    if request.method == 'GET':
        return jsonify({
            'message': 'This is a GET request',
            'data': [1, 2, 3, 4, 5]
        })
    elif request.method == 'POST':
        data = request.get_json()
        return jsonify({
            'message': 'Data received successfully',
            'received_data': data
        })

# Route for HTML template
@app.route('/template')
def template_example():
    users = ['Priya', 'Marcus', 'Sofia']
    return render_template('users.html', users=users)

# Error handling
@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Page not found'}), 404

# Run the app
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

This Flask application demonstrates basic web development concepts including routes, API endpoints, templates, and error handling.