# Phase 3: Web Application with Flask
"""
Phase 3: Simple Web Application with Flask
Learning Objectives:
- HTTP requests and responses
- Routing
- Templates
- Building a complete web app
"""
from flask import Flask, render_template_string, request, jsonify, redirect, url_for
app = Flask(__name__)
# ============================================================
# LESSON 1: Basic Routes and Responses
# ============================================================
@app.route('/')
def home():
"""Home page"""
html = '''
Lao Python Web App - Lesson 1
🐍 Lao Python Web Application
Lesson 1: Basic Routes
Routes map URLs to Python functions:
@app.route('/')
def home():
return "Hello World!"
Navigation:
About |
Contact |
API Data
'''
return html
@app.route('/about')
def about():
"""About page"""
return 'About
This is a Flask web application for learning Python.
'
@app.route('/contact')
def contact():
"""Contact page"""
return '''
Contact
'''
@app.route('/submit', methods=['POST'])
def submit():
"""Handle form submission"""
name = request.form.get('name', 'Anonymous')
return f'Thanks {name}!
Your message has been received.
Back'
# ============================================================
# LESSON 2: Templates
# ============================================================
TEMPLATE = '''
{{ title }}
{{ title }}
{{ heading }}
{{ content }}
{% if items %}
Items
{% for item in items %}
- {{ item }}
{% endfor %}
{% endif %}
Home
'''
@app.route('/template-demo')
def template_demo():
"""Demonstrate template rendering"""
items = ["Python", "Flask", "HTML", "CSS", "JavaScript"]
return render_template_string(TEMPLATE,
title="Template Demo",
heading="Passing Variables to Templates",
content="Flask templates make it easy to separate logic from presentation.",
items=items)
# ============================================================
# LESSON 3: API Endpoints
# ============================================================
# In-memory "database"
tasks = []
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
"""Get all tasks"""
return jsonify(tasks)
@app.route('/api/tasks', methods=['POST'])
def create_task():
"""Create a new task"""
data = request.get_json()
task = {
"id": len(tasks) + 1,
"title": data.get("title", ""),
"completed": False
}
tasks.append(task)
return jsonify(task), 201
@app.route('/api/tasks/', methods=['PUT'])
def update_task(task_id):
"""Update a task"""
for task in tasks:
if task["id"] == task_id:
data = request.get_json()
task["title"] = data.get("title", task["title"])
task["completed"] = data.get("completed", task["completed"])
return jsonify(task)
return jsonify({"error": "Task not found"}), 404
@app.route('/api/tasks/', methods=['DELETE'])
def delete_task(task_id):
"""Delete a task"""
global tasks
tasks = [t for t in tasks if t["id"] != task_id]
return jsonify({"message": "Task deleted"})
@app.route('/api/data')
def api_data():
"""Simple API endpoint"""
return jsonify({
"message": "Hello from Flask API!",
"timestamp": "2026-10-25",
"version": "1.0"
})
# ============================================================
# LESSON 4: Full Web App - Task Manager
# ============================================================
TASK_MANAGER_TEMPLATE = '''
Task Manager - Lesson 4
📋 Task Manager
{% for task in tasks %}
{% endfor %}
Total: {{ tasks|length }} tasks | Completed: {{ tasks|selectattr("completed")|list|length }} tasks
'''
@app.route('/tasks', methods=['GET'])
def list_tasks():
"""List all tasks"""
return render_template_string(TASK_MANAGER_TEMPLATE, tasks=tasks)
@app.route('/tasks', methods=['POST'])
def add_task():
"""Add a new task"""
title = request.form.get('title', '').strip()
if title:
tasks.append({
"id": len(tasks) + 1,
"title": title,
"completed": False
})
return redirect(url_for('list_tasks'))
@app.route('/tasks//toggle', methods=['GET'])
def toggle_task(task_id):
"""Toggle task completion"""
for task in tasks:
if task["id"] == task_id:
task["completed"] = not task["completed"]
break
return redirect(url_for('list_tasks'))
@app.route('/tasks//delete', methods=['GET'])
def delete_task_route(task_id):
"""Delete a task"""
global tasks
tasks = [t for t in tasks if t["id"] != task_id]
return redirect(url_for('list_tasks'))
# ============================================================
# LESSON 5: Integration
# ============================================================
@app.route('/dashboard')
def dashboard():
"""Dashboard showing all info"""
completed = len([t for t in tasks if t["completed"]])
return jsonify({
"total_tasks": len(tasks),
"completed_tasks": completed,
"pending_tasks": len(tasks) - completed,
"message": "Welcome to your Python Dashboard!"
})
@app.errorhandler(404)
def not_found(e):
"""Handle 404 errors"""
return jsonify({"error": "Page not found"}), 404
# ============================================================
# RUN THE APP
# ============================================================
def run_web_app():
"""Run the Flask web application"""
print("=" * 50)
print("🚀 Flask Web Application")
print("=" * 50)
print("\nRoutes:")
print(" GET / - Home page")
print(" GET /about - About page")
print(" GET /contact - Contact form")
print(" POST /submit - Submit contact form")
print(" GET /template-demo - Template example")
print(" GET /api/data - API endpoint")
print(" GET /tasks - Task manager")
print(" POST /tasks - Add task")
print(" GET /dashboard - Dashboard")
print("\nAPI Endpoints:")
print(" GET /api/tasks - List tasks")
print(" POST /api/tasks - Create task")
print(" PUT /api/tasks/ - Update task")
print(" DELETE /api/tasks/ - Delete task")
print("\n" + "=" * 50)
print("Starting Flask server on http://localhost:5000")
print("=" * 50)
app.run(debug=True, host='0.0.0.0', port=5000)
if __name__ == '__main__':
run_web_app()