Setting Up a Complete Development Environment

Python Web Development Toolkit Configuration

Why a Proper Development Environment Matters

Think of your development environment as a chef's kitchen. A professional chef doesn't just need a stove and some pans—they need a properly organized workspace with quality tools arranged for efficiency. Similarly, a developer needs more than just a text editor and Python installed. You need a complete ecosystem where all your tools work together seamlessly.

Today, we'll build this ecosystem piece by piece, focusing on four core areas:

By the end of this session, you'll have a professional-grade development environment that will serve as the foundation for all your future projects in this course.

Code Editor Configuration for Python Development

VS Code has become the editor of choice for many Python developers due to its balance of performance, features, and extensibility. Let's configure it properly for Python development.

Basic VS Code Settings for Python

The settings.json file in VS Code controls your editor's behavior. Here's a recommended configuration specifically for Python development:

{
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": ["--line-length", "88"],
    "editor.formatOnSave": true,
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": ["--max-line-length=88"],
    "python.sortImports.args": ["--profile", "black"],
    "editor.rulers": [88],
    "files.trimTrailingWhitespace": true,
    "python.analysis.typeCheckingMode": "basic"
}

This configuration does several important things:

Real-world benefit: When working on teams, consistent code formatting eliminates unproductive discussions about code style and prevents "format wars" in pull requests. It's like having standardized containers in a kitchen—everyone knows exactly where things belong.

Setting Up Python Interpreter Selection

VS Code needs to know which Python environment to use. Here's how to configure it:

  1. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac) to open the command palette
  2. Type "Python: Select Interpreter" and select it
  3. Choose your project's virtual environment from the list

Pro tip: You can create a .vscode/settings.json file in your project directory with project-specific settings. This helps when different projects need different environments or configurations.

Configuring Debugging

Proper debugging setup saves countless hours. Create a launch.json file in the .vscode directory:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false
        },
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py",
                "FLASK_ENV": "development"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        }
    ]
}

This configuration gives you two debug profiles:

Analogy: Debugging without proper tools is like trying to find a leak in your plumbing without being able to see through the walls. These debug configurations are like having X-ray vision for your code—you can see exactly what's happening inside as it runs.

Git Integration

Git is the industry standard for version control. It's like having a time machine for your code—you can go back to any previous state and see how things evolved.

VS Code Git Configuration

VS Code has excellent built-in Git support, but we can enhance it with some settings:

{
    "git.enableSmartCommit": true,
    "git.confirmSync": false,
    "git.autofetch": true,
    "diffEditor.ignoreTrimWhitespace": false,
    "git.inputValidationSubjectLength": 72,
    "git.inputValidationLength": 500
}

These settings:

Setting Up a .gitignore File

A good .gitignore file prevents unnecessary files from being tracked. Create one in your project root:

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Virtual Environment
venv/
ENV/

# VS Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# Docker
.docker/

# Environment Variables
.env
.env.local
.env.development

# Database
*.sqlite3

# Logs
logs/
*.log

# Tests
.coverage
htmlcov/
.pytest_cache/

Metaphor: Think of .gitignore as the bouncer at your code's nightclub—it decides what gets in and what stays out. Without it, your repository gets cluttered with temporary files, build artifacts, and environment-specific settings that shouldn't be shared.

Git Hooks for Code Quality

Git hooks let you run scripts before or after Git events like commit or push. They're like automatic quality control for your code.

Let's set up a pre-commit hook that runs our linters before allowing a commit:

  1. Install pre-commit: pip install pre-commit
  2. Create a .pre-commit-config.yaml file in your project root:
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files

-   repo: https://github.com/psf/black
    rev: 23.3.0
    hooks:
    -   id: black

-   repo: https://github.com/pycqa/isort
    rev: 5.12.0
    hooks:
    -   id: isort
        args: ["--profile", "black"]

-   repo: https://github.com/pycqa/flake8
    rev: 6.0.0
    hooks:
    -   id: flake8
        additional_dependencies: [flake8-docstrings]
  1. Initialize pre-commit: pre-commit install

