lback.models package

This file serves as the initialization point for the ‘lback_framework/lback/models’ package. It is designed to expose the core components necessary for defining and managing the application’s data models within the Lback web framework. This package centralizes the definition of database schemas, relationships between entities, and provides utilities for interacting with the underlying database.

Key Components Exposed by this Package:

  1. AdminUser, Role, Permission (from .adminuser): These classes define the data models related to the administrative users and their access control within the application.

    • AdminUser: Represents an administrative user account, typically with elevated

      privileges for managing the application’s backend.

    • Role: Defines a specific role that can be assigned to users (e.g., ‘admin’, ‘editor’).

      Roles are used to group permissions and simplify access control management.

    • Permission: Represents a specific action or resource that a user can be

      granted access to (e.g., ‘can_edit_products’, ‘can_view_reports’).

  2. BaseModel (from .base): The foundational base class for all data models within the Lback framework. This class typically provides common functionalities and attributes that all models share, such as primary key definitions, timestamp fields (created_at, updated_at), and potentially methods for common database operations.

  3. DatabaseManager (from .database): A component responsible for managing the database connection and session lifecycle. This class typically handles the initialization of the database engine, creation of database sessions, and other low-level database interactions, providing a centralized point for database access.

  4. Product (from .product): A specific data model representing a product within the application. This class defines the schema for product-related data, such as name, description, price, and other relevant attributes. It’s an example of an application-specific model.

  5. Session (from .session): A data model representing a user’s session. This class is used to store and manage session-specific data on the server side, enabling the application to maintain user state across multiple requests (e.g., login status, shopping cart).

  6. User, Group, UserPermission (from .user): These classes define the data models related to standard application users and their access control.

    • User: Represents a general user account within the application.

    • Group: Defines a group that users can belong to, often used to assign

      permissions or roles to multiple users collectively.

    • UserPermission: Represents a direct permission granted to a specific user,

      allowing for fine-grained access control beyond roles or groups.

Submodules

lback.models.adminuser module

class lback.models.adminuser.AdminUser(**kwargs)[source][source]

Bases: BaseModel

Represents an administrative user in the system. Admin users can have roles and permissions.

__repr__() str[source][source]

Provides a developer-friendly string representation of the AdminUser.

created_at
email
has_permission(permission_name: str) bool[source][source]

Checks if the admin user has a specific permission. Superusers have all permissions. Otherwise, checks the user’s role’s permissions. Emits ‘admin_user_permission_checked’ signal.

Parameters:

permission_name – The name string of the permission to check.

Returns:

True if the user has the permission, False otherwise.

id
is_superuser
password
property permissions: Set[str]

Returns a set of permission names associated with this user’s role. This property is used by the PermissionRequired decorator.

role
role_id
updated_at
username
class lback.models.adminuser.Permission(**kwargs)[source][source]

Bases: BaseModel

Represents a specific permission that can be assigned to roles.

__repr__() str[source][source]

Provides a developer-friendly string representation of the Permission.

created_at
description
id
name
roles
updated_at
class lback.models.adminuser.Role(**kwargs)[source][source]

Bases: BaseModel

Represents a role that groups multiple permissions. Admin users can be assigned roles.

__repr__() str[source][source]

Provides a developer-friendly string representation of the Role.

add_permission(permission: Permission)[source][source]

Adds a permission to this role. Emits ‘role_permission_added’ signal on success. Emits ‘role_permission_operation_failed’ signal on failure (invalid type, already exists).

Parameters:

permission – The Permission object to add.

admin_users
created_at
description
id
name
permissions
remove_permission(permission: Permission)[source][source]

Removes a permission from this role. Emits ‘role_permission_removed’ signal on success. Emits ‘role_permission_operation_failed’ signal on failure (invalid type, not found).

Parameters:

permission – The Permission object to remove.

updated_at

lback.models.base module

class lback.models.base.BaseModel(**kwargs: Any)[source][source]

Bases: Base

Abstract base class for all SQLAlchemy models in the application. Provides common fields like primary key ID, creation timestamp, and update timestamp. Integrates SignalDispatcher to emit events related to model lifecycle (specifically validation).

__repr__() str[source][source]

Provides a developer-friendly string representation of the model instance.

created_at = Column(None, DateTime(), table=None, nullable=False, default=CallableColumnDefault(<function datetime.utcnow>))
id = Column(None, Integer(), table=None, primary_key=True, nullable=False)
to_dict() Dict[str, Any][source][source]

