Flask Web Framework
Expert skill for working with Flask, a lightweight WSGI web application framework for Python. Flask is designed for quick starts with the flexibility to scale to complex applications, built on Werkzeug and Jinja.
When to Use This Skill
Use this skill when you need to:
Create or modify Flask web applicationsBuild REST APIs with FlaskSet up routing, views, and templatesConfigure Flask applicationsWork with Flask extensionsDebug Flask applicationsImplement authentication/authorizationHandle forms and database integrationInstructions
When working with Flask applications, follow these guidelines:
1. Project Structure Analysis
First, examine the project structure to understand the Flask app organizationLook for `app.py`, `__init__.py`, or application factory patternsIdentify the Flask version in use (check `requirements.txt` or `pyproject.toml`)Review existing routes, blueprints, and configuration files2. Flask Best Practices
Use application factories for better testing and multiple instancesOrganize larger applications using BlueprintsKeep configuration separate (development, testing, production)Use environment variables for sensitive dataFollow RESTful conventions for API endpointsImplement proper error handling with custom error pages3. Common Flask Patterns
**Basic Application:**
```python
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
if request.method == 'POST':
data = request.get_json()
return jsonify({'status': 'success', 'data': data})
return jsonify({'message': 'Hello, World!'})
```
**Application Factory Pattern:**
```python
def create_app(config_name='development'):
app = Flask(__name__)
app.config.from_object(config[config_name])
# Register blueprints
from .main import main_bp
app.register_blueprint(main_bp)
return app
```
4. Key Components to Consider
**Routing**: Define URL patterns and HTTP methods**Templates**: Use Jinja2 for rendering HTML**Request/Response**: Handle form data, JSON, files**Session Management**: Secure user sessions**Database**: Integration with SQLAlchemy or other ORMs**Extensions**: Flask-Login, Flask-WTF, Flask-Migrate, etc.**Error Handling**: Custom error pages and logging**Testing**: Write unit and integration tests5. Security Considerations
Always set a strong `SECRET_KEY` in productionUse CSRF protection (Flask-WTF)Validate and sanitize user inputImplement proper authentication and authorizationUse HTTPS in productionSet secure session cookiesProtect against SQL injection (use parameterized queries)6. Development Workflow
Run in debug mode during development: `flask run --debug`Use environment variables for configurationSet up logging for debuggingWrite tests before deployingUse virtual environments for dependency isolation7. Common Tasks
**Adding a new route:**
Define the route function with appropriate decoratorsHandle request data (query params, form data, JSON)Return appropriate responses (templates, JSON, redirects)**Database operations:**
Use Flask-SQLAlchemy or Flask-Migrate for database managementDefine models with proper relationshipsImplement CRUD operations safely**API development:**
Use RESTful conventions (GET, POST, PUT, DELETE)Return proper HTTP status codesStructure JSON responses consistentlyImplement API authentication (JWT, OAuth)8. Troubleshooting
Check Flask version compatibility with extensionsReview application logs for errorsVerify configuration settingsTest routes with proper HTTP methodsEnsure templates are in the correct directoryCheck for circular imports in larger applicationsExample: Complete Minimal API
```python
app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dev-secret-key'
@app.route('/')
def home():
return jsonify({'message': 'Welcome to Flask API'})
@app.route('/api/users', methods=['GET', 'POST'])
def users():
if request.method == 'POST':
user_data = request.get_json()
# Process user data
return jsonify({'status': 'created', 'user': user_data}), 201
# Return users list
return jsonify({'users': []})
if __name__ == '__main__':
app.run(debug=True)
```
Run with: `python app.py` or `flask run`
Notes
Flask is unopinionated - choose your own tools and librariesMany community extensions available for added functionalityOfficial documentation: https://flask.palletsprojects.com/Consider using Flask blueprints for modular applicationsAlways use virtual environments for Flask projects