lback.core package
This file serves as the initialization point for the ‘lback_framework/lback/core’ package. It is designed to expose the fundamental building blocks and core functionalities of the Lback web framework. This package centralizes the definition and management of the framework’s internal mechanisms, including application control, request/response handling, configuration, error management, routing, and server operations.
—
Key Components Exposed by this Package:
AppController (from .app_controller): The central orchestrator of the Lback application. This class is responsible for managing the application lifecycle, dispatching requests to the appropriate handlers, and coordinating various framework components like middleware, routing, and response generation. It acts as the main entry point for processing incoming HTTP requests.
BaseMiddleware (from .base_middleware): The foundational class for all middleware components within Lback. Middleware are components that process requests and responses before or after they reach the main application logic. This base class defines the interface and common behavior for custom middleware implementations.
Cache, CacheItem (from .cache): Components for managing application-level caching. * Cache: Provides an interface for storing and retrieving data in a temporary,
fast-access storage. It’s used to reduce redundant computations or database queries.
- CacheItem: Represents a single item stored within the cache, potentially including
metadata like expiration times.
Configuration Management (from .config_manager and .config): A set of utilities and classes for handling application configuration and settings. * SettingsFileHandler: Manages reading and writing application settings from configuration files. * load_config: A function to load the application’s configuration from various sources. * load_settings_module: A function to load settings from a Python module. * update_config: A function to dynamically update configuration settings. * start_settings_watcher: Initiates a process to monitor configuration files for changes. * sync_settings_to_config: Synchronizes settings from a source to the active configuration. * get_project_root: A utility function to determine the root directory of the Lback project. * Config: The main class representing the application’s configuration, holding all settings.
dispatcher (from .dispatcher_instance): Likely a pre-initialized instance of a signal dispatcher or event manager. This component allows different parts of the framework (and application) to communicate with each other by sending and receiving signals or events, promoting a loosely coupled architecture.
ErrorHandler (from .error_handler): Manages the handling and rendering of application errors and exceptions. This component intercepts unhandled exceptions, logs them, and generates appropriate error responses (e.g., custom error pages or JSON error messages) to the client.
Exceptions (from .exceptions): A collection of custom exception classes specific to the Lback framework. These exceptions provide more granular control over error handling and allow for specific error responses based on the type of issue encountered. * FrameworkException: Base exception for all Lback framework-specific errors. * Forbidden: Raised when a user attempts to access a resource they are not authorized for (HTTP 403). * HTTPException: Base exception for all HTTP-related errors. * BadRequest: Raised for invalid client requests (HTTP 400). * NotFound: Raised when a requested resource or URL is not found (HTTP 404). * RouteNotFound: Specifically raised when no matching route is found for a URL. * MethodNotAllowed: Raised when an unsupported HTTP method is used for a route (HTTP 405). * Unauthorized: Raised when authentication is required but has failed or not been provided (HTTP 401). * ConfigurationError: Raised for issues related to application configuration. * ValidationError: Raised when data validation fails. * ServerError: Raised for internal server errors (HTTP 500).
setup_logging (from .logging_setup): A function responsible for configuring the application’s logging system. It sets up loggers, handlers, and formatters to ensure that application events, errors, and debugging information are captured and stored appropriately.
Middleware Management (from .middleware_loader and .middleware_manager): Components for loading, creating, and managing middleware within the framework. * load_middlewares_from_config: Loads middleware definitions from the application configuration. * create_middleware: Instantiates a middleware class. * import_class: A utility function to dynamically import a Python class by its string path. * MiddlewareManager: Manages the execution order and application of multiple middleware components
to incoming requests and outgoing responses.
Middleware: A class or interface representing a single middleware component.
Response Handling (from .response): Classes for constructing various types of HTTP responses. * RedirectResponse: Creates an HTTP redirect response. * Response: The base class for all HTTP responses. * HTMLResponse: Creates an HTTP response with HTML content. * JSONResponse: Creates an HTTP response with JSON content.
Routing (from .router): Components for defining and managing URL routing within the application. * Route: Represents a single route definition, mapping a URL pattern to a view handler. * Router: The central component responsible for matching incoming request URLs to the
appropriate route and dispatching them to the corresponding view.
Server (from .server): Components related to running the Lback web server. * Server: The main class for the HTTP server, responsible for listening for incoming
requests and handing them off to the application.
- initialize_core_components: A function to initialize essential framework components
before the server starts.
- wsgi_application: The WSGI (Web Server Gateway Interface) application callable,
which is the entry point for WSGI-compatible web servers.
SignalDispatcher (from .signals): A system for implementing signals (or events) within the framework. This allows different parts of the application to send notifications and react to them, promoting a decoupled architecture.
Templates (from .templates): Components for rendering HTML templates. * TemplateRenderer: The main class for rendering templates, often integrating with
a templating engine (e.g., Jinja2).
- default_global_context: Provides default variables or functions available
to all templates.
custom_uppercase: A custom filter or function for template rendering.
custom_url_tag: A custom tag for generating URLs within templates.
Type Definitions (from .types): Custom type hints or definitions used throughout the framework for clarity and type checking. * Request: A type hint for the HTTP request object. * HTTPMethod: An enumeration or type hint for HTTP methods (GET, POST, etc.). * TypeConverter: A base class or type for URL path converters. * UploadedFile: A type hint for objects representing uploaded files. * UUIDConverter: A URL path converter specifically for UUIDs. * IntegerConverter: A URL path converter specifically for integers.
URL Utilities (from .urls_utils): Utilities for managing URL patterns. * Include: A function or class to include URL patterns from other modules,
allowing for modular URL configuration.
WebSocketServer (from .websocket): A component for handling WebSocket communication, enabling real-time, bidirectional communication between the server and clients.
WSGI Entry Point (from .wsgi_entry): Utilities related to the WSGI application setup. * create_wsgi_app: A function to create the WSGI application instance. * setup_logging: A function to configure logging specifically for the WSGI environment.
Submodules
lback.core.app_controller module
- class lback.core.app_controller.AppController(middleware_manager: MiddlewareManager, router: Router, template_renderer: TemplateRenderer, config: Config, admin_user_manager: AdminUserManager, session_manager: SessionManager, user_manager: UserManager, available_dependencies_instances: Dict[str, Any], dispatcher: SignalDispatcher)[source][source]
Bases:
objectManages the application flow for each incoming request. Responsible for routing, executing middleware chains (request and response), dispatching the request to the appropriate view, and managing the database session lifecycle (creation, commit, rollback, removal) within the request context. Also handles loading application components like routes and admin registrations from installed apps during initialization. Integrates SignalDispatcher to emit events throughout the request lifecycle.
- __init__(middleware_manager: MiddlewareManager, router: Router, template_renderer: TemplateRenderer, config: Config, admin_user_manager: AdminUserManager, session_manager: SessionManager, user_manager: UserManager, available_dependencies_instances: Dict[str, Any], dispatcher: SignalDispatcher)[source][source]
Initializes the AppController with necessary core dependencies. These dependencies are typically singletons managed globally (e.g., in core/server.py).
- Parameters:
middleware_manager – The MiddlewareManager instance responsible for executing middlewares.
router – The Router instance responsible for matching requests to views.
template_renderer – The TemplateRenderer instance for rendering templates.
config – The application Config instance containing application settings.
admin_user_manager – The AdminUserManager instance for admin user business logic.
session_manager – The SessionManager instance for session data storage.
user_manager – The UserManager instance for regular user business logic.
available_dependencies_instances – A dictionary mapping dependency names (str) to their instances, which will be made available on the request context for middlewares and views.
dispatcher – The SignalDispatcher instance for sending signals.
- add_route(path: str, view: Callable, methods: List[str] | None = None, name: str | None = None, requires_auth: bool = True)[source][source]
- handle_request(request: Request) Response[source][source]
Handles an incoming request by orchestrating the application flow. This includes: 1. Setting core dependencies on the request context. 2. Executing the request middleware chain. 3. Resolving the route using the router (if not short-circuited by middleware). 4. Dispatching the request to the appropriate view. 5. Managing the database session (commit on success, rollback on exception). 6. Executing the response middleware chain. 7. Returning the final Response object. Emits signals at key points in the request lifecycle.
- Parameters:
request – The incoming Request object. This object is mutable and carries context, user, session, etc., throughout the pipeline.
- Returns:
The final Response object to be sent back to the client.
- Raises:
RouteNotFound – If no route matches the request path.
MethodNotAllowed – If a route matches but the HTTP method is not allowed.
Exception – For any unhandled exceptions occurring during the pipeline (these should ideally be caught by a higher-level error handler).
lback.core.base_middleware module
- class lback.core.base_middleware.BaseMiddleware[source][source]
Bases:
ABCAbstract base class for all middleware classes in the application framework. Defines the required interface that all concrete middleware implementations must follow. Middlewares are processed by the MiddlewareManager during request and response handling.
- abstractmethod process_request(request: Any) Response | None[source][source]
Abstract method to process the incoming request before it reaches the view.
Concrete middleware classes must implement this method. It can modify the request object or return a Response object to short-circuit the request processing chain and prevent the view from being called.
- Parameters:
request – The incoming request object.
- Returns:
A Response object to immediately return to the client (short-circuit), or None to allow the request to proceed to the next middleware or the view.
- abstractmethod process_response(request: Any, response: Response) Response[source][source]
Abstract method to process the outgoing response after the view has been executed or a middleware has short-circuited the request.
Concrete middleware classes must implement this method. It can modify the response object before it is sent back to the client. This method is typically called in reverse order of middleware addition.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The initial Response object generated by the view or a preceding middleware.
- Returns:
The modified or original Response object. Must always return a Response.
lback.core.cache module
- class lback.core.cache.Cache[source][source]
Bases:
objectA simple thread-safe in-memory cache with optional time-to-live (TTL). Integrates SignalDispatcher to emit events for cache operations.
- delete(key: Any)[source][source]
Deletes a key-value pair from the cache. Emits ‘cache_item_deleted’ signal if the key was found and deleted.
- Parameters:
key – The cache key to delete.
- get(key: Any) Any | None[source][source]
Retrieves a value from the cache by key. Handles expired items. Emits ‘cache_item_fetched’, ‘cache_hit’, ‘cache_miss’, and ‘cache_item_expired’ signals.
- Parameters:
key – The cache key to retrieve.
- Returns:
The value associated with the key, or None if the key is not found or expired.
- has(key: Any) bool[source][source]
Checks if a key exists in the cache and is not expired. # No signals here, as this is a simple status check.
- Parameters:
key – The cache key to check.
- Returns:
True if the key exists and is not expired, False otherwise.
- keys() List[Any][source][source]
Returns a list of all non-expired keys currently in the cache. # No signals here, as this is a simple read operation.
- Returns:
A list of cache keys.
- set(key: Any, value: Any, ttl: int | None = None)[source][source]
Sets a key-value pair in the cache with an optional time-to-live (TTL). Emits ‘cache_item_set’ signal.
- Parameters:
key – The cache key.
value – The value to store.
ttl (Optional[int]) – The time-to-live in seconds. If None, the item does not expire.
lback.core.config module
- class lback.core.config.Config(config_file='config.json')[source][source]
Bases:
objectManages application configuration, loading with priority: Environment Variables -> Config File -> Defaults. Provides access to settings and generates derived values.
- property DATABASE_URI
Generates the database connection URI based on configured engine and credentials.
lback.core.config_manager module
- class lback.core.config_manager.SettingsFileHandler(settings_path, config_file='config.json')[source][source]
Bases:
FileSystemEventHandlerHandles file system events for settings.py.
- lback.core.config_manager.get_project_root()[source][source]
Finds the project root directory by searching for settings.py.
- lback.core.config_manager.load_config(config_file='config.json')[source][source]
Load configuration from JSON file. This is mainly for reading existing config before updating.
- lback.core.config_manager.load_settings_module(settings_path)[source][source]
Dynamically loads/reloads a Python file as a module.
- lback.core.config_manager.start_settings_watcher(project_root)[source][source]
Starts the file system watcher for settings.py.
lback.core.dispatcher_instance module
lback.core.error_handler module
- class lback.core.error_handler.ErrorHandler(config: Config, template_renderer: TemplateRenderer, router: Router)[source][source]
Bases:
objectHandles application errors and exceptions, generating appropriate responses. Provides specific handlers for common HTTP errors (404, 405, 500) and unhandled exceptions. Integrates SignalDispatcher to emit events whenever an error response is generated.
- __init__(config: Config, template_renderer: TemplateRenderer, router: Router)[source][source]
Initializes the ErrorHandler. Emits ‘error_handler_initialized’ signal.
- handle_403(request: Any, message: str = 'Forbidden: You do not have permission to access this resource.') Response[source][source]
Handles 403 Forbidden errors. Generates a 403 response, potentially with debug information in DEBUG mode. Emits ‘error_response_generated’ signal with status 403.
- Parameters:
request – The incoming request object.
message – The specific message to display for the forbidden error.
- Returns:
An HTMLResponse with status 403.
- handle_404(request: Any) Response[source][source]
Handles 404 Not Found errors. Generates a 404 response, potentially with debug information in DEBUG mode. Emits ‘error_response_generated’ signal with status 404.
- Parameters:
request – The incoming request object.
- Returns:
An HTMLResponse with status 404.
- handle_405(request: Any, allowed_methods: list) Response[source][source]
Handles 405 Method Not Allowed errors. Generates a 405 response, potentially with debug information in DEBUG mode. Emits ‘error_response_generated’ signal with status 405.
- Parameters:
request – The incoming request object.
allowed_methods – A list of allowed HTTP methods for the requested path.
- Returns:
An HTMLResponse with status 405 and an ‘Allow’ header.
- handle_500(error: Exception) Response[source][source]
Handles generic 500 Internal Server Errors (explicitly raised 500). Generates a generic 500 response. Emits ‘error_response_generated’ signal with status 500.
- Parameters:
error – The exception object that caused the 500 error.
- Returns:
An HTMLResponse with status 500.
- handle_custom_error(status_code: int, message: str) Response[source][source]
Handles custom errors with a specific status code and message. Generates a custom error response. Emits ‘error_response_generated’ signal with the custom status code.
- Parameters:
status_code – The HTTP status code for the error.
message – The custom error message.
- Returns:
An HTMLResponse with the custom status code.
- handle_exception(exception: Exception, request: Any) Response[source][source]
Handles unhandled exceptions that occur during request processing. Generates a 500 response, potentially with detailed debug information in DEBUG mode. Emits ‘unhandled_exception_response_generated’ signal.
- Parameters:
exception – The unhandled exception object.
request – The incoming request object.
- Returns:
An HTMLResponse with status 500.
lback.core.exceptions module
- exception lback.core.exceptions.BadRequest(message: str | None = None, data: Any | None = None)[source][source]
Bases:
HTTPException- message = 'Bad Request'
- status_code = 400
- exception lback.core.exceptions.ConfigurationError[source][source]
Bases:
FrameworkException
- exception lback.core.exceptions.Forbidden(message: str | None = None, data: Any | None = None)[source][source]
Bases:
HTTPException- message = 'Forbidden'
- status_code = 403
- exception lback.core.exceptions.HTTPException(message: str | None = None, status_code: int | None = None, data: Any | None = None)[source][source]
Bases:
FrameworkException- data: Any | None = None
- message = 'An unexpected error occurred.'
- status_code = 500
- exception lback.core.exceptions.MethodNotAllowed(path: str, method: str, allowed_methods: list, message: str | None = None)[source][source]
Bases:
HTTPException- message = 'Method Not Allowed'
- status_code = 405
- exception lback.core.exceptions.NotFound(message: str | None = None, data: Any | None = None)[source][source]
Bases:
HTTPException- message = 'Not Found'
- status_code = 404
- exception lback.core.exceptions.RouteNotFound(path: str, method: str, message: str | None = None)[source][source]
Bases:
NotFound- message = 'Route Not Found'
- exception lback.core.exceptions.ServerError(message: str | None = None, data: Any | None = None)[source][source]
Bases:
HTTPException- message = 'Internal Server Error'
- status_code = 500
lback.core.logging_setup module
lback.core.middleware_loader module
- lback.core.middleware_loader.create_middleware(middleware_class: Type[Any], available_dependencies_instances: Dict[str, Any], params: Dict[str, Any] | None = None) Any[source][source]
Instantiates a middleware class, injecting dependencies based on its constructor signature, the provided available dependency instances, and parameters from config.
- Parameters:
middleware_class – The middleware class (not instance) to instantiate.
available_dependencies_instances – A dictionary mapping dependency names (str) to their instances.
params – A dictionary of parameters to pass to the middleware’s __init__, typically from config.
- Returns:
An instance of the middleware_class.
- Raises:
TypeError – If the middleware class requires a dependency or parameter that is not available or cannot be matched.
Exception – For other errors during inspection or instantiation.
- lback.core.middleware_loader.import_class(class_path: str) Type[Any][source][source]
Dynamically imports a class from a string path representing its full location (e.g., ‘my_app.middlewares.MyCustomMiddleware’).
- Parameters:
class_path – The full string path of the class.
- Returns:
The imported class type.
- Raises:
ImportError – If the module or class cannot be imported.
TypeError – If the imported object is not a class.
- lback.core.middleware_loader.load_middlewares_from_config(middleware_manager: MiddlewareManager, config: Config, available_dependencies_instances: Dict[str, Any])[source][source]
Loads and registers middleware instances based on a list defined in the application configuration. Reads the middleware list from a Config object, imports classes, and instantiates them using the available dependencies and parameters from the config, adding them to MiddlewareManager in order.
- Parameters:
middleware_manager – The MiddlewareManager instance to add middlewares to.
config – The Config instance containing the middleware list (e.g., config.MIDDLEWARES).
available_dependencies_instances – A dictionary mapping dependency names (str) to their instances.
lback.core.middleware_manager module
- class lback.core.middleware_manager.Middleware(*args, **kwargs)[source][source]
Bases:
ProtocolProtocol defining the interface for middleware objects. Any class implementing these methods can be considered a Middleware.
- process_request(request: Any) Response | None[source][source]
Process an incoming request before the view is dispatched. Can modify the request or return a Response to short-circuit the request processing chain.
- Parameters:
request – The incoming request object.
- Returns:
A Response object to stop further processing and return this response immediately, or None to allow the request to proceed to the next middleware or the view.
- process_response(request: Any, response: Response) Response[source][source]
Process the outgoing response after the view has been executed (or a middleware short-circuited). Can modify the response. This method is called in reverse order of middleware addition.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The Response object generated by the view or a preceding middleware.
- Returns:
The modified or original Response object. Must always return a Response.
- class lback.core.middleware_manager.MiddlewareManager[source][source]
Bases:
objectManages a list of middleware instances and applies them to requests and responses. Middlewares are processed in the order they are added for process_request and in reverse order for process_response. Integrates SignalDispatcher to emit events during middleware processing.
- __init__()[source][source]
Initializes the MiddlewareManager with an empty list of middlewares. Emits ‘middleware_manager_initialized’ signal.
- add_middleware(middleware: Middleware)[source][source]
Registers a new middleware component instance. Middlewares should be instances of classes implementing the Middleware Protocol. Emits ‘middleware_added’ signal on success. Emits ‘middleware_add_failed’ signal on failure (invalid type).
- Parameters:
middleware – The middleware instance to add.
- Raises:
TypeError – If the provided object does not implement the Middleware Protocol (i.e., missing process_request or process_response methods).
- process_request(request: Any) Response | None[source][source]
Applies the process_request method of each middleware in the order they were added. Stops the chain and returns a Response object if any middleware returns one. Exceptions raised by middlewares are caught and result in a 500 Internal Server Error response. Emits ‘middleware_request_processing_started’, ‘middleware_request_processing_finished’, ‘middleware_process_request_started’, ‘middleware_process_request_succeeded’, ‘middleware_process_request_failed’, and ‘middleware_request_short_circuited’ signals.
- Parameters:
request – The incoming request object. This object is passed through the chain and can be modified by middlewares (e.g., adding context, user).
- Returns:
A Response object if a middleware short-circuits the chain or an error occurs, otherwise returns None to indicate that the request should proceed to the view.
- process_response(request: Any, response: Response) Response[source][source]
Applies the process_response method of each middleware in reverse order of addition. Starts with the response generated by the view or a short-circuiting middleware. Each middleware receives the output of the previous one. Exceptions raised by middlewares are caught and logged, but the response chain attempts to continue. Emits ‘middleware_response_processing_started’, ‘middleware_response_processing_finished’, ‘middleware_process_response_started’, ‘middleware_process_response_succeeded’, and ‘middleware_process_response_failed’ signals.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The initial Response object generated by the view or a short-circuiting middleware.
- Returns:
The final Response object after all response middlewares have been applied.
- remove_middleware(middleware: Middleware)[source][source]
Removes a specific middleware instance from the manager. Emits ‘middleware_removed’ signal on success. Emits ‘middleware_remove_failed’ signal on failure (not found).
- Parameters:
middleware – The middleware instance to remove.
- remove_middleware_by_class(middleware_class: Type[Middleware])[source][source]
Removes all instances of a given middleware class from the chain. Emits ‘middleware_removed_by_class’ signal on success (if any were removed). Emits ‘middleware_remove_by_class_failed’ signal on failure (invalid class type).
- Parameters:
middleware_class – The class of the middleware instances to remove. Should be a class that implements the Middleware Protocol.
lback.core.response module
- class lback.core.response.HTMLResponse(content: str, status_code: int = 200, headers: Dict[str, str] | None = None)[source][source]
Bases:
Response
- class lback.core.response.JSONResponse(data: Any = None, status_code: int = 200, headers: Dict[str, str] | None = None, message: str | None = None)[source][source]
Bases:
Response
- class lback.core.response.RedirectResponse(redirect_url: str, status_code: int = 302, headers: Dict[str, str] | None = None)[source][source]
Bases:
Response
- class lback.core.response.Response(body: Any = None, status_code: int = 200, headers: Dict[str, str] | None = None, content_type: str | None = None)[source][source]
Bases:
object- static bad_request(message: str = 'Bad Request') JSONResponse[source][source]
- static conflict(message: str = 'Conflict') JSONResponse[source][source]
- static error(message: str = 'Internal Server Error', status_code: int = 500) JSONResponse[source][source]
- static forbidden(message: str = 'Forbidden') JSONResponse[source][source]
- static html(content: str, status_code: int = 200, headers: Dict[str, str] | None = None) HTMLResponse[source][source]
- static json(data: Any = None, status_code: int = 200, headers: Dict[str, str] | None = None, message: str | None = None) JSONResponse[source][source]
- static not_found(message: str = 'Not Found') JSONResponse[source][source]
- static redirect(redirect_url: str, status_code: int = 302, headers: Dict[str, str] | None = None) RedirectResponse[source][source]
- static unauthorized(message: str = 'Unauthorized') JSONResponse[source][source]
lback.core.router module
- class lback.core.router.Route(path: str, view: Callable, methods: List[str] | None = None, name: str | None = None, requires_auth: bool = True)[source][source]
Bases:
objectRepresents a single registered route in the routing system. Stores the path pattern, view callable, allowed methods, optional name, and whether the route requires authentication.
- __init__(path: str, view: Callable, methods: List[str] | None = None, name: str | None = None, requires_auth: bool = True)[source][source]
Initializes a Route object.
- Parameters:
path – The URL path pattern (e.g., ‘/users/{user_id:int}’).
view – The view function or class that will handle matching requests.
methods – A list of allowed HTTP methods (e.g., [‘GET’, ‘POST’]). If None, all methods are allowed.
name – An optional name for the route (useful for URL reversal).
requires_auth – Boolean indicating if this route requires user authentication. Defaults to True.
- match(path: str, method: str) Dict[str, Any] | None[source][source]
Checks if the route’s path pattern matches the given path and if the method is allowed.
- Parameters:
path – The incoming request path string.
method – The incoming request HTTP method string (e.g., ‘GET’, ‘POST’).
- Returns:
A dictionary of path variables if the path and method match. Returns a dictionary {‘_method_mismatch’: True, ‘_allowed_methods’: […]} if the path matches but the method is not allowed. Returns None if the path does not match the route’s pattern.
- class lback.core.router.Router[source][source]
Bases:
objectManages a collection of Route objects and provides methods for matching incoming requests to registered routes and generating URLs.
- add_route(path: str, view: Callable, methods: List[str] | None = None, name: str | None = None, requires_auth: bool = True)[source][source]
Adds a new route definition to the router.
- Parameters:
path – The URL path pattern string.
view – The view function or class to handle requests matching the pattern.
methods – A list of HTTP methods allowed for this route (e.g., [‘GET’, ‘POST’]). If None, attempts to get methods from a ‘methods’ attribute on the view callable. If still None, all methods are allowed.
name – An optional name for the route (useful for URL reversal).
requires_auth – Boolean indicating if this route requires user authentication. Defaults to True.
- get_route_by_name(name: str) Route | None[source][source]
Retrieves a Route object based on its name.
- Parameters:
name – The name of the route to find.
- Returns:
The Route object if found, otherwise None.
- remove_route(path: str, methods: List[str] | None = None)[source][source]
Removes a route or specific methods for a route based on path and optional methods.
- Parameters:
path – The path of the route(s) to remove.
methods – A list of specific HTTP methods to remove for the given path. If None, all routes matching the path are removed.
- resolve(path: str, method: str) Tuple[Callable, Dict[str, Any], bool][source][source]
Finds a matching route for the given path and method.
Iterates through registered routes and uses the Route.match method. If a path matches but the method is not allowed, it collects allowed methods.
- Parameters:
path – The incoming request path string.
method – The incoming request HTTP method string.
- Returns:
The view callable for the matched route.
A dictionary of extracted path variables.
A boolean indicating if the route requires authentication.
- Return type:
A tuple containing
- Raises:
RouteNotFound – If no route matches the path.
MethodNotAllowed – If a route matches the path but not the method.
- url_for(name: str, **params: Any) str[source][source]
Generates a URL for a route based on its name and provided parameters.
- Parameters:
name – The name of the route.
**params – Keyword arguments for the path variables in the route pattern.
- Returns:
The generated URL string.
- Raises:
ValueError – If no route with the given name is found or if required parameters are missing for the route pattern.
lback.core.server module
- class lback.core.server.Server[source][source]
Bases:
objectThe main server class to set up and run the application.
- lback.core.server.initialize_core_components() None[source][source]
Initializes all core framework components and sets module-level variables. This function should be called once before running the server or adding routes. Includes loading settings, installed apps, and initializing managers.
- lback.core.server.wsgi_application(environ: Dict[str, Any], start_response: Callable) Any[source][source]
WSGI application entry point for handling incoming requests. Parses WSGI environment, creates a Request object, delegates to AppController, handles errors, and returns a WSGI-compatible response. Accesses core components from module-level variables (initialized by initialize_core_components). CORRECTED: Defers body reading for methods handled by BodyParsingMiddleware
to prevent premature stream exhaustion.
lback.core.signals module
- class lback.core.signals.SignalDispatcher[source][source]
Bases:
objectSignal Dispatcher for the Lback framework.
This class allows registering receivers (callable functions or methods) for specific signals, and dispatching signals to invoke all registered receivers.
- connect(signal_name: str, receiver: Callable[[...], Any])[source][source]
Registers a receiver function or method to a specific signal.
- Parameters:
signal_name (str) – The name of the signal to connect the receiver to.
receiver (Callable) – The function or method to be called when the signal is dispatched. Must be callable.
- disconnect(signal_name: str, receiver: Callable[[...], Any])[source][source]
Unregisters a receiver function or method from a specific signal.
- Parameters:
signal_name (str) – The name of the signal to disconnect the receiver from.
receiver (Callable) – The function or method to be unregistered.
- send(signal_name: str, sender: Any | None = None, **kwargs: Any)[source][source]
Dispatches a signal, invoking all receivers registered to it.
- Parameters:
signal_name (str) – The name of the signal to dispatch.
sender (Any, optional) – The object sending the signal. Typically the instance where the event occurred.
**kwargs – Additional keyword arguments to pass to the receivers.
- Returns:
A list of tuples containing each receiver and its return value or exception.
- Return type:
list
lback.core.templates module
- class lback.core.templates.TemplateRenderer(config: Config, db_session: Any | None = None, template_model: Any | None = None, db_loader_func: Callable[[str, Any | None], str | None] | None = None)[source][source]
Bases:
objectManages the rendering of templates using Jinja2. Supports loading templates from file system directories and optionally from a database. Integrates SignalDispatcher to emit events during the rendering process.
- __init__(config: Config, db_session: Any | None = None, template_model: Any | None = None, db_loader_func: Callable[[str, Any | None], str | None] | None = None)[source][source]
Initializes the TemplateRenderer.
- Parameters:
config – The application Config instance.
db_session – Optional SQLAlchemy session for loading templates from DB.
template_model – Optional SQLAlchemy model class for templates stored in DB.
db_loader_func – Optional custom function to load template content from DB. It should accept template_name (str) and db_session (Optional[Any]) and return template content (str) or None.
- load_template_from_db(template_name: str) str | None[source][source]
Attempts to load template content from the database using a custom loader or a default model lookup. Emits ‘db_template_loaded’ or ‘db_template_load_failed’ signals.
- render_from_db_to_string(template_name: str, **context: Any) str[source][source]
Loads and renders a template from the database to a string. Emits ‘template_rendering_started’ and ‘template_rendered’ or ‘template_rendering_failed’ signals. Raises TemplateNotFound or other exceptions on failure.
- lback.core.templates.custom_uppercase(value)[source][source]
Custom Jinja2 filter to convert a value to uppercase if it’s a string.
lback.core.types module
- class lback.core.types.HTTPMethod(*values)[source][source]
Bases:
EnumRepresents standard HTTP methods.
- DELETE = 'DELETE'
- GET = 'GET'
- HEAD = 'HEAD'
- OPTIONS = 'OPTIONS'
- PATCH = 'PATCH'
- POST = 'POST'
- PUT = 'PUT'
- class lback.core.types.IntegerConverter[source][source]
Bases:
TypeConverter- property openapi_type: Dict[str, Any]
Returns the OpenAPI schema type for this converter.
- class lback.core.types.Request(path: str, method: str | HTTPMethod, body: str | bytes | None, headers: Dict[str, str], environ: Dict[str, Any])[source][source]
Bases:
objectRepresents an incoming HTTP request. This object carries all request information (path, method, headers, body, query params) and serves as a context object to pass data (user, session, db_session, path_params, dependencies) through the middleware chain and to the view. Includes enhancements for file uploads, cookies, META, etc., populated by middlewares.
- property DATA: Dict[str, Any]
Provides access to parsed body data, suitable for APIs accepting JSON or other structured data in the body (PUT, PATCH, POST). Assumes Body Parsing Middleware has populated request.parsed_body. Returns an empty dictionary if no parsed body data is available.
- property GET: Dict[str, Any]
Provides access to parsed query parameters. Equivalent to request.query_params.
- property POST: Dict[str, Any]
Provides access to parsed body data typically from form submissions (application/x-www-form-urlencoded or multipart/form-data). This data is expected to be populated in request.parsed_body by a Body Parsing Middleware. Returns an empty dictionary if the method is not POST or no form data is available.
- __init__(path: str, method: str | HTTPMethod, body: str | bytes | None, headers: Dict[str, str], environ: Dict[str, Any])[source][source]
Initializes a Request object with raw request data and WSGI environment.
- add_context(key: str, value: Any)[source][source]
Adds a single key-value pair to the request context dictionary (alias for set_context).
- property admin_registry: Any | None
Provides access to the AdminRegistry instance from request context.
- property admin_user_manager: Any | None
Provides access to the AdminUserManager instance from request context.
- property body_bytes: bytes
Returns the request body as bytes. Reads the body from the stream if not already read. Caches the result. Note: This reads the entire body into memory. Use get_body_stream() for streaming large request bodies before accessing this property.
- property body_text: str | None
Returns the request body as text (UTF-8 decoded). Caches the result of decoding. Returns None if decoding fails or body is empty.
- build_absolute_uri(location: str | None = None) str[source][source]
Builds an absolute URI for a given location or the current request path. Mimics Django’s build_absolute_uri.
- Parameters:
location – A path or URL string. If None, uses the current request path. Can be a relative path, absolute path (starting with ‘/’), or a full URL (with scheme and host).
- Returns:
The built absolute URI as a string.
- property context_data: Dict[str, Any]
Provides public access to a combined view of context data.
- property db_session: Session | None
Property to access the database session.
- property dispatcher: SignalDispatcher | None
Provides access to the SignalDispatcher instance from request context.
- property environ: Dict[str, Any]
Provides access to the raw WSGI environment dictionary.
- property error_handler: ErrorHandler | None
Provides access to the ErrorHandler instance from request context.
- property files: Dict[str, UploadedFile | List[UploadedFile]]
Provides access to uploaded files (from multipart/form-data). This data is expected to be populated by a Body Parsing Middleware. Returns a dictionary where keys are form field names and values are UploadedFile objects or lists of UploadedFile objects for multiple files with the same name. Returns an empty dictionary if no files were uploaded or parsing failed.
- get_body_stream() BinaryIO | None[source][source]
Returns the raw input stream from the WSGI environment (‘wsgi.input’). Useful for streaming large request bodies without loading into memory. Note: Reading from this stream consumes the data. If you read from the stream, subsequent access to request.body_bytes or request.body_text might be empty or incomplete unless the stream supports seeking. The stream is typically available only before the body_bytes property is accessed for the first time (as body_bytes reads the whole stream).
- get_context(key: str, default: Any | None = None) Any | None[source][source]
Retrieves a value from the internal context dictionary (_context). Known context items with dedicated properties should be accessed via those properties (e.g., request.db_session, request.user) for type safety and clarity. This method is for accessing other arbitrary data stored in the context dictionary via set_context().
- property get_host: str
Returns the hostname for the request, looking at standard headers first, then falling back to WSGI environment variables.
- property is_secure: bool
Returns True if the request is secure (HTTPS), checking WSGI environment and common headers set by proxies.
- property parsed_body: Dict[str, Any] | None
Provides access to parsed body data (from form-urlencoded or JSON). This data is expected to be populated by a Body Parsing Middleware. Returns a dictionary or None if no body or parsing failed.
- property path_params: Dict[str, Any]
Property to access path parameters extracted by the router.
- property router: Any | None
Provides access to the Router instance from request context.
- property session: AppSession | None
Provides access to the Session instance from request context.
- property session_manager: Any | None
Provides access to the SessionManager instance from request context.
- set_context(**kwargs: Any)[source][source]
Sets key-value pairs in the request context dictionary. Also updates dedicated internal attributes if setters are defined and the key matches a property name. Used by AppController and Middlewares to attach request-scoped data.
- property template_renderer: TemplateRenderer | None
Provides access to the TemplateRenderer instance from request context.
- property user: Any | None
Provides access to the authenticated user from request context.
- property user_manager: Any | None
Provides access to the UserManager instance from request context.
- class lback.core.types.TypeConverter[source][source]
Bases:
objectBase class for path variable type converters.
- property openapi_type: Dict[str, Any]
Returns the OpenAPI schema type for this converter.
- class lback.core.types.UUIDConverter[source][source]
Bases:
TypeConverter- property openapi_type: Dict[str, Any]
Returns the OpenAPI schema type for this converter.
- class lback.core.types.UploadedFile(filename: str, content_type: str, file: BinaryIO, field_name: str, size: int, headers: Dict[str, str] = None)[source][source]
Bases:
object- __init__(filename: str, content_type: str, file: BinaryIO, field_name: str, size: int, headers: Dict[str, str] = None)[source][source]
Represents a single uploaded file from a multipart/form-data request.
- Parameters:
filename – The name of the uploaded file.
content_type – The content type of the file (e.g., ‘image/png’).
file – A file-like object containing the file content.
field_name – The name of the form field that contained this file.
size – The size of the file in bytes.
headers – Optional dictionary of headers specific to the file part (e.g., Content-Disposition).