lback.admin package

This file serves as the initialization point for the ‘lback_framework/lback/admin’ package. It is designed to expose the core components necessary for building and managing the administrative interface within the Lback web framework. This package centralizes the definition and management of administrative functionalities, including views for data management, an admin registry, and URL patterns for the admin site.

Key Components Exposed by this Package:

  1. admin (from .admin): This likely refers to the main Admin class or instance that orchestrates the entire administrative site. It’s responsible for managing registered models, dispatching requests to appropriate admin views, and potentially handling global admin configurations. It acts as the central hub for the administrative interface.

  2. Admin Views (from .auth_views and .generic): A collection of pre-built views designed to handle common administrative operations on data models. These views abstract away boilerplate logic for managing users, and performing CRUD operations on generic models within the admin interface.

    • admin_user_add_view: A specific view for adding new administrative users.

      This view typically handles the form submission, validation, and creation of new admin user accounts.

    • admin_user_list_view: A specific view for listing existing administrative users.

      It displays a table or list of admin users, often with options for searching, filtering, and pagination.

    • generic_add_view: A generic view for adding new instances of any registered model.

      This view provides a standardized interface for creating new records dynamically.

    • generic_list_view: A generic view for listing instances of any registered model.

      It displays a table or list of records for a given model, offering general management capabilities.

    • generic_delete_view: A generic view for deleting instances of any registered model.

      It handles the logic for removing records from the database.

    • generic_change_view: A generic view for updating existing instances of any registered model.

      This view provides an interface for modifying existing records.

    • generic_detail_view: A generic view for displaying the detailed information of a single

      instance of any registered model.

  3. AdminRegistry (from .registry): A central registry where application models are registered to be managed by the administrative interface. This class keeps track of which models have an admin interface defined for them, and how they should be displayed and interacted with. It’s crucial for dynamically generating admin forms and lists.

  4. urlpatterns (from .urls): A list or collection of URL patterns specifically for the admin site. These patterns map incoming HTTP requests to the appropriate admin views, defining the routing for all administrative functionalities (e.g., /admin/users/, /admin/products/add/).

  5. Admin Page Views (from .views): Specific views related to the core administrative user experience, such as login, dashboard, and logout functionalities.

    • admin_login_page: The view responsible for rendering the administrative login form.

    • admin_dashboard_page: The main dashboard view displayed after a successful

      administrative login, providing an overview of the system.

    • admin_login_post: The view that handles the submission of the administrative

      login form, processing credentials and authenticating the user.

    • admin_logout_post: The view that handles administrative logout requests,

      terminating the user’s admin session.

Submodules

lback.admin.admin module

lback.admin.auth_views module

lback.admin.auth_views.admin_user_add_view(request: Request) Response[source][source]

View to add a new AdminUser object. Handles both GET (display form) and POST (process form).

lback.admin.auth_views.admin_user_list_view(request: Request) Response[source][source]

View to list AdminUser objects with precise access control for display.

lback.admin.generic module

lback.admin.generic.generic_add_view(request: Request, model: Type[BaseModel]) Response[source][source]

Handles the generic “add” view for creating new instances of a database model.

This view supports both displaying an empty form for new object creation (GET request) and processing form submissions to persist a new object to the database (POST request). It dynamically handles various SQLAlchemy column types and relationships (Many-to-One, One-to-One, Many-to-Many) based on the provided model’s schema.

It includes: - Dynamic permission checking using the @PermissionRequired decorator. - Handling of file uploads with configurable allowed types and max size. - Type conversion for different database column types (String, Integer, Boolean, DateTime, JSON). - Error handling for form validation and database integrity issues. - Redirection upon successful creation or re-rendering the form with errors.

Parameters:
  • request (Request) – The incoming request object, containing parsed body, files, database session, configuration, and router information.

  • model (Type[BaseModel]) – The SQLAlchemy BaseModel class for which a new instance is to be added.

Returns:

A Response object, either a redirect on success, or a rendered form (potentially with errors) on failure or for initial display.

Return type:

Response

lback.admin.generic.generic_change_view(request: Request, model: Type[BaseModel], object_id: Any) Response[source][source]

Handles the generic “change” view for editing existing instances of a database model.