Returns a dictionary representation of the model instance. Note: This is a basic implementation and might not handle relationships or complex types well. Consider using a dedicated serialization library for more complex scenarios.

updated_at = Column(None, DateTime(), table=None, nullable=False, onupdate=CallableColumnDefault(<function datetime.utcnow>), default=CallableColumnDefault(<function datetime.utcnow>))
validate() None[source][source]

Placeholder method for model validation. Subclasses should override this method to implement specific validation logic before saving or updating an instance. Should raise a ValidationError or similar exception if validation fails. Emits ‘model_pre_validate’ signal before any validation logic runs.

lback.models.database module

class lback.models.database.DatabaseManager[source][source]

Bases: object

Manages the database connection and session factory as a singleton. Responsible for creating the SQLAlchemy engine and providing a scoped session factory for managing database sessions within the application context (e.g., per request). Emits signals for key database lifecycle events.

property Session: Any | None

Returns the scoped session factory. Calling this property returns the factory function that provides the current session for the calling thread/context.

Returns:

The scoped session factory, or None if initialization failed.

__init__()[source][source]

Initializes the DatabaseManager. This constructor should ideally only be called once via get_instance(). It sets up the database engine and session factory based on Config settings. Emits ‘db_manager_initialized’ signal on success. Emits ‘db_operation_failed’ signal on initialization failure.

__repr__() str[source][source]

Provides a developer-friendly string representation of the DatabaseManager.

create_all_tables()[source][source]

Creates all database tables defined by the models associated with Base.metadata. Requires the engine to be successfully initialized. Emits ‘db_tables_created’ signal on success. Emits ‘db_operation_failed’ signal on failure.

create_session() Session[source][source]

Creates and returns a new SQLAlchemy database session using the scoped session factory. This method is intended to be called once per request by the SQLAlchemySessionMiddleware.

dispose_engine()[source][source]

Disposes the database engine’s connection pool. This should be called on application shutdown to release database connections. Emits ‘db_engine_disposed’ signal on success. Emits ‘db_operation_failed’ signal on failure.

drop_all_tables()[source][source]

Drops all database tables defined by the models associated with Base.metadata. Use with caution, as this will delete all data. Requires the engine to be successfully initialized. Emits ‘db_tables_dropped’ signal on success. Emits ‘db_operation_failed’ signal on failure.

property engine: Any | None

Returns the SQLAlchemy engine instance.

Returns:

The SQLAlchemy engine, or None if initialization failed.

classmethod get_instance() DatabaseManager[source][source]

Gets the singleton instance of the DatabaseManager. Initializes the manager if it hasn’t been already.

Returns:

The singleton DatabaseManager instance.

lback.models.product module

class lback.models.product.Product(**kwargs)[source][source]

Bases: BaseModel

Represents a product in the inventory. Inherits common fields from BaseModel. Includes validation rules for product attributes using SQLAlchemy @validates. Integrates SignalDispatcher to emit events related to product-specific actions.

__repr__() str[source][source]

Provides a developer-friendly string representation of the Product instance.

apply_discount(discount_percentage: float)[source][source]

Applies a percentage discount to the product price. Raises ValueError if the discount percentage is invalid. Emits ‘product_discount_applied’ signal on success. Emits ‘product_discount_application_failed’ signal on failure.

Parameters:

discount_percentage – The discount percentage (0 to 100).

category
created_at
description
classmethod get_fields() Dict[str, str][source][source]

Returns a dictionary of column names and their SQLAlchemy types for this model. Useful for introspection, e.g., in generic admin views. # No signals here, as this is a static introspection method.

id
image_url
name
price
quantity
sku
update_quantity(amount: int)[source][source]

Updates the product quantity by a specified amount. Raises ValueError if the resulting quantity would be negative. Emits ‘product_quantity_updated’ signal on success. Emits ‘product_quantity_update_failed’ signal on failure.

Parameters:

amount – The integer amount to add to the current quantity (can be positive or negative).

updated_at
validate_category(key, value)[source][source]

Placeholder for category validation. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run.

validate_image_url(key, value)[source][source]

Placeholder for image_url validation. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run.

validate_name(key: str, value: str | None) str[source][source]

Validate that the name is not empty. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run.

validate_price(key: str, value: Any) float[source][source]