Real-world application: This setup catches style issues, formatting problems, and basic errors before they even make it into your commit history. It's like having a proofreader who checks your work before you submit it, ensuring consistently high-quality code.

Docker Integration

Docker ensures that your application runs the same way everywhere. It's like shipping your entire kitchen along with the meal you cooked—the recipient gets exactly the same experience you intended.

VS Code Docker Extension Setup

The Docker extension for VS Code provides seamless Docker integration:

  1. Open the Extensions view (Ctrl+Shift+X)
  2. Search for "Docker" and install the Microsoft Docker extension
  3. After installation, you'll see a new Docker icon in the Activity Bar

This extension provides:

Creating a Development Dockerfile

Let's create a development-focused Dockerfile that includes all the tools we need:

# Dockerfile.dev
FROM python:3.10-slim

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PYTHONPATH=/app

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    curl \
    git \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Install development tools
RUN pip install --no-cache-dir black flake8 pytest isort mypy pre-commit

# Keep container running
CMD ["bash"]

Explanation: This Dockerfile:

Docker Compose for Development

Docker Compose makes it easy to run multi-container applications. Create a docker-compose.yml file:

version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - .:/app
    ports:
      - "5000:5000"
    command: bash -c "flask run --host=0.0.0.0"
    environment:
      - FLASK_APP=app.py
      - FLASK_ENV=development
      - FLASK_DEBUG=1
    
  db:
    image: postgres:13
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=app_dev

volumes:
  postgres_data:

Analogy: Docker Compose is like a restaurant recipe that includes not just how to cook each dish, but also how all the dishes work together to create a complete meal. It orchestrates all your containers to work as a unified system.

VS Code Remote Development with Docker

One of the most powerful features of VS Code is its ability to develop inside a container:

  1. Install the "Remote - Containers" extension
  2. Create a .devcontainer/devcontainer.json file:
{
    "name": "Python Development",
    "dockerComposeFile": ["../docker-compose.yml"],
    "service": "app",
    "workspaceFolder": "/app",
    "extensions": [
        "ms-python.python",
        "ms-python.vscode-pylance",
        "ms-azuretools.vscode-docker",
        "streetsidesoftware.code-spell-checker",
        "eamodio.gitlens"
    ],
    "settings": {
        "python.linting.enabled": true,
        "python.linting.pylintEnabled": true,
        "python.formatting.provider": "black",
        "editor.formatOnSave": true,
        "python.linting.flake8Enabled": true
    }
}
  1. Use the Command Palette to run "Remote-Containers: Reopen in Container"

Real-world benefit: This setup eliminates the "it works on my machine" problem. New team members can be productive immediately—they just clone the repo, open it in VS Code, and all the tools and dependencies are automatically set up inside the container.

Extensions and Tools for Productivity

The right extensions can supercharge your development workflow. Here are the essential ones for Python web development:

Essential VS Code Extensions

You can install these from the command line:

code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension eamodio.gitlens
code --install-extension ms-azuretools.vscode-docker
code --install-extension ms-vscode-remote.vscode-remote-extensionpack
code --install-extension njpwerner.autodocstring
code --install-extension littlefoxteam.vscode-python-test-adapter
code --install-extension kevin-rose.vscode-python-indent
code --install-extension streetsidesoftware.code-spell-checker
code --install-extension aaron-bond.better-comments

Command Line Tools for Python Development

Beyond VS Code, several command-line tools will enhance your workflow:

# Install development tools
pip install black         # Code formatting
pip install flake8        # Linting
pip install mypy          # Type checking
pip install pytest        # Testing
pip install isort         # Import sorting
pip install pre-commit    # Git hooks
pip install httpie        # HTTP client for API testing
pip install pgcli         # Better PostgreSQL CLI
pip install pipenv        # Better package management
pip install python-dotenv # Environment variable management

Metaphor: These tools are like having specialized kitchen gadgets. Sure, you could chop everything with a regular knife, but having a food processor, mandoline slicer, and garlic press makes you much more efficient at specific tasks.

