Python for Web Development
Python is a popular choice for web back ends. Learn the essentials of the language and how a Python web app handles a request using a small Flask example.
Why Python on the Web?
Python's readable syntax, huge library ecosystem and strong data and AI tooling make it a favorite for back ends. Popular frameworks include Flask (minimal), Django (batteries included) and FastAPI (modern and async).
Python Essentials Refresher
A few features you will use constantly: f-strings, list comprehensions, dictionaries and functions with type hints.
from typing import Optional
def greet(name: str, title: Optional[str] = None) -> str:
prefix = f"{title} " if title else ""
return f"Hello, {prefix}{name}!"
users = [
{"name": "Ada", "active": True},
{"name": "Linus", "active": False},
]
active_names = [u["name"] for u in users if u["active"]]
by_name = {u["name"]: u for u in users}
print(greet("Ada", "Dr."), active_names, by_name["Linus"]["active"])Your First Flask App
Flask maps URLs to Python functions. Install it with `pip install flask` inside a virtual environment, then create `app.py`:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.get("/")
def home():
return "<h1>Hello from Flask</h1>" @app.get("/api/greet")
def greet():
name = request.args.get("name", "world")
return jsonify(message=f"Hello, {name}!")
if __name__ == "__main__":
app.run(debug=True, port=5000)Project Hygiene
Set up every project the same way from day one:
- Create a virtual environment: `python -m venv .venv`.
- Pin dependencies in `requirements.txt`.
- Keep secrets in environment variables, never in code.
- Never run `debug=True` in production.
Key Takeaways
- Python offers Flask, Django and FastAPI for building web back ends.
- Type hints, f-strings and comprehensions make code clear and concise.
- Isolate each project in a virtual environment.
- Disable debug mode and keep secrets out of source code in production.
Contact Us
Have a question or feedback? Fill out the form below or reach us directly at support@nvaitraining.com