Python Flask SQLite Best Practices
Overview
This skill enforces comprehensive Python development best practices for Flask applications with SQLite databases. It mandates git commit hygiene and exhaustive Docker healthchecks while guiding proper project structure, security, testing, and deployment patterns.
Critical Requirements
1. Mandatory Git Commits
**EVERY file change MUST be committed immediately:**
1. Stage all modified files: `git add <files>` or `git add .`
2. Commit with conventional format: `git commit -m "type: descriptive message"`
3. Verify success before proceeding
**Commit types:**
`fix:` - Bug fixes`feat:` - New features`refactor:` - Code refactoring`docs:` - Documentation`chore:` - Maintenance`test:` - Test changes**Never summarize changes without committing. Never skip commits.**
2. Docker Healthcheck Requirements
**ALL Docker services MUST have comprehensive healthchecks:**
✅ **Required:**
Full HTTP/HTTPS endpoint validationProper intervals, timeouts, retries, start_periodTest actual functionality, not just portsInclude `deunhealth.restart.on.unhealthy: "true"` labelInstall health check tools if missing❌ **Forbidden:**
Disabled healthchecksCommented healthchecksTCP-only checks (nc -z)Removing healthchecks to "fix" issues**Example proper healthcheck:**
```yaml
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://127.0.0.1:8080/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
labels:
deunhealth.restart.on.unhealthy: "true"
```
Project Structure Guidelines
Directory Layout
```
project/
├── src/
│ └── your_package_name/
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ └── types.py
├── tests/
├── config/
├── static/
├── templates/
├── requirements.txt
└── README.md
```
Configuration Management
Store config in `config/` directory or environment variablesUse `requirements.txt` or `pyproject.toml` for dependenciesPin all dependency versionsSeparate dev/prod dependenciesCode Style Standards
Formatting
Use Black formatter (88 character line length)Use isort for import sortingFollow PEP 8 naming: - `snake_case` for functions/variables
- `PascalCase` for classes
- `UPPER_CASE` for constants
Use absolute imports over relativeType Hints
Add type hints to all function parameters and returnsUse `typing` module importsUse `Optional[Type]` instead of `Type | None`Define custom types in `types.py`Use `Protocol` for duck typingFlask Application Structure
Factory Pattern
Use Flask application factory patternOrganize routes using BlueprintsSeparate concerns properly in viewsImplement proper error handlersDatabase Layer
Use Flask-SQLAlchemy ORMImplement Alembic migrationsUse proper connection poolingDefine models in separate modulesImplement proper relationships and indexesAuthentication
Use Flask-Login for session managementImplement OAuth (Google) with Flask-OAuthHash passwords with bcryptEnable CSRF protectionUse role-based access controlAPI Design Patterns
Use Flask-RESTful for REST APIsValidate all requestsUse proper HTTP status codesHandle errors consistentlyImplement rate limitingUse standardized response formatsTesting Strategy
Use pytest as test frameworkWrite tests for all routesUse pytest-cov for coverage trackingImplement proper fixturesMock external dependencies with pytest-mockTest all error scenarios and edge casesSecurity Checklist
Use HTTPS in productionImplement proper CORSSanitize all user inputsConfigure sessions securelyImplement comprehensive loggingFollow OWASP security guidelinesPerformance Optimization
Use Flask-Caching for cachingOptimize database queriesUse proper connection poolingImplement pagination for large datasetsUse background tasks for heavy operationsMonitor application performance metricsError Handling
Create custom exception classesUse try-except blocks appropriatelyImplement structured loggingReturn meaningful error responsesHandle edge cases explicitlyUse user-friendly error messagesDocumentation Standards
Use Google-style docstringsDocument all public APIsKeep README.md currentAdd inline comments for complex logicGenerate API documentationDocument environment setup stepsDevelopment Workflow
Use virtual environments (venv)Implement pre-commit hooksFollow proper Git workflowUse semantic versioningImplement CI/CD pipelinesUse structured logging throughoutDependency Management
Pin all dependency versions in requirements.txtSeparate dev dependenciesUse specific package versionsUpdate dependencies regularlyScan for security vulnerabilitiesDocument dependency changesUsage Instructions
When working on Python Flask/SQLite projects:
1. **Before making changes:** Review project structure and existing patterns
2. **During development:**
- Follow code style guidelines
- Add type hints to all functions
- Write tests for new code
- Implement proper error handling
- Add comprehensive healthchecks to Docker services
3. **After changes:**
- Run tests with pytest
- Check code formatting with Black
- Stage and commit ALL changes with proper commit message format
- Verify commit succeeded
4. **For Docker services:**
- Add exhaustive healthchecks to all containers
- Never disable or remove healthchecks
- Test actual service functionality in healthchecks
- Include self-healing labels
Constraints
Never skip git commits after file changesNever disable or remove Docker healthchecksAlways validate user inputsAlways use type hintsAlways write tests for new functionalityAlways follow Black formattingAlways use proper error handlingAlways implement security best practices