Building Your Own Utilities

Database Regeneration - Practical Scripting
Course 1 ยท Chapter 6 ยท Building Your Own Utilities

๐Ÿ› ๏ธ Building Your Own Utilities

You've learned the core patterns: paths, configuration, databases, and automation. Now it's time to take these patterns and apply them to build reusable utilities for any project. This final chapter teaches best practices for structure, documentation, testing, and sharing your utilities.

๐Ÿ“‹ The Utility Template

Every utility you build should follow this structure:

my-utility/
โ”œโ”€โ”€ .env.example              โ† Configuration template
โ”œโ”€โ”€ requirements.txt          โ† Python dependencies
โ”œโ”€โ”€ README.md                 โ† Usage instructions
โ”œโ”€โ”€ utils.py                  โ† Core functionality
โ”œโ”€โ”€ main.py                   โ† Entry point
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ test_utils.py        โ† Unit tests

โœ… Best Practices

1. Separate Concerns

# โŒ BAD: Everything in one file
main.py:
  - Load config
  - Connect to database
  - Process files
  - Insert into database
  - Display results

# โœ… GOOD: Separate modules
config.py        โ†’ Configuration loading
db_utils.py      โ†’ Database operations
file_utils.py    โ†’ File operations
main.py          โ†’ Orchestration

2. Configuration Management

# โœ… GOOD: All config in one place
config.py:
  - Load from .env
  - Set defaults
  - Validate
  - Return structured config

# โœ… GOOD: .env.example for documentation
.env.example:
  DB_HOST=localhost
  DB_USER=your_username
  DB_PASS=your_password

3. Error Handling

# โœ… GOOD: Graceful failure
try:
    # Main operation
except SpecificError as e:
    print(f"โŒ {e}")
    return False
finally:
    # Cleanup

4. Type Hints

def process_file(filepath: str, config: dict) -> bool:
    """Process a file and return success status."""
    pass

def find_files(directory: str) -> list[str]:
    """Find all files in directory."""
    pass

5. Documentation

# README.md should explain:

1. What it does (1 paragraph)
2. Installation (pip install -r requirements.txt)
3. Setup (.env configuration)
4. Usage (how to run it)
5. Examples (real-world usage)
6. Troubleshooting (common issues)

๐Ÿ”„ Adapting Patterns to New Projects

From TypeScript Course to Any Course

Component TypeScript Example Generic Pattern
Find Files glob("ts1-*.html") glob("{prefix}-*.{ext}")
Parse Metadata Extract from <h2> Extract key data from file
Database Entity TypeScript Fundamentals Any course name
Insert Operation insert_chapter_with_content() insert_<item>()

Real-World Examples

Example 1: Import Blog Posts

  • Find: blog-*.md files
  • Parse: Extract title, date, content
  • Database: Insert into posts table

Example 2: Sync User Data

  • Find: users.csv file
  • Parse: Read CSV rows
  • Database: Update users table

Example 3: Process Images

  • Find: *.jpg files in directory
  • Parse: Extract metadata (size, dimensions)
  • Database: Insert into images table

๐Ÿงช Testing Your Utility

Unit Tests

import pytest
from utils import parse_metadata, find_files

def test_parse_metadata():
    """Test metadata parsing."""
    result = parse_metadata("chapter-1.html")
    assert result['number'] == 1
    assert result['title'] is not None

def test_find_files(tmp_path):
    """Test file discovery."""
    # Create test files
    (tmp_path / "chapter-1.html").touch()
    (tmp_path / "chapter-2.html").touch()

    # Test finding them
    files = find_files(tmp_path)
    assert len(files) == 2

Integration Tests

def test_full_workflow(tmp_path, test_db):
    """Test complete workflow."""
    # Create test files
    # Run main workflow
    # Verify database
    pass

๐ŸŽฏ Common Utility Patterns

Pattern 1: File Discovery + Database Insert

Find files โ†’ Parse โ†’ Insert into database

Pattern 2: Data Transformation

Read source โ†’ Transform โ†’ Write result

Pattern 3: API Sync

Fetch from API โ†’ Parse โ†’ Store in database

Pattern 4: CSV/Excel Import

Read file โ†’ Parse rows โ†’ Insert records

Pattern 5: Batch Processing

Find items โ†’ Process each โ†’ Report results

๐Ÿ“ Documentation Checklist

โœ… README.md with overview and usage
โœ… .env.example showing all config options
โœ… requirements.txt with all dependencies
โœ… Type hints on all functions
โœ… Docstrings on modules and functions
โœ… Error messages that explain what went wrong
โœ… Examples of how to use the utility
โœ… Troubleshooting section for common issues

๐Ÿ’ป Final Challenges

Challenge 1: Create a Blog Post Importer

Build a utility that:

  1. Finds all blog-*.md files
  2. Parses title and date from front matter
  3. Inserts into database
  4. Reports count

Goal: Apply patterns to a new domain (blog posts vs. courses).

โ†’ Solution

Challenge 2: Data Transformation Utility

Build a utility that:

  1. Reads a CSV file
  2. Transforms data (cleanup, validation)
  3. Writes to database
  4. Generates report

Goal: Practice the data transformation pattern.

โ†’ Solution

Challenge 3: Reusable Utility Package

Build a complete utility package with:

  1. Main script with proper structure
  2. Configuration management
  3. Error handling and logging
  4. Unit tests
  5. Complete documentation

Goal: Build a production-ready utility you could share.

โ†’ Solution

๐ŸŽ“ Course Conclusion

๐Ÿ† You've Mastered
  • โœ… File system navigation with Path and glob
  • โœ… Configuration management with .env
  • โœ… Database connections and operations
  • โœ… Building reusable utility modules
  • โœ… Complete automation workflows
  • โœ… Best practices for production code

What You Can Build Now

With these patterns, you can build utilities for:

  • ๐Ÿ“š Course content management systems
  • ๐Ÿ“ Blog post importers
  • ๐Ÿ“Š Data migration tools
  • ๐Ÿ”„ API sync utilities
  • ๐Ÿ“ Batch file processors
  • ๐Ÿ—„๏ธ Database administration tools
  • ๐Ÿš€ CI/CD automation scripts

Next Steps

  1. Pick a project: What do you want to automate?
  2. Follow the template: Use the structure from this course
  3. Test thoroughly: Write unit and integration tests
  4. Document well: Help future users understand it
  5. Share it: Put it on GitHub so others can use it
๐Ÿ’ก Remember

The patterns you've learned work for any project. The details change (different file types, different databases, different APIs), but the structure stays the same. Master the patterns, adapt them to your needs, and you can build anything!