---
title: Flask Best Practices
type: agent/instruction
tags: [flask, python, web]
---

{{h1}}Flask

{{h2}}Structure
- Application factory pattern
- Blueprints for modularity
- Environment-based config
- Views thin, logic in services

{{h2}}Configuration
- `app.config.from_object()`
- Secrets in environment variables
- `python-dotenv` for local dev

{{h2}}Blueprints
- Group related routes
- URL prefixes for versioning
- Register in factory
- Blueprint-level error handlers

{{h2}}Request Handling
- `request.get_json()` for JSON
- Validate input
- Proper HTTP status codes
- `jsonify()` for responses

{{h2}}Database
- Flask-SQLAlchemy for ORM
- Migrations (Flask-Migrate)
- Connection pooling
- Avoid N+1 queries

{{h2}}Error Handling
- Register error handlers
- Consistent error responses
- Handle 404 and 500

{{h2}}Security
- Flask-Login for auth
- CSRF protection
- Validate input
- Secure session cookies
- HTTPS in production

{{h2}}Performance
- Caching (Flask-Caching)
- Pagination
- Celery for background tasks
- Gzip compression

{{h2}}Avoid
- Don't use global state
- Don't ignore app context
- Don't skip validation
- Don't use debug in production