Configuring Python Path Intelligence

For better import auto-completion and navigation, create a pyrightconfig.json file:

{
    "include": [
        "app",
        "tests"
    ],
    "exclude": [
        "**/__pycache__",
        "**/.venv"
    ],
    "reportMissingImports": true,
    "reportMissingTypeStubs": false,
    "pythonVersion": "3.10",
    "typeCheckingMode": "basic"
}

Real-world application: This configuration helps Pylance (VS Code's Python language server) understand your project structure and provide better code intelligence, reducing the time you spend tracking down import errors or navigating between files.

Putting It All Together: Creating a Project Template

Now that we've configured all these tools, let's create a reusable project template. Create a directory structure like this:

project_template/
├── .vscode/
│   ├── settings.json
│   └── launch.json
├── .devcontainer/
│   └── devcontainer.json
├── app/
│   ├── __init__.py
│   ├── config.py
│   ├── models.py
│   ├── routes.py
│   └── utils.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   └── test_app.py
├── .gitignore
├── .pre-commit-config.yaml
├── docker-compose.yml
├── Dockerfile.dev
├── requirements.txt
├── pyrightconfig.json
└── README.md

Benefits of this setup:

Analogy: This template is like a chef's mise en place—everything is prepared and in its place before you start cooking. When inspiration strikes, you can focus on creating rather than setting up tools.

A Day in the Life: A Real-World Development Workflow

Let's walk through how a typical development day looks with this setup:

  1. Start the environment: Open VS Code, open your project folder, and use "Remote-Containers: Reopen in Container"
  2. Pull latest changes: Use the Source Control tab to pull the latest changes from the remote repository
  3. Create a new feature branch: Click the branch name in the status bar and create a new branch for your feature
  4. Run the application: Use the debug configuration to start your Flask application with breakpoints ready
  5. Write code: As you code, your changes are automatically formatted on save, and linters highlight potential issues
  6. Run tests: Use the Test Explorer to run tests for your changes
  7. Commit changes: Stage and commit your changes in the Source Control tab (pre-commit hooks will check your code quality)
  8. Push your branch: Push your feature branch to the remote repository
  9. Create a pull request: Use GitLens or the GitHub PR extension to create a pull request
  10. Review and merge: After review and CI passes, merge your changes

Real-world efficiency gain: With this workflow, you spend less time on setup, environment issues, and manual checks, and more time on actual problem-solving and feature development. Studies show that a well-configured development environment can reduce time spent on non-coding tasks by up to 60%.

Common Issues and Troubleshooting

Even the best environments occasionally have problems. Here are solutions to common issues:

Container Startup Problems

Issue: VS Code can't connect to the container
Solution: Check Docker service is running, try rebuilding with "Remote-Containers: Rebuild Container"

Python Environment Issues

Issue: VS Code isn't using the correct Python interpreter
Solution: Use "Python: Select Interpreter" and choose the one in your container (/usr/local/bin/python)

Git Integration Problems

Issue: Git complains about line ending differences
Solution: Set git config --global core.autocrlf input on Unix/Mac or git config --global core.autocrlf true on Windows

Pre-commit Hook Failures

Issue: Pre-commit hooks failing unexpectedly
Solution: Run pre-commit run --all-files to see detailed errors, then fix them

Metaphor: Think of troubleshooting as debugging a recipe. When something doesn't taste right, a good chef knows to check the temperature, ingredients, and cooking time methodically—the same approach works for development environments.

Conclusion and Next Steps

You now have a professional-grade development environment that integrates all the tools you need for Python web development. This foundation will serve you well throughout this course and your professional career.

Weekend Project

For your weekend project, you'll apply what you've learned by setting up a containerized Python environment that includes:

This project will solidify your understanding and give you a template you can use for all future projects in this course.

Additional Resources

Remember: A well-configured development environment is an investment that pays dividends every day. The time you spend setting it up now will save you countless hours throughout your career.