Python Flask SQLite Best Practices
Expert guidance for building robust Python applications with Flask and SQLite, following modern software development standards.
Instructions
When working on Python projects, follow these comprehensive guidelines:
1. Project Structure
Organize the project using these conventions:
Use src-layout with `src/your_package_name/` for all application codePlace all tests in `tests/` directory parallel to `src/`Store configuration in `config/` or use environment variablesManage dependencies in `requirements.txt` or `pyproject.toml`Place static files (CSS, JS, images) in `static/` directoryUse `templates/` directory for all Jinja2 templates2. Code Style and Formatting
Apply these styling rules consistently:
Use Black code formatter with default settings (88 character line length)Sort imports using isortFollow PEP 8 naming conventions: - `snake_case` for functions and variables
- `PascalCase` for classes
- `UPPER_CASE` for constants
Prefer absolute imports over relative importsKeep lines to maximum 88 characters3. Type Hints
Implement strong typing throughout:
Add type hints to all function parameters and return valuesImport types from `typing` moduleUse `Optional[Type]` instead of `Type | None`Use `TypeVar` for generic typesDefine custom types in dedicated `types.py` fileUse `Protocol` for duck typing interfaces4. API Design with Flask
Build REST APIs following these patterns:
Use Flask-RESTful for REST API structureImplement proper request validation for all endpointsUse appropriate HTTP status codes (200, 201, 400, 404, 500, etc.)Handle errors consistently with standardized error responsesUse consistent response formats (JSON)Implement rate limiting to protect endpoints5. Testing
Write comprehensive tests:
Use pytest as the testing frameworkWrite tests for all routes and endpointsUse pytest-cov for code coverage reportingCreate reusable fixtures for common test setupUse pytest-mock for proper mockingTest all error scenarios and edge cases6. Security
Implement security best practices:
Use HTTPS in production environmentsConfigure CORS properly with Flask-CORSSanitize and validate all user inputsUse secure session configurationImplement comprehensive loggingFollow OWASP security guidelines7. Performance Optimization
Optimize application performance:
Use Flask-Caching for caching frequently accessed dataOptimize database queries (use indexes, avoid N+1 queries)Implement proper connection poolingUse pagination for large result setsOffload heavy operations to background tasksMonitor application performance metrics8. Error Handling
Handle errors gracefully:
Create custom exception classes for domain-specific errorsUse proper try-except blocks to catch exceptionsImplement structured logging for debuggingReturn appropriate error responses to clientsHandle edge cases explicitlyProvide clear, actionable error messages9. Documentation
Maintain clear documentation:
Use Google-style docstrings for all functions and classesDocument all public APIs with parameters and return valuesKeep README.md updated with setup and usage instructionsAdd inline comments for complex logicGenerate API documentation automaticallyDocument environment setup and dependencies10. Development Workflow
Follow professional development practices:
Always use virtual environments (venv or virtualenv)Implement pre-commit hooks for code quality checksUse proper Git workflow (feature branches, pull requests)**IMPORTANT:** Do not push to repository without explicit permissionFollow semantic versioning (MAJOR.MINOR.PATCH)Use CI/CD pipelines for automated testing and deploymentImplement structured logging at appropriate levels11. Dependency Management
Manage dependencies carefully:
Pin exact dependency versions in productionUse `requirements.txt` for production dependenciesSeparate development dependencies (testing, linting)Specify compatible version ranges appropriatelyRegularly update dependencies for security patchesRun security vulnerability checks on dependenciesExample Usage
```python
from typing import Optional, List
from flask import Flask, jsonify
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class UserResource(Resource):
"""User resource for managing user data."""
def get(self, user_id: Optional[int] = None) -> tuple:
"""
Retrieve user(s) from the database.
Args:
user_id: Optional user ID to retrieve specific user
Returns:
Tuple of (response_data, status_code)
"""
try:
if user_id:
user = get_user_by_id(user_id)
return jsonify(user), 200
users = get_all_users()
return jsonify(users), 200
except ValueError as e:
return {"error": str(e)}, 404
except Exception as e:
logger.error(f"Error retrieving users: {e}")
return {"error": "Internal server error"}, 500
api.add_resource(UserResource, "/users", "/users/<int:user_id>")
```
Constraints
Always validate user input before processingNever commit sensitive data (API keys, passwords) to version controlUse environment variables for configuration secretsTest thoroughly before requesting permission to push changesFollow the principle of least privilege for database accessKeep dependencies minimal and well-justified