Validate that the price is a non-negative float. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run. Specific validation failure signals could be added here if needed, but might be overly granular.

validate_quantity(key: str, value: Any) int[source][source]

Validate that the quantity is a non-negative integer. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run. Specific validation failure signals could be added here if needed.

validate_sku(key: str, value: str | None) str[source][source]

Validate that the SKU is not empty. SQLAlchemy @validates are called before session flush/commit. ‘model_pre_validate’ signal is emitted by BaseModel.validate() before these run.

lback.models.session module

class lback.models.session.Session(**kwargs)[source][source]

Bases: BaseModel

Represents a server-side session stored in the database.

This model manages user session data, including session ID, associated user, creation and expiration timestamps, and a binary field for storing arbitrary session data. It provides convenient properties to serialize and deserialize the session data to and from a Python dictionary.

__repr__()[source][source]

Provides a string representation of the Session object for debugging purposes.

created_at

The timestamp when the session was created.

data

A text field to store arbitrary session data as a JSON string. This field holds dynamic session-specific information (e.g., user login status, shopping cart contents, flash messages). Data is serialized to JSON string before storage and deserialized from JSON string upon retrieval.

property data_dict: Dict[str, Any]

Deserializes the binary ‘data’ field into a Python dictionary.

This property handles the conversion of the stored binary data back into a usable dictionary format, making it easy to access session variables. It uses pickle for deserialization.

Returns:

The session data as a dictionary, or an empty dictionary if no data is stored.

Return type:

Dict[str, Any]

expires_at

The timestamp when the session is scheduled to expire.

id

The unique identifier for the session, generated as a UUID.

updated_at

The timestamp of the last update to the session. Automatically updated on record modification.

user_id

The ID of the authenticated user associated with this session. Can be None for anonymous sessions.

lback.models.user module

class lback.models.user.Group(**kwargs)[source][source]

Bases: BaseModel

Represents a group or role that users can belong to. A group has a name and can be associated with multiple permissions.

created_at
description
id
name
permissions
updated_at
class lback.models.user.User(**kwargs)[source][source]

Bases: BaseModel

Represents a regular application user. Extends BaseModel with user-specific fields and validation. Now supports Many-to-Many relationship with Groups for flexible role management.

__repr__() str[source][source]

Provides a developer-friendly string representation of the User instance.

auth_token
check_password(plain_password: str) bool[source][source]

Checks the provided plain text password against the stored hashed password. Emits ‘user_password_checked’ signal after the check, ‘user_password_check_failed’ on error.

created_at
email
email_verification_token
email_verification_token_expiry
generate_email_verification_token(expiry_minutes: int = 60)[source][source]

Generates a new email verification token and sets its expiry.

classmethod get_fields() Dict[str, str][source][source]

Returns a dictionary of column names and their SQLAlchemy types for this model. Useful for introspection, e.g., in generic admin views.

groups
has_permission(permission_name: str) bool[source][source]

Checks if the user has a specific permission by checking their groups’ permissions. Uses a class-level cache to improve performance.

id
is_active
property is_admin: bool

Determines if the user is an admin based on their group membership. Assumes there’s a group named ‘admin’.

is_email_verified
property is_superuser: bool

Determines if the user is a superuser. This can be based on a specific group or a dedicated flag in the User model. For simplicity, we’ll assume ‘admin’ group implies superuser for now. In a real app, you might have a separate is_superuser column.

password
set_password(plain_password: str)[source][source]

Hashes the plain text password and sets it on the model. Emits ‘user_password_set’ signal on success, ‘user_password_set_failed’ on failure.

token_expiry
updated_at
property user_type: str

Returns the general type of the user (‘user’ or ‘admin’). The AuthMiddleware uses this general type to differentiate between regular users and admin users handled by separate managers. Specific roles (like ‘premium_user’, ‘editor’, ‘basic_user’) should be checked via has_permission or groups_names property.

username
validate_email(key: str, value: str | None) str[source][source]
validate_password(key: str, value: str | None) str[source][source]
validate_username(key: str, value: str | None) str[source][source]
verify_email(token: str) bool[source][source]

Verifies the provided email verification token and marks email as verified if valid.

class lback.models.user.UserPermission(**kwargs)[source][source]

Bases: BaseModel

Represents a specific permission that can be granted to groups.

created_at
description
id
name
updated_at