This view supports both displaying a pre-filled form for editing (GET request) and processing form submissions to update an existing object in the database (POST request). It dynamically handles various SQLAlchemy column types and relationships (Many-to-One, One-to-One, Many-to-Many) based on the provided model’s schema.

It includes: - Dynamic permission checking using the @PermissionRequired decorator. - Retrieval of the existing object by object_id. - Handling of file uploads, including replacing old files and validating new ones. - Type conversion for different database column types (String, Integer, Boolean, DateTime, JSON). - Management of Many-to-Many relationships by clearing and re-adding associated objects. - Robust error handling for object not found, form validation, and database integrity issues. - Redirection upon successful update or re-rendering the form with errors.

Parameters:
  • request (Request) – The incoming request object, containing parsed body, files, database session, configuration, and router information.

  • model (Type[BaseModel]) – The SQLAlchemy BaseModel class whose instance is to be changed.

  • object_id (Any) – The primary key or unique identifier of the object to be changed.

Returns:

A Response object, either a redirect on success, or a rendered form (potentially with errors) on failure or for initial display.

Return type:

Response

lback.admin.generic.generic_delete_view(request: Request, model: Type[BaseModel], object_id: Any) Response[source][source]

Handles the generic “delete” view for removing instances of a database model.

This view is specifically designed to process POST requests for deletion to prevent accidental deletions via GET requests. It performs the following actions: - Permission Checking: Uses the @PermissionRequired decorator to ensure the user

has the necessary permission (delete_<model_name>).

  • Dependency Check: Verifies the presence of a database session and configuration.

  • HTTP Method Enforcement: Ensures the request method is POST.

  • Object Retrieval: Fetches the object to be deleted by its object_id.

  • AdminUser Specific Protections: Implements special logic to prevent:
    • Deletion of the primary superuser (ID 1).

    • Non-primary superusers from deleting other superusers.

    • Non-superusers from deleting any AdminUser.

  • Associated File Deletion: Iterates through model attributes to identify and delete any associated files (e.g., fields ending with ‘_file’ or ‘_path’) from the filesystem before deleting the database record.

  • Database Deletion: Deletes the object from the database and commits the transaction.

  • Redirection: Redirects to the model’s list view upon successful deletion.

  • Error Handling: Provides robust error handling for object not found, forbidden operations, and unexpected exceptions during the deletion process.

Parameters:
  • request (Request) – The incoming request object, containing the database session, configuration, and the current user.

  • model (Type[BaseModel]) – The SQLAlchemy BaseModel class whose instance is to be deleted.

  • object_id (Any) – The primary key or unique identifier of the object to be deleted.

Returns:

A Response object, typically a redirect on success, or an error response (404, 403, or 500) on failure.

Return type:

Response

lback.admin.generic.generic_detail_view(request: Request, model: Type[BaseModel], object_id: Any) Response[source][source]

Handles the generic “detail” view for displaying the attributes of a single instance of a database model.

This view retrieves a specific object by its ID and dynamically prepares its fields for display. It handles various SQLAlchemy column types and relationships, formatting them appropriately for presentation in a detail page.

It includes: - Dynamic permission checking using the @PermissionRequired decorator to ensure

the user is authorized to view the specific model’s details.

  • Retrieval of the existing object by object_id from the database.

  • Handling of “object not found” scenarios by returning a 404 response.

  • Exclusion of sensitive or internal fields (e.g., ‘id’, ‘password’) from display.

  • Special formatting for different data types:
    • SQLAlchemy Relationships (ManyToOne, OneToOne): Displays string representation.

    • SQLAlchemy Relationships (ManyToMany): Displays a list of string representations.

    • File/Path Fields (ending with _file or _path): Constructs a full URL for download/display based on UPLOAD_URL from request.config.

    • JSON Fields: Pretty-prints the JSON content.

    • Boolean Fields: Displays “Yes” or “No”.

    • DateTime Fields: Formats as “YYYY-MM-DD HH:MM:SS”.

    • Other standard column types are displayed as is.

  • Sorting of displayed fields alphabetically by name for consistent presentation.

  • Robust error handling for missing database session/configuration or other runtime exceptions, returning a 500 response.

  • Rendering of an HTML template (admin/generic_detail.html) with the object’s details.

Parameters:
  • request (Request) – The incoming request object, containing path parameters, database session, application configuration, etc.

  • model (Type[BaseModel]) – The SQLAlchemy BaseModel class whose instance details are to be viewed.

  • object_id (Any) – The primary key or unique identifier of the object to be displayed.

Returns:

A Response object, typically a rendered HTML page showing the object’s details, or an HTTP 404/500 error response if the object is not found or an internal error occurs.

Return type:

Response

lback.admin.generic.generic_list_view(request: Request, model: Type[BaseModel]) Response[source][source]

Handles the generic “list” view for displaying, searching, filtering, and paginating instances of a database model.

This view dynamically generates a list of objects based on the provided model’s schema and query parameters. It supports various SQLAlchemy column types and relationships for advanced filtering and sorting capabilities.

It includes: - Dynamic permission checking using the @PermissionRequired decorator, ensuring users

can only view models they are authorized to access.

  • Retrieval and pagination of model instances from the database.

  • Full-text search functionality across string-based columns.

  • Advanced filtering options:
    • Range filtering for date/datetime and numeric fields (e.g., created_at_min, price_max).

    • Null/Not Null checks for any field, including relationship foreign keys (e.g., author_id_isnull=true).

    • Exact match filtering for boolean, integer, float, and string fields.

    • Filtering based on Many-to-One relationships (e.g., selecting objects linked to a specific related entity).

    • Filtering based on Many-to-Many relationships (e.g., finding objects associated with a particular related entity).

    • Filtering for the existence/non-existence of One-to-One related objects.

  • Customizable sorting by any sortable model column, in ascending or descending order.

  • Dynamic determination of fields to display in the list, excluding sensitive or overly large fields by default.

  • Generation of metadata for filter controls to be used in the UI, including available choices for relationship-based filters.

  • Robust error handling for database session issues or unexpected exceptions during processing.

  • Rendering of an HTML template (admin/generic_list.html) with the prepared data.

Parameters:
  • request (Request) – The incoming request object, containing query parameters, path parameters, database session, and other request-specific data.

  • model (Type[BaseModel]) – The SQLAlchemy BaseModel class whose instances are to be listed.

Returns:

A Response object, typically a rendered HTML page displaying the list of objects, or an error response if issues occur (e.g., database session missing).

Return type:

Response

lback.admin.registry module

class lback.admin.registry.AdminRegistry[source][source]

Bases: object

Registry for the standard administration application. Keeps track of models registered for administration. Integrates SignalDispatcher to emit events related to registry initialization and model registration.

__init__()[source][source]

Initializes the AdminRegistry. Emits ‘admin_registry_initialized’ signal.

get_model(model_name: str) Type[Any] | None[source][source]

Retrieves a registered model class by its name (case-insensitive). Converts the input name to lowercase before lookup.

Parameters:

model_name – The name of the model class as a string.

Returns:

The model class if registered, otherwise None.

get_registered_models() Dict[str, Type[Any]][source][source]

Retrieves a dictionary of all registered models, using the original model names as keys. This is useful for displaying in the UI with correct capitalization.

register(model_class: Type[Any])[source][source]

Registers a model class with the admin registry. Stores the model using its lowercase name as the dictionary key. Emits ‘admin_model_registered’ signal on success. Emits ‘admin_model_registration_failed’ signal on failure (invalid model, already registered).

Parameters:

model_class – The SQLAlchemy model class to register.

Raises:

ValueError – If the registered model is not a valid model class, or if the model is already registered (case-insensitive).

lback.admin.urls module

lback.admin.views module

lback.admin.views.admin_dashboard_page(request: Request) Response[source][source]

Displays the admin dashboard page. Requires authentication and ‘view_dashboard’ permission. Simplified using render helper and request properties. Updated to use new error shortcuts.

lback.admin.views.admin_login_page(request: Request) Response[source][source]

Renders the admin login page. Simplified using render helper and request properties. Updated to use new error shortcuts.

lback.admin.views.admin_login_post(request: Request) Response[source][source]

Handles the submission of the admin login form. Authenticates the admin user and redirects to the dashboard on success. Simplified using redirect helper and request properties. Updated to use new error shortcuts and leverage request.POST/request.DATA.

lback.admin.views.admin_logout_post(request: Request) Response[source][source]

Handles admin logout. Requires authentication. Simplified using redirect helper and request properties. Updated to use new error shortcuts.