Flask Overview
Flask is a lightweight WSGI web application framework in Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.
Key Features
- Lightweight: Minimal core with extensibility.
- Jinja2 Templating: Powerful template engine.
- Werkzeug WSGI: Solid foundation for web apps.
- Development Server: Built-in debugger and reloader.
- RESTful: Great for building APIs.
- Extensions: Rich ecosystem of add-ons.
- Flexible: Choose your own components.
Common Use Cases
Microservices
Small, focused services in a larger system.
Prototyping
Quickly build proof-of-concept apps.
REST APIs
Backend services for web/mobile apps.
Simple Web Apps
When full-stack frameworks are overkill.
Example Code
# Basic Flask application
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, World!'
@app.route('/greet/<name>')
def greet(name):
return f'Hello, {name}!'
@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
if request.method == 'POST':
data = request.get_json()
return jsonify({'received': data})
return jsonify({'message': 'Send a POST request with JSON data'})
@app.route('/template')
def template_example():
return render_template('example.html', title='Flask Template')
if __name__ == '__main__':
app.run(debug=True)
# Flask with SQLAlchemy example
"""
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.username}>'
@app.route('/users')
def users():
users = User.query.all()
return render_template('users.html', users=users)
"""
# Flask template example (HTML)
"""
<!-- templates/example.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>This is a Flask template example.</p>
</body>
</html>
"""