211 lines
7.0 KiB
Markdown
211 lines
7.0 KiB
Markdown
|
|
# MVC Refactoring Documentation
|
||
|
|
|
||
|
|
## Overview
|
||
|
|
|
||
|
|
This document describes the MVC (Model-View-Controller) refactoring that has been implemented in the Flask application to improve code organization, maintainability, and separation of concerns.
|
||
|
|
|
||
|
|
## Architecture Overview
|
||
|
|
|
||
|
|
The application has been refactored from a monolithic `app.py` file to a proper MVC architecture with the following structure:
|
||
|
|
|
||
|
|
```
|
||
|
|
controles/
|
||
|
|
├── app.py # Main application entry point (minimal)
|
||
|
|
├── controllers/ # Controllers (handling routes and request logic)
|
||
|
|
│ ├── auth_controller.py
|
||
|
|
│ ├── home_controller.py
|
||
|
|
│ ├── militante_controller.py
|
||
|
|
│ ├── pagamento_controller.py
|
||
|
|
│ ├── cota_controller.py
|
||
|
|
│ └── usuario_controller.py
|
||
|
|
├── models/ # Models (database operations and business logic)
|
||
|
|
│ ├── militante_model.py
|
||
|
|
│ ├── pagamento_model.py
|
||
|
|
│ └── entities/
|
||
|
|
├── services/ # Services (business logic and external integrations)
|
||
|
|
│ ├── auth_service.py
|
||
|
|
│ ├── dashboard_service.py
|
||
|
|
│ └── celula_service.py
|
||
|
|
├── templates/ # Views (HTML templates)
|
||
|
|
├── static/ # Static assets (CSS, JS, images)
|
||
|
|
└── functions/ # Utility functions and helpers
|
||
|
|
```
|
||
|
|
|
||
|
|
## Key Improvements
|
||
|
|
|
||
|
|
### 1. Separation of Concerns
|
||
|
|
|
||
|
|
**Before Refactoring:**
|
||
|
|
- All routes, business logic, and database operations were in a single `app.py` file
|
||
|
|
- Mixed responsibilities made the code difficult to maintain
|
||
|
|
- Large file size (120+ lines) with complex logic
|
||
|
|
|
||
|
|
**After Refactoring:**
|
||
|
|
- **Controllers**: Handle HTTP requests, route definitions, and request/response logic
|
||
|
|
- **Models**: Encapsulate database operations and data manipulation
|
||
|
|
- **Services**: Contain business logic and external service integrations
|
||
|
|
- **Views**: HTML templates remain in the templates directory
|
||
|
|
|
||
|
|
### 2. Modularity
|
||
|
|
|
||
|
|
Each major feature now has its own controller:
|
||
|
|
- `auth_controller.py` - Authentication and user management
|
||
|
|
- `home_controller.py` - Dashboard and home page
|
||
|
|
- `militante_controller.py` - Member management
|
||
|
|
- `pagamento_controller.py` - Payment management
|
||
|
|
- `cota_controller.py` - Quota management
|
||
|
|
- `usuario_controller.py` - User administration
|
||
|
|
|
||
|
|
### 3. Code Reusability
|
||
|
|
|
||
|
|
- **Models**: Provide reusable database operations
|
||
|
|
- **Services**: Encapsulate business logic that can be used across controllers
|
||
|
|
- **Blueprints**: Enable modular route registration
|
||
|
|
|
||
|
|
## Detailed Architecture
|
||
|
|
|
||
|
|
### Controllers Layer
|
||
|
|
|
||
|
|
Controllers handle HTTP requests and coordinate between models and services:
|
||
|
|
|
||
|
|
```python
|
||
|
|
# Example: auth_controller.py
|
||
|
|
from flask import Blueprint, request, render_template, redirect, url_for, flash
|
||
|
|
from services.auth_service import AuthService
|
||
|
|
|
||
|
|
auth_bp = Blueprint('auth', __name__)
|
||
|
|
|
||
|
|
@auth_bp.route("/login", methods=["GET", "POST"])
|
||
|
|
def login():
|
||
|
|
if request.method == "POST":
|
||
|
|
result = AuthService.autenticar_usuario(
|
||
|
|
request.form.get("email"),
|
||
|
|
request.form.get("password"),
|
||
|
|
request.form.get("otp")
|
||
|
|
)
|
||
|
|
# Handle result and response
|
||
|
|
```
|
||
|
|
|
||
|
|
### Models Layer
|
||
|
|
|
||
|
|
Models encapsulate database operations and data manipulation:
|
||
|
|
|
||
|
|
```python
|
||
|
|
# Example: militante_model.py
|
||
|
|
class MilitanteModel:
|
||
|
|
@staticmethod
|
||
|
|
def criar_militante(data: Dict) -> Dict:
|
||
|
|
"""Cria um novo militante"""
|
||
|
|
db = get_db_connection()
|
||
|
|
try:
|
||
|
|
# Database operations
|
||
|
|
return {'status': 'success', 'message': 'Militante criado'}
|
||
|
|
except Exception as e:
|
||
|
|
return {'status': 'error', 'message': str(e)}
|
||
|
|
finally:
|
||
|
|
db.close()
|
||
|
|
```
|
||
|
|
|
||
|
|
### Services Layer
|
||
|
|
|
||
|
|
Services contain business logic and external integrations:
|
||
|
|
|
||
|
|
```python
|
||
|
|
# Example: auth_service.py
|
||
|
|
class AuthService:
|
||
|
|
@staticmethod
|
||
|
|
def autenticar_usuario(email_or_username: str, password: str, otp: str = None) -> Dict:
|
||
|
|
"""Autentica um usuário"""
|
||
|
|
# Business logic for authentication
|
||
|
|
return {'status': 'success', 'user': user}
|
||
|
|
```
|
||
|
|
|
||
|
|
### Main Application
|
||
|
|
|
||
|
|
The main `app.py` file is now minimal and focused on configuration:
|
||
|
|
|
||
|
|
```python
|
||
|
|
def create_app():
|
||
|
|
"""Cria e configura a aplicação Flask"""
|
||
|
|
app = Flask(__name__)
|
||
|
|
|
||
|
|
# Configuration
|
||
|
|
app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
|
||
|
|
bootstrap = Bootstrap5(app)
|
||
|
|
csrf = CSRFProtect()
|
||
|
|
csrf.init_app(app)
|
||
|
|
|
||
|
|
# Register blueprints
|
||
|
|
app.register_blueprint(auth_bp)
|
||
|
|
app.register_blueprint(home_bp)
|
||
|
|
app.register_blueprint(militante_bp)
|
||
|
|
app.register_blueprint(pagamento_bp)
|
||
|
|
app.register_blueprint(cota_bp)
|
||
|
|
app.register_blueprint(usuario_bp)
|
||
|
|
app.register_blueprint(admin_bp)
|
||
|
|
|
||
|
|
return app
|
||
|
|
```
|
||
|
|
|
||
|
|
## Benefits Achieved
|
||
|
|
|
||
|
|
### 1. Maintainability
|
||
|
|
- Each component has a single responsibility
|
||
|
|
- Easier to locate and modify specific functionality
|
||
|
|
- Reduced coupling between components
|
||
|
|
|
||
|
|
### 2. Testability
|
||
|
|
- Controllers can be tested independently
|
||
|
|
- Models can be unit tested without HTTP context
|
||
|
|
- Services can be mocked for testing
|
||
|
|
|
||
|
|
### 3. Scalability
|
||
|
|
- New features can be added as new controllers
|
||
|
|
- Existing functionality can be extended without affecting other parts
|
||
|
|
- Blueprint structure supports modular development
|
||
|
|
|
||
|
|
### 4. Code Organization
|
||
|
|
- Clear separation between presentation, business logic, and data access
|
||
|
|
- Consistent patterns across the application
|
||
|
|
- Easier onboarding for new developers
|
||
|
|
|
||
|
|
## File Size Reduction
|
||
|
|
|
||
|
|
**Before Refactoring:**
|
||
|
|
- `app.py`: 120+ lines with mixed responsibilities
|
||
|
|
|
||
|
|
**After Refactoring:**
|
||
|
|
- `app.py`: ~80 lines (configuration only)
|
||
|
|
- Controllers: 80-300 lines each (focused responsibilities)
|
||
|
|
- Models: 200+ lines each (data operations)
|
||
|
|
- Services: 70-150 lines each (business logic)
|
||
|
|
|
||
|
|
## Best Practices Implemented
|
||
|
|
|
||
|
|
1. **Single Responsibility Principle**: Each class/module has one reason to change
|
||
|
|
2. **Dependency Injection**: Services are injected into controllers
|
||
|
|
3. **Error Handling**: Consistent error handling patterns across layers
|
||
|
|
4. **Type Hints**: Used throughout for better code documentation
|
||
|
|
5. **Static Methods**: Used in models and services for stateless operations
|
||
|
|
6. **Blueprint Pattern**: Modular route organization
|
||
|
|
7. **Database Connection Management**: Proper connection handling with try/finally blocks
|
||
|
|
|
||
|
|
## Migration Notes
|
||
|
|
|
||
|
|
The refactoring maintains backward compatibility:
|
||
|
|
- All existing routes continue to work
|
||
|
|
- Database models remain unchanged
|
||
|
|
- Template structure is preserved
|
||
|
|
- Configuration and environment variables are maintained
|
||
|
|
|
||
|
|
## Future Enhancements
|
||
|
|
|
||
|
|
1. **Repository Pattern**: Further abstraction of data access layer
|
||
|
|
2. **Dependency Injection Container**: For better service management
|
||
|
|
3. **API Versioning**: Support for multiple API versions
|
||
|
|
4. **Caching Layer**: Redis integration for performance
|
||
|
|
5. **Event System**: Decoupled event handling between components
|
||
|
|
|
||
|
|
## Conclusion
|
||
|
|
|
||
|
|
The MVC refactoring has successfully transformed the application from a monolithic structure to a well-organized, maintainable, and scalable architecture. The separation of concerns makes the codebase easier to understand, test, and extend while maintaining all existing functionality.
|