Writing Python Web Apps with
VS Code

Demo app

github.com/pamelafox/django-quiz-app/
aka.ms/django-quiz-app

Screenshot of Quiz page

Built with Django 🎸 + PostgreSQL 🐘

GitHub Codespaces

Codespaces is an online development environment.

Open GitHub repo in Codespaces by clicking Code button, selecting Codespaces tab, and clicking Create codespace on main.

Then wait patiently... ☺️

Screenshot of Codespace tab

60 hours of free usage each month.
πŸ”— Tips for optimizing quotas

Dev Containers

Dockerfile


                ARG IMAGE=python:3
                FROM --platform=amd64 mcr.microsoft.com/devcontainers/${IMAGE}

                RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
                    && apt-get -y install --no-install-recommends postgresql-client \
                        && apt-get clean -y && rm -rf /var/lib/apt/lists/*
                

πŸ”— Using container image from mcr.microsoft.com devcontainer Python images

πŸ‘οΈ See full file: Dockerfile

Docker-compose.yaml


                    services:
                      app:
                        build:
                          context: ..
                          dockerfile: .devcontainer/Dockerfile
                          args:
                            IMAGE: python:3.11
                        volumes:
                          - ..:/workspace:cached
                        command: sleep infinity
                        network_mode: service:db
                      db:
                        image: postgres:latest
                        restart: unless-stopped
                        volumes:
                          - postgres-data:/var/lib/postgresql/data
                        environment:
                          POSTGRES_DB: app
                          POSTGRES_USER: app_user
                          POSTGRES_PASSWORD: app_password
                    volumes:
                      postgres-data:
                

πŸ‘οΈ See full file: docker-compose.yaml

devcontainer.json

Configuration needed to work with the Docker files:


                    ...
                    "dockerComposeFile": "docker-compose.yml",
                    "service": "app",
                    "workspaceFolder": "/workspace",
                    "forwardPorts": [8000, 5432],
                    "portsAttributes": {
                        "8000": {"label": "Django port", "onAutoForward": "notify"},
                        "5432": {"label": "PostgreSQL port", "onAutoForward": "silent"}
                    },
                    ...
                

πŸ‘οΈ See full file: devcontainer.json

devcontainer.json

Recommended extensions:


                    ...
                    "extensions": [
                        "ms-python.python",
                        "ms-python.vscode-pylance",
                        "charliermarsh.ruff",
                        "mtxr.sqltools",
                        "mtxr.sqltools-driver-pg",
                    ]
                    ...
                

πŸ‘οΈ See full file: devcontainer.json

devcontainer.json

Configuring extensions:


                    ...
                    "sqltools.connections": [
                        {
                            "name": "Container database",
                            "driver": "PostgreSQL",
                            "previewLimit": 50,
                            "server": "localhost",
                            "port": 5432,
                            "database": "app",
                            "username": "app_user",
                            "password": "app_password"
                        }
                    ],
                    ...
                

πŸ‘οΈ See full file: devcontainer.json

devcontainer.json

Configuring VS Code:


                    ...
                    "python.defaultInterpreterPath": "/usr/local/bin/python",
                    "python.linting.enabled": true,
                    "python.testing.pytestEnabled": true,
                    "python.testing.unittestEnabled": false,
                    "python.formatting.provider": "black",
                    "[python]": {
                        "editor.formatOnSave": true,
                        "editor.codeActionsOnSave": {
                            "source.fixAll": true
                        }
                    },
                    "files.exclude": {
                        "**/*.coverage": true,
                        ".ruff_cache": true
                    }
                    ...
                

πŸ‘οΈ See full file: devcontainer.json

VS Code customizations

VS Code tasks

In .vscode/tasks.json:


                    {
                        "version": "2.0.0",
                        "tasks": [ {
                          "label": "Apply migrations",
                          "type": "shell",
                          "command": "./src/manage.py migrate",
                          "problemMatcher": [],
                          "presentation": {
                            "reveal": "always",
                            "panel": "dedicated"
                          }
                        },
                    ...
                    

πŸ‘οΈ See full file: tasks.json

VS Code Debugging

.vscode/launch.json:


                { "version": "0.2.0",
                  "configurations": [{
                        "name": "Python: Django",
                        "type": "python",
                        "request": "launch",
                        "program": "${workspaceFolder}/src/manage.py",
                        "args": [
                            "runserver"
                        ],
                        "django": true,
                        "justMyCode": true
                    }]}
                

In settings.py:


                DEBUG_PROPAGATE_EXCEPTIONS = env("DEBUG") # True locally
                

VS Code Testing

Only supports unittest and pytest now.
See issue #73 for Django TestCase

In requirements-dev.txt:


                pytest
                pytest-django
                

In devcontainer.json:


                "python.testing.pytestEnabled": true,
                "python.testing.unittestEnabled": false,
                

In pyproject.toml:


                [tool.pytest.ini_options]
                pythonpath = ["src"]
                python_files = ["tests.py"]
                env_files = [".env", ".env.test"]
                

Deployment

Bicep extension

Screenshot of Bicep extension, linting on one side, visualization on other

Deployment

Using the Azure Developer CLI: aka.ms/azd

Screenshot of azd up command

Result

Deployed endpoint:
djangoquizt-qckblqxbskqfy-appservice.azurewebsites.net

Deployed resources:
Screenshot of Portal resources created

Next steps

More example repos

All of these repos are equipped with Dev Containers:

App Service Functions Container Apps
Django + PG Quiz app
+ VNET: Reviews app
+ VNET: Booking app
cookiecutter
Booking app
Flask Simple App Simple API Simple App
Simple API
+ CDN: App
+ CDN: API
+ PostgreSQL Quiz app
+ VNET: Reviews app
Surveys App
FastAPI Salary API Simple API
+ APIM: Simple API
+ CDN: Maps API
Simple API
+ MongoDB Todo API Todo API Todo API

Thank you!

Photo of Pamela smiling with a stuffed elephant

Grab the slides @ aka.ms/python-apps-vscode

Find me online at:

Mastodon @pamelafox@fosstodon.org
Twitter @pamelafox
GitHub www.github.com/pamelafox
Website pamelafox.org

Let me know about your experiences with VS Code + Python!

Any questions?

A bunch of raccoon students with computers