Base View
Smarter API command-line interface Base class API view
- exception smarter.apps.api.v1.cli.views.base.APIV1CLIViewError(message='')[source]
Bases:
SmarterExceptionBase class for all APIV1CLIView errors.
- property get_formatted_err_message
- class smarter.apps.api.v1.cli.views.base.CliBaseApiView(*args, **kwargs)[source]
Bases:
APIView,SmarterRequestMixinBase class for all Smarter API v1 command-line interface (CLI) views. This class provides common functionality for all /api/v1/cli endpoints, including:
Authentication using either Knox TokenAuthentication or Django SessionAuthentication.
Initialization of the
SAMLoaderandAbstractBrokerinstances.Resolution of the manifest kind and broker for the YAML manifest document.
Setting the user profile for the request.
The base class is responsible for as much request “housekeeping” as possible, so that child views can focus on business logic. The following attributes are set up and managed:
Notes
The base class is designed to minimize boilerplate in child views.
Manifest parsing and broker instantiation are implemented lazily.
Authentication is enforced by default, but can be bypassed for internal API requests.
Examples
- Example URL with a manifest name:
/api/v1/cli/describe/chatbot/<str:name>/- Example command extraction:
If the URL path is
/api/v1/cli/apply/, then the command will beSmarterJournalCliCommands.APPLY.
- property BrokerClass: Type[AbstractBroker]
Get the broker class for the manifest kind. This is used to instantiate a broker for the manifest kind.
- Returns:
Broker class for the manifest kind
- Return type:
Type[AbstractBroker]
- __init__(*args, **kwargs)[source]
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
- authentication_classes = (<class 'smarter.lib.drf.token_authentication.SmarterTokenAuthentication'>, <class 'rest_framework.authentication.SessionAuthentication'>)
- property broker: AbstractBroker | None
Use a loader to try to instantiate a broker. A broker is a class that implements the broker service pattern. It provides a service interface that ‘brokers’ the http request for the underlying object that provides the object-specific service (create, update, get, delete, etc).
- Returns:
Broker instance for the manifest kind
- Return type:
Optional[AbstractBroker]
- property command: SmarterJournalCliCommands
Translate the request route into a SmarterJournalCliCommands enum instance. For example, if the route is ‘/api/v1/cli/apply/’, then the corresponding command will be SmarterJournalCliCommands.APPLY.
- Returns:
SmarterJournalCliCommands enum instance
- Return type:
- dispatch(request, *args, **kwargs)[source]
Dispatch the request to the appropriate handler method.
This method is a core part of the Django REST Framework (DRF) view lifecycle. It is called automatically by DRF when an HTTP request is received and is responsible for routing the request to the correct handler method (such as
get(),post(),put(), etc.) based on the HTTP method of the request.In DRF, the
dispatch()method performs several critical functions:It determines which handler method should process the request.
It manages the execution of middleware and mixins.
It handles exceptions that may be raised during request processing.
It returns a DRF
Responseobject to the client.
In this base class implementation, the primary objective is to provide robust exception handling for all CLI API views. The method attempts to map known exceptions to appropriate HTTP status codes and, where possible, adds additional context to error messages. This ensures that clients receive meaningful and actionable error responses, even if an unexpected error occurs.
Ideally, child views should handle their own exceptions and return a
SmarterJournaledJsonErrorResponseor similar structured response. However, this base implementation acts as a safety net, catching any unhandled exceptions and returning a generic error message along with a bug report URL for further trouble shooting.Signals are emitted to indicate the completion or failure of API requests, which can be used for logging, auditing, or triggering other side effects.
- Parameters:
request (Request) – The HTTP request object provided by DRF, containing all request data, headers, and user context.
*args – Additional positional arguments passed to the view.
**kwargs – Additional keyword arguments passed to the view, often including URL parameters.
- Returns:
A DRF
Responseobject representing the result of the request, or an error response if an exception was raised.- Return type:
Response
Notes
This method is a critical integration point with DRF’s request/response lifecycle.
Exception mapping is comprehensive, covering both application-specific and DRF exceptions.
Unhandled exceptions are logged and reported with a generic message and bug report instructions.
Signals are used for observability and integration with other parts of the application.
See also
https//www.django-rest-framework.org/api-guide/views/#view-methods DRF documentation on view methods and the dispatch process.
- property formatted_class_name: str
Returns the class name in a formatted string along with the name of this mixin.
- Returns:
Formatted class name string
- Return type:
- initial(request, *args, **kwargs)[source]
Perform view initialization after setup and before dispatch.
This method is called by Django REST Framework (DRF) after the setup() method but before the dispatch() method. It is the earliest point in the DRF view lifecycle where the request object is fully available and can be used to complete any additional initialization required by the view.
In DRF, the initial() method is responsible for performing tasks such as: - Completing any remaining setup that depends on the request object. - Enforcing authentication and permission checks. - Raising appropriate exceptions if the request is not valid or not authenticated.
In this implementation, initial() ensures that the SmarterRequestMixin and any related mixins are fully initialized with the request object. It also performs authentication checks, sets up user and account context, and prepares manifest data or prompt text for downstream processing. If authentication fails, it raises a custom error with detailed logging.
- Parameters:
request (Request) – The HTTP request object provided by DRF. This object contains all request data, headers, user information, and other context needed for processing the API call.
*args – Additional positional arguments passed to the view.
**kwargs – Additional keyword arguments passed to the view, often including URL parameters extracted by the router.
- Raises:
SmarterAPIV1CLIViewErrorNotAuthenticated – If the request is not authenticated and is not an internal API request, this exception is raised to indicate authentication failure.
SmarterConfigurationError – If the request object is not properly set up in the view, this error is raised to indicate a misconfiguration.
Notes
This method is a critical part of the DRF request lifecycle, ensuring that all necessary context and validation is in place before the main handler methods (get, post, etc.) are called.
Manifest parsing and broker instantiation are deferred (lazy) and only performed when needed by child views.
The method also logs key events and warnings for observability.
See also
https//www.django-rest-framework.org/api-guide/views/#view-initialization DRF documentation on the view initialization process.
- property is_cli_base_api_view_ready: bool
Check if the CliBaseApiView is ready.
- Returns:
True if the view is ready, False otherwise
- Return type:
- property is_cli_base_api_view_ready_state: str
Get a string representation of the readiness state of the CliBaseApiView.
- Returns:
Readiness state as a string
- Return type:
- property loader: SAMLoader | None
Get the SAMLoader instance. a SAMLoader instance is used to load raw manifest text into a Pydantic model. It performs cursory validations such as validating the file format, and identifying required dict key values such as the api version, the manifest kind and its name.
The loader is instantiated lazily, so it will only be created when it is first accessed.
- Returns:
SAMLoader instance or None
- Return type:
Optional[SAMLoader]
- property logger_prefix: str
Get the logger prefix for this class.
- Returns:
Logger prefix string
- Return type:
- property manifest_data: dict | None
The raw manifest data from the request body. The manifest data is a json object which needs to be rendered into a Pydantic model. The Pydantic model is then used to instantiate a broker for the manifest kind.
- Returns:
Raw manifest data as a json object
- Return type:
Optional[dict]
- property manifest_kind: str | None
The kind of the manifest. The manifest kind is used to identify the type of resource that the manifest is describing. The kind is used to identify the broker that will be used to broker the http request for the resource.
- Returns:
The kind of the manifest
- Return type:
Optional[str]
- property manifest_name: str | None
The name of the manifest. The manifest name is used to identify the resource within a Kind. For example, the manifest name for a ChatBot resource is the name of the chatbot. The manifest name is used to identify the resource within a Kind. The name can be passed from inside the raw manifest data, or it can be passed as part of a url path.
Example url path with a name: /api/v1/cli/describe/chatbot/<str:name>/
- Returns:
The name of the manifest
- Return type:
Optional[str]
- permission_classes = (<class 'smarter.lib.drf.views.helpers.SmarterAuthenticatedPermissionClass'>,)
- property ready: bool
Check if the CliBaseApiView and SmarterRequestMixin are ready.
- Returns:
True if both the view and mixin are ready, False otherwise
- Return type:
- setup(request, *args, **kwargs)[source]
Setup the view. This is called by Django before dispatch() and is used to set up the view for the request. the request is not yet authenticated.
- Parameters:
request (Request) – The HTTP request object
- exception smarter.apps.api.v1.cli.views.base.SmarterAPIV1CLIViewErrorNotAuthenticated(message='')[source]
Bases:
APIV1CLIViewErrorError class for not authenticated errors.
- property get_formatted_err_message
- smarter.apps.api.v1.cli.views.base.should_log(level)[source]
Check if logging should be done based on the waffle switch.