Tips for navigating the slides:
Python Cloud Advocate at Microsoft
Volunteer instructor for GDI (GirlDevelopIt)
Formerly: UC Berkeley, Coursera, Khan Academy, Google
Find me online at:
Mastodon | @pamelafox@fosstodon.org |
@pamelafox | |
www.linkedin.com/in/pamelafox | |
GitHub | www.github.com/pamelafox |
Website | pamelafox.org |
Today we'll talk about...
For the frontend:
For the backend:
Python is a great language for teaching web development because:
The current version of Python is 3.12. See python.org/downloads for the latest version of Python.
Try not to stay behind more than a year. New versions are faster due to efforts of the Faster CPython team.
New versions also have better debugging messages:
schwarzschild_blackhole = 1916
>>> schwarschild_blackhole
Traceback (most recent call last):
File "", line 1, in
NameError: name 'schwarschild_blackhole' is not defined.
Did you mean: schwarzschild_blackhole?
In a company, the goal of a dev environment is to make it easy for a developer to work on multiple projects, and for all developers on a particular project to have the same environment.
An good dev environment is replicable and isolated.
Options:
Python has a built-in tool for creating virtual environments:
% python -m venv .venv
% source .venv/bin/activate
Then you can install dependencies with pip:
(.venv) % python -m pip install numpy
(.venv) % python -m pip install -r requirements.txt
Virtual environments are good for isolating Python dependencies, but they do not isolate the rest of the environment.
Dev Containers define a complete development environment for a project,
using a .devcontainer/devcontainer.json
file
that configures a Docker image and other settings.
Benefits:
To use a repository that has a dev container defined, first install:
Then, open the repository in VS Code, and you will be prompted to "Reopen in Container". Select that option and wait... (First build takes time ⏱️)
GitHub Codespaces is a cloud-based development environment that can be used to develop any GitHub repository.
If no devcontainer.json
is in the repository, it will try using the default "universal" container.
If a devcontainer.json
is present, it will use that.
Start from existing dev container definitions and modify as needed:
Learn more about dev containers: containers.dev
Python has a few modern web frameworks that are popular:
Flask is a lightweight web framework that includes routing and template rendering.
from flask import Flask, render_template
app = Flask(__name__)
@app.get('/')
def hello_world():
return render_template('index.html')
For more functionality, bring in extensions like: Flask-SQLAlchemy for database ORM, WTForms for forms, etc.
Quart is an asynchronous version of Flask.
Sample apps: Basic Flask server, Flask + DB example
Django is an opinionated web framework with:
Sample apps: Django quiz app
FastAPI is an async framework for building APIs (with auto-generated documentation) based on standard Python type hints.
from fastapi import FastAPI
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
@app.post("/items/")
async def create_item(item: Item):
return item
Sample apps: Simple FastAPI app, Static Maps API
We need async to build modern web apps that support concurrency.
A web app without async:
A web app with async can handle new requests while waiting for an I/O op:
Any app with slow network requests, DB queries, or file reads can benefit.
See also: FastAPI tutorial on async
I like to teach all of them, so students can become framework-agnostic and choose the best tool for the job.
But if you have to choose one...
Get workshop materials for Flask, Django, and FastAPI from https://github.com/pamelafox/python-web-apps
👩🏼🏫 Attend our live streams covering those workshops in June.
https://aka.ms/PWA/RSVP-B
Two main types of databases:
PostgreSQL is a popular open-source relational database that supports JSON, XML, and other data types.
CREATE TABLE cities (
name varchar(80),
location point
);
INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)');
SELECT name FROM cities WHERE location <@ circle '((0,0), 300)';
There are many popular extensions for PostgreSQL like PostGIS for geospatial data and pgvector for vector similarity search.
Python libraries for PostgreSQL: psycopg (driver), SQLAlchemy (ORM)
Playgrounds: PostgreSQL playground, pgvector playground
ORMs (Object-Relational Mappers) like SQLAlchemy and Django's ORM make it easier to work with databases and protect against SQL injection attacks.
Example code using SQLAlchemy ORM:
class BlogPost(Base):
__tablename__ = "blog_post"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(30))
content: Mapped[str]
b = BlogPost(title="My first post", content="Hello world")
session.add(b)
session.commit()
Playgrounds: PostgreSQL playground, pgvector playground
MongoDB is a popular source-available NoSQL database that stores data in JSON-like documents.
post = {
"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"]
}
db.posts.insert_one(post)
Python libraries for MongoDB: pymongo (driver), beanie (ODM)
Redis is an open-source in-memory data structure store that can be used as a database, cache, or message broker.
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('session-id-123', 'user-id-456')
Python libraries for Redis: redis-py (driver)
My personal preference is to teach PostgreSQL, because it can be used in so many different types of applications, and most students do not need the extreme scalability of NoSQL databases or the fast caching abilities of Redis.
Also, SQL is a good skill to have, given the popularity of SQL databases.
Get workshop materials for "Databases" from https://github.com/pamelafox/python-web-apps
👩🏼🏫 Attend our live stream covering the workshop in June.
https://aka.ms/PWA/RSVP-B
The Docker engine runs multiple Docker containers, where each container is an isolated environment.
A container image is a software package that includes
everything needed to run an application.
A container is a running instance of a container image.
A Dockerfile is a text file that contains instructions for building a Docker image.
FROM python:3.11
WORKDIR /code
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 50505
ENTRYPOINT ["gunicorn", "-c", "gunicorn.conf.py", "app:app"]
Local development:
Production:
Get workshop materials for "Containerization" from https://github.com/pamelafox/python-web-apps
👩🏼🏫 Attend our live stream covering the workshop in June.
https://aka.ms/PWA/RSVP-B
Check out container.training for more materials.
Modern coding assistance tools can help students write better code, faster, and can make coding more accessible.
Intellisense is an IDE feature that provides code completions, parameter info, quick info, and member lists.
In VS Code use the Python extension which includes the Pylance extension.
Debuggers help you step through code, set breakpoints, and inspect variables.
In VS Code, use the Python extension which includes the Debugpy extension.
A linter identifies code style issues as well as possible bugs. The most common linter is flake8 but there's a new faster linter called ruff.
Run ruff
on a file or folder:
% python -m ruff check .
In VS Code, use the Ruff extension for in-IDE linting.
A formatter automatically formats code to a consistent style. The most popular formatter is black, which is PEP 8 compliant and fairly opinionated.
Run black on a file or folder:
python3 -m black --verbose .
In VS Code, use the Black extension for in-IDE formatting.
You can also use ruff as a formatter:
python -m ruff format .
GitHub Copilot works particularly well for writing web apps, since there are many common patterns across web apps.
Getting started with GitHub Copilot for students:
aka.ms/Copilot4Students
Get Copilot today! gh.io/sigcse2024
📖 Blog: Best practices for prompting GitHub Copilot in VS Code
🎥 Video: Best practices for prompting GitHub Copilot in VS Code
Find out ASAP if Copilot made something up:
Should you start at top or bottom? Start somewhere, atleast!
Most commonly used libraries:
Code coverage is a measure of how much of your code is tested by your tests, either in terms of lines of code or branches of code.
Set a minimum threshold for code coverage, and use a tool like coverage to measure it.
def test_destinations(page: Page, live_server_url: str):
page.goto(live_server_url)
page.get_by_role("link", name="Destinations").click()
expect(page).to_have_title("ReleCloud - Destinations")
check_for_violations(page)
python -m pytest
or python -m unittest
For student projects, you could give them the tests and ask them to write the code to pass the tests, or you could give them the code and ask them to write the tests - or both!
Get workshop materials for "Testing Web Apps" from github.com/pamelafox/python-web-apps
👩🏼🏫 Attend our live stream covering the workshops in June.
https://aka.ms/PWA/RSVP-B
Cloud deployment is a good way to:
Azure is a good choice for students because of the free credits and the many services that are available.
Azure Container Apps | Azure Functions | |||
Azure Kubernetes Service | Container Management | Azure App Service | Serverless | |
Environment | Containers | PaaS | ||
Cloud | Azure |
For students, App Service or Container Apps are good options.
Most web apps need more than just hosting:
Databases | PostGreSQL, MySQL, CosmosDB, ... |
---|---|
Storage | Blob Storage, Files, Archive Storage, ... |
Networking | DNS Zone, Virtual Network, VPN Gateway, ... |
Caching | CDN, Front Door, ... |
Security | Key Vault, Security Center, ... |
Machine Learning + AI | OpenAI, Translator, Bot Service, Computer Vision, ... |
...and more! |
UI based:
Command based:
az webapp up --name myapp --sku F1
azd up
All of these repos are set up for easy Azure deployment.
App Service | Functions | Container Apps | |
---|---|---|---|
Django + PG |
Travel app
Quiz app + VNET: Reviews app | Travel app | |
Flask | Simple App | Simple API |
Simple App Simple API + CDN: App + CDN: API |
+ PostgreSQL |
Travel app Quiz app + VNET: Reviews app |
Travel app Surveys App | |
FastAPI | Salary API |
Simple
API + APIM: Simple API + CDN: Maps API | Simple API |
+ PostgreSQL | Travel app | Travel app | |
+ MongoDB | Todo API | Todo API | Todo API |
Get Copilot today! 🔗 gh.io/sigcse2024
Get Azure today! 🔗 aka.ms/azureforstudents
Receive a regular digest of relevant technical content, events, and training.
Get the best of the newest resources, tools, and guidance to help developers quickly build and deploy on Azure.
Get links from today's session.
Grab the slides @ aka.ms/teaching-python-web-sigcse
Find me online at:
Mastodon | @pamelafox@fosstodon.org |
@pamelafox | |
GitHub | www.github.com/pamelafox |
Website | pamelafox.org |