Instruction file imported from krizzo101/arxiv-py-enhanced (
.cursor/rules/3000-framework-architecture.mdc). Copyright stays with the author.
framework-architecture
1.1.0
Metadata
{ "rule_id": "3000-framework-architecture", "taxonomy": { "category": "Core Framework Design", "parent": "Core Framework DesignRule", "ancestors": [ "Rule", "Core Framework DesignRule" ], "children": [ "3001-architecture-best-practices", "3002-architecture-patterns", "3003-architecture-guidelines" ] }, "tags": [ "framework", "architecture", "design", "core" ], "priority": "50", "inherits": [ "000", "020", "030" ] }
Overview
{ "purpose": "MUST provide a structured approach to framework architecture design TO ensure components are modular, maintainable, and aligned with system goals", "application": "SHOULD be applied during the initial phases of framework development WHEN defining the overall architecture and component interactions", "importance": "This rule MATTERS because a well-defined architecture enhances system scalability, facilitates collaboration among developers, and reduces technical debt over time" }
design_patterns
{ "description": "MUST utilize established design patterns WHEN designing core framework components TO promote reuse and maintainability.", "requirements": [ "MUST identify and apply relevant design patterns such as MVC, Singleton, or Factory based on component functionality.", "SHOULD document the rationale for selecting specific design patterns TO facilitate understanding among team members.", "NEVER deviate from established patterns without a thorough justification TO maintain consistency across the framework." ] }
modularity
{ "description": "MUST ensure that components are modular WHEN structuring the framework TO enhance maintainability and scalability.", "requirements": [ "MUST define clear interfaces for each component TO enable independent development and testing.", "SHOULD limit component dependencies TO reduce coupling and increase flexibility in component usage.", "NEVER allow components to contain multiple responsibilities TO adhere to the Single Responsibility Principle." ] }
scalability
{ "description": "MUST design the framework architecture with scalability in mind TO accommodate future growth and feature enhancements.", "requirements": [ "MUST implement scalable patterns such as Microservices or Event-Driven Architecture depending on project requirements.", "SHOULD include load balancing and caching strategies TO optimize performance under increased load.", "NEVER hard-code limits on component scaling TO allow for dynamic adjustment based on system needs." ] }
# Import necessary libraries
from flask import Flask, request, jsonify
from werkzeug.exceptions import NotFound, BadRequest
# Initialize the Flask application
app = Flask(__name__)
# In-memory database simulation for users
database = {}
user_id_counter = 1
# User Model - Represents the User entity
class User:
def __init__(self, username, email):
self.id = user_id_counter
self.username = username
self.email = email
def to_dict(self):
return {'id': self.id, 'username': self.username, 'email': self.email}
# Controller - Responsible for handling requests and responses
class UserController:
@staticmethod
def create_user(data):
global user_id_counter
if 'username' not in data or 'email' not in data:
raise BadRequest('Username and Email are required.')
user = User(data['username'], data['email'])
database[user_id_counter] = user
user_id_counter += 1
return user.to_dict(), 201
@staticmethod
def get_user(user_id):
user = database.get(user_id)
if not user:
raise NotFound('User not found.')
return user.to_dict(), 200
# API Routes
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
return UserController.create_user(data)
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
return UserController.get_user(user_id)
# Error Handling
@app.errorhandler(NotFound)
def handle_not_found(error):
return jsonify({'error': str(error)}), 404
@app.errorhandler(BadRequest)
def handle_bad_request(error):
return jsonify({'error': str(error)}), 400
# Run the application
if __name__ == '__main__':
app.run(debug=True)
This example demonstrates the principles of the framework-architecture rule in the core framework design category by implementing a modular User Management System using the MVC (Model-View-Controller) design pattern. The code is structured into clear components:
-
Model (User): Represents the user entity with attributes and a method to convert it to a dictionary format. This adheres to the Single Responsibility Principle, as the User class is solely responsible for the user representation.
-
Controller (UserController): Manages the business logic for user creation and retrieval, encapsulating the logic away from the route definitions. The controller methods handle necessary error checks and throw appropriate exceptions which are then caught by the error handling functions.
-
API Routes: Define the endpoints for creating and retrieving users. Each route is clearly associated with its respective controller method, enhancing readability and maintainability.
-
Error Handling: Proper error handling ensures that the application provides meaningful error messages and maintains robustness. Custom error handlers for
NotFoundandBadRequestexceptions enhance user experience and debugging. -
Modularity and Scalability: The separation of concerns through MVC allows each component to be developed, tested, and maintained independently. As the application grows, additional features (like updating or deleting users) can be implemented without significant refactoring of existing code, thus ensuring scalability.
Overall, the example adheres to best practices by employing modular design, proper error handling, and clear code organization, demonstrating how to structure core components effectively for consistency and scalability.