Flask MVC
Transform your Flask application into a structured MVC architecture with powerful CLI tools
Installation • Quick Start • Documentation • Examples • Contributing
🚀 Features
- 🏗️ MVC Architecture: Clean separation of concerns with Models, Views, and Controllers
- ⚡ CLI Generator: Powerful command-line tools to generate controllers, models, and more
- 🎨 Template System: Professional templates with Flask best practices
- 🔧 Flexible Configuration: Customizable paths and settings via environment variables
- 📝 Type Safety: Full type hints support for better development experience
- 🧪 Testing Ready: Built-in support for testing with comprehensive error handling
- � SQLAlchemy Introspection: Deferred model reflection support via
ReflectedModelandFlaskReflection, allowing models to map table schemas dynamically without explicit field declarations. - �📖 Auto Documentation: Generated code includes professional docstrings
- 🌐 API & Web Support: Content negotiation for both web and API responses
📦 Installation
Using pip
pip install flask-mvc2
Using UV
uv add flask-mvc2
Development Installation
git clone https://github.com/marcuxyz/flask-mvc.git
cd flask_mvc
uv sync
🏃♂️ Quick Start
Basic Setup
from flask import Flask
from flask_mvc import FlaskMVC
app = Flask(__name__)
FlaskMVC(app)
if __name__ == "__main__":
app.run(debug=True)
Using Application Factory Pattern
from flask import Flask
from flask_mvc import FlaskMVC
from flask_sqlalchemy import SQLAlchemy
mvc = FlaskMVC()
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db.init_app(app)
mvc.init_app(app, path='src') # Custom path (default: 'app')
return app
app = create_app()
SQLAlchemy Introspection Support
Flask MVC now includes Rails-like SQLAlchemy introspection support. With ReflectedModel and FlaskReflection, you can define a model that only declares __tablename__ while the extension discovers table columns at runtime.
from flask_mvc.middlewares.base_model import ReflectedModel
from tests.app import db
class Message(ReflectedModel, db.Model):
__tablename__ = 'messages'
This feature works best when the database extension is initialized before Flask MVC:
db.init_app(app)
FlaskMVC(app, path='app', db=db)
Generate Your First Controller
# Generate a basic controller
flask mvc generate controller home
# Generate controller in custom path
flask mvc generate controller user --path src/controllers
# Force overwrite existing controller
flask mvc generate controller admin --force
This creates a professional controller with CRUD operations:
"""HomeController - Generated by Flask MVC CLI."""
from flask import render_template, jsonify, request
from typing import Any, Dict, Optional, Union
class HomeController:
"""Controller for handling home related requests."""
def index(self) -> Union[str, Dict[str, Any]]:
"""Display the index page."""
if request.is_json or request.accept_mimetypes.accept_json:
return jsonify({
"message": "Hello from HomeController!",
"controller": "home",
"action": "index"
})
return "Hello from HomeController!"
# Complete CRUD methods included...
📁 Project Structure
Flask MVC encourages a clean project structure:
your-project/
├── app/ # Main application directory
│ ├── __init__.py
│ ├── controllers/ # Controllers directory
│ │ ├── __init__.py
│ │ ├── home_controller.py
│ │ └── user_controller.py
│ ├── models/ # Models directory (optional)
│ │ └── user.py
│ ├── views/ # Templates directory
│ │ ├── layouts/
│ │ ├── home/
│ │ └── user/
│ └── routes.py # Route definitions
├── tests/ # Test directory
├── requirements.txt # Dependencies
└── app.py # Application entry point
🛠️ CLI Commands
Flask MVC provides powerful CLI commands for rapid development:
Controller Generation
# Basic controller
flask mvc generate controller blog
# API controller
flask mvc generate controller api_v1_users
# Controller with custom path
flask mvc generate controller admin --path admin/controllers
# Force overwrite
flask mvc generate controller posts --force
Available Options
| Option | Short | Description |
|---|---|---|
--path |
-p |
Custom path for generated files |
--force |
-f |
Overwrite existing files |
--help |
-h |
Show command help |
🎯 Examples
Web Application Controller
class BlogController:
def index(self):
posts = Post.get_all()
return render_template('blog/index.html', posts=posts)
def show(self, id: int):
post = Post.get_by_id(id)
return render_template('blog/show.html', post=post)
API Controller
class ApiUserController:
def index(self):
users = User.get_all()
return jsonify([user.to_dict() for user in users])
def create(self):
data = request.get_json()
user = User.create(data)
return jsonify(user.to_dict()), 201
Hybrid Controller (Web + API)
Generated controllers automatically handle both web and API requests:
def index(self) -> Union[str, Dict[str, Any]]:
posts = Post.get_all()
if request.is_json or request.accept_mimetypes.accept_json:
return jsonify([post.to_dict() for post in posts])
return render_template('posts/index.html', posts=posts)
⚙️ Configuration
Environment Variables
Customize Flask MVC behavior using environment variables:
# Custom paths
export FLASK_MVC_CONTROLLERS_PATH="src/controllers"
export FLASK_MVC_VIEWS_PATH="src/templates"
export FLASK_MVC_MODELS_PATH="src/models"
# Template settings
export FLASK_MVC_TEMPLATES_DIR="custom/templates"
export FLASK_MVC_FILE_ENCODING="utf-8"
Programmatic Configuration
from flask_mvc.commands.config import CLIConfig
# Override default settings
CLIConfig.DEFAULT_CONTROLLERS_PATH = "src/controllers"
CLIConfig.DEFAULT_VIEWS_PATH = "src/templates"
🧪 Testing
Flask MVC is built with testing in mind:
import pytest
from flask_mvc.command.controller.generator import Generator as ControllerGenerator
from flask_mvc.command.exceptions import InvalidControllerNameError
def test_controller_generation():
generator = ControllerGenerator()
# Test valid controller generation
result = generator.generate("test", "/tmp/controllers")
assert result.exists()
# Test invalid name handling
with pytest.raises(InvalidControllerNameError):
generator.generate("123invalid")
📚 Documentation
- Full Documentation - Complete guide and API reference
- Quick Start Guide - Get up and running fast
- Controller Guide - Working with controllers
- Router Guide - Route configuration
- CLI Reference - Command-line tools
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Setup
# Clone the repository
git clone https://github.com/marcuxyz/flask-mvc.git
cd flask_mvc
# Install dependencies
uv sync
# Run tests
uv run pytest
# Run linting
uv run black .
uv run flake8
# Build documentation
uv run mkdocs serve
Reporting Issues
📋 Requirements
- Python: 3.12+
- Flask: 3.0+
- Click: 8.0+ (included with Flask)
- Jinja2: 3.0+ (included with Flask)
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Flask Community - For the amazing web framework
- Click Team - For the excellent CLI framework
- Contributors - Everyone who has contributed to this project
📊 Stats
Metadata
Release files for flask-mvc2 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| flask_mvc2-0.5.0.tar.gz | 16.3 kB | Without provenance | Details for flask_mvc2-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| flask_mvc2-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for flask_mvc2-0.5.0-py3-none-any.whl |
Total release size: 36.3 kB
Release files / flask_mvc2-0.5.0.tar.gz
| Download URL | flask_mvc2-0.5.0.tar.gz |
|---|---|
| Size | 16.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
162a30ded9c7ddb4d16c7d6823aced8b0b93626cce3c54f244f67de1e516888e
|
|
BLAKE2b-256 checksum How to use checksums |
22a7c08381e466f0decfdfc9bf48f55c327b384323d7755ffb7d6dc6a69a778a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / flask_mvc2-0.5.0-py3-none-any.whl
| Download URL | flask_mvc2-0.5.0-py3-none-any.whl |
|---|---|
| Size | 20.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bed2b17656a107548ef486e97cb066ef2c0fff79bbecf6838e30458cad5e6033
|
|
BLAKE2b-256 checksum How to use checksums |
6c58ccb8b703b5e58dd2cc49673f8594f577ef49f5b6d52341fec160acbe9f54
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for flask-mvc2 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.