SmarterAdminWebView

class smarter.lib.django.views.SmarterAdminWebView(**kwargs)[source]

Bases: SmarterAuthenticatedNeverCachedWebView

An admin-only optimized web view that is never cached.

Its dispatch method checks the user explicitly, rather than with a decorator such as @staff_member_required, so that a user who may not access the view is redirected rather than shown an error:

  • An anonymous user is redirected to /login/.

  • An authenticated user who is not marked as staff (is_staff) is redirected to the admin login page.

Both redirects expire the cache. In addition, this view inherits from SmarterAuthenticatedNeverCachedWebView, which is never cached. This means:

  • Only authenticated staff members can access the view.

  • Every response is generated fresh for each request, with no caching at any layer.

This combination makes the view ideal for admin pages that display sensitive or frequently changing data, ensuring both strict access control and cache prevention.

__init__(**kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

accepted_session_key(session_key, source)

Return a session key that the request carries, if it is well formed.

The key comes from the client: the url, the request body, a cookie or a get() parameter. A malformed key, e.g. a cookie of the same name that another application set on a parent domain, is ignored rather than raised, so that the request starts a new session instead of failing.

Parameters:
  • session_key (str | None) – The raw value that the request carries, or None.

  • source (str) – Where the value came from, for the log, e.g. "cookie".

Return type:

str | None

Returns:

The session key, stripped of whitespace and of a trailing slash, or None if the value is missing or malformed.

property account: Account | None

Returns the account for the current user.

Handle lazy instantiation from user or user_profile.

Returns:

The account for the current user.

Return type:

Account or None

property account_number: str | None

A helper function to get the account number from the account.

Returns:

The account number for the current account.

Return type:

str or None

property administers_account: bool

manages every resource in it.

See user_administers_account().

Returns:

True if the current user may manage every resource of the current account.

Type:

Whether the current user administers the current account

property am_ready: bool

Returns True if the AccountMixin is am_ready to be used.

This is a convenience property that checks if the account and user are initialized. AccountMixin is considered am_ready if: - self.user is an instance of User - self.user_profile is an instance of UserProfile - self.account is an instance of Account

Returns:

True if the AccountMixin is am_ready to be used.

Return type:

bool

property amnesty_urls: list[str]

Returns a list of URLs that are exempt from certain checks.

Returns:

List of URL path strings that are exempt.

Return type:

list[str]

property api_subdomain: str | None

Extract the API subdomain, the first label of the host, from an llmclient URL.

For example, this url returns 'hr':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The API subdomain, or None if the url is not an llmclient url.

property api_token: bytes | None

Get the API token from the request’s Authorization header.

The header’s value is Token <key> or Bearer <key>.

Example:

request_mixin = SmarterRequestMixin(request)
token = request_mixin.api_token
Returns:

The API token as bytes, or None if the header is missing or has neither prefix.

classmethod as_view(**initkwargs)

Main entry point for a request-response process.

property auth_header: str | None

Get the Authorization header from the request.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.auth_header)

This property checks for the “Authorization” header in the request headers.

Returns:

The value of the “Authorization” header as a string, or None if not present.

authenticate(api_token=None, request=None)

Authenticate the request using the API token in its Authorization header.

The request is passed along, so that a token that was already authenticated for it, e.g. by the token middleware or by AccountMixin’s own initialization, is not authenticated again.

Parameters:
  • api_token (bytes | None) – The API token to authenticate with. Defaults to the request’s.

  • request (HttpRequest | None) – The request that carries the token. Defaults to this mixin’s request.

Return type:

bool

Returns:

True if there is an API token and the parent’s authenticate() accepts it, otherwise False.

bool_environment_variable(var_name, default=False)

Retrieves a boolean value from an environment variable.

This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.

Parameters:
  • var_name (str) – The name of the environment variable to check.

  • default (bool) – The default boolean value to return if the environment variable is not set or invalid.

Returns:

The boolean value of the environment variable or the default.

Return type:

bool

property cache_key: str | None

Returns a cache key for the request.

This is used to cache the prompt request thread. The key is the sha256 hash of:

  • the class name,

  • the request’s user, or "Anonymous",

  • and the client UID (uid), or "unknown_uid".

Currently used by the ApiV1CliPromptConfigApiView and ApiV1CliPromptApiView as a means of sharing the session_key.

Example:

request_mixin = SmarterRequestMixin(request)
key = request_mixin.cache_key
print(key)  # e.g., 'a1b2c3d4e5f6...'
Returns:

A unique cache key string, or None if there is no request.

clean_http_response(request, template_path, *args, context=None, **kwargs)

Render a template and return an HttpResponse with comments removed.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • template_path (str) – The path to the template to render.

  • args – Ignored.

  • context (dict[str, Any] | None) – The context to use for rendering the template.

  • kwargs – Ignored.

Return type:

HttpResponse

Returns:

An HttpResponse with the cleaned HTML content, or the error response of render_clean_html() if the template could not be rendered.

clear_cached_properties()

Clear the request, its parsed values, and all cached properties in this mixin.

Return type:

None

Returns:

None.

context: dict[str, Any] = {}
property data: dict[str, Any] | list[Any] | str | None

Get the request body data as a dictionary, list or str.

Used for setting the session_key.

Example:

request_mixin = SmarterRequestMixin(request)
data = request_mixin.data
print(data)  # e.g., {'session_key': 'abc123', ...}
Returns:

The request body parsed as json or yaml, an empty dict if the body is empty or can’t be parsed, or None if there is no request or the request is not qualified.

data_to_dict(data)

Converts data to a dictionary, handling different types of input.

This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.

Parameters:

data (dict[str, Any] | str) – The data to convert, either a dict or a JSON/YAML string.

Returns:

The data as a dictionary.

Return type:

dict[str, Any]

Raises:

SmarterValueError – If the data cannot be converted to a dictionary.

deserves_amnesty(slug)

Determines if a given URL deserves amnesty based on the amnesty URLs list.

This excuses certain endpoints (like health checks) from select middleware checks.

Parameters:

slug (str) – The URL path to check.

Returns:

True if the URL deserves amnesty, False otherwise.

Return type:

bool

dict_is_contained_in(dict1, dict2)

Checks if one dictionary is contained within another.

This method determines if all key-value pairs in dict1 are present in dict2.

Parameters:
  • dict1 (dict[str, Any]) – The dictionary to check for containment.

  • dict2 (dict[str, Any]) – The dictionary to check against for containment.

Returns:

True if dict1 is contained in dict2, False otherwise.

Return type:

bool

dict_is_subset(small, big)

Checks if one dictionary is a subset of another.

This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.

Parameters:
  • small (dict[str, Any]) – The dictionary to check as a subset.

  • big (dict[str, Any]) – The dictionary to check against as a superset.

Returns:

True if the small dictionary is a subset of the big dictionary, False otherwise.

Return type:

bool

dispatch(request, *args, **kwargs)[source]

Redirect anonymous users to the login page and non-staff users to the admin login, then dispatch.

The response varies on the Cookie header.

Parameters:
  • request (HttpRequest) – The request.

  • args – Passed to the view.

  • kwargs – Passed to the view.

Return type:

HttpResponseBase

Returns:

The view’s response, or a redirect that expires the cache.

property domain: str | None

Extract the domain, the host and port, from the URL.

For example, this url returns 'hr.3141-5926-5359.alpha.api.example.com':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The domain, or None if there is no request or url.

eval_llmclient_url()

Resolve the account and user of a request to a deployed LLMClient’s own host.

For a named url, e.g. http://example.3141-5926-5359.api.localhost:9357/, the account is loaded from the url’s account number when account is not already set, and then, when user is not set, the user becomes that account’s admin user.

Other llmclient urls, the smarter api and cli api urls, need no follow up here. A request that is not an llmclient request is left as it is.

Return type:

None

Returns:

None. Sets account and user as a side effect.

find_session_key()

Return the unique prompt session key value for this request.

The session_key is managed by the /config/ endpoint for the llmclient. The React app calls this endpoint at app initialization to get a JSON dict that includes, among other info, this session_key, which uniquely identifies the device and the individual llmclient session for the device.

For subsequent prompt requests, the session_key is intended to be sent in the body of the request as a key-value pair, e.g. {"session_key": "1234567890"}.

The session key is looked for in these places, in this order, and the first well formed one (see accepted_session_key()) is returned:

  • The URL, e.g. http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a

  • The request body: {'session_key': '1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a'}

  • A cookie

  • The request’s GET parameters

Return type:

str | None

Returns:

The session key as a string, or None if not found.

property formatted_class_name: str

Return the class name in a formatted string along with the name of this view.

Returns:

The dotted name of this view class and its instance id, formatted for logs.

formatted_json(json_obj)

Formats a JSON object as a pretty-printed string with ANSI color codes for logging.

Parameters:

json_obj (dict[str, Any] | list) – The JSON object (dict or list) to format.

Returns:

A string representation of the JSON object with ANSI color codes.

Return type:

str

property formatted_state_not_ready: str

Returns the not-ready state formatted for logging.

Returns:

The formatted not-ready state as a string.

Return type:

str

property formatted_state_ready: str

Returns the readiness state formatted for logging.

Returns:

The formatted readiness state as a string.

Return type:

str

formatted_text(text, color_code='\x1b[1;31m')

Formats text with ANSI color codes for logging.

Parameters:
  • text (str) – The text to format.

  • color_code (str) – The ANSI color code to apply.

Returns:

The formatted text with ANSI color codes.

Return type:

str

formatted_text_blue(text)

Formats text in bold dark blue for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bold dark blue.

Return type:

str

formatted_text_green(text)

Formats text in bright green for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bright green.

Return type:

str

formatted_text_red(text)

Formats text in dark red for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in dark red.

Return type:

str

generate_fernet_encryption_key()

Generates a Fernet encryption key.

This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.

Returns:

A new Fernet encryption key.

Return type:

str

generate_session_key()

Generate a new, random session_key.

Return type:

str

Returns:

A random 64 character session key.

generate_smarter_request_id()

Generate a unique identifier for the request.

Return type:

str

Returns:

A random uuid4, as 32 hexadecimal characters.

get(request, *args, **kwargs)

Handle GET requests and return a cleaned HttpResponse.

A view without a template, e.g. a JSON api that only answers POST, has nothing to render, so a GET receives 405 Method Not Allowed instead of a 500 (issue #963).

Parameters:
Return type:

HttpResponse

Returns:

An HttpResponse with the cleaned HTML content, or a 405 response when the view has no template.

Retrieve the value of a cookie from the request object.

Parameters:

cookie_name (str) – Name of the cookie to retrieve.

Return type:

str | None

Returns:

Value of the cookie, or None if there is no request or the cookie does not exist.

get_not_allowed(request, *args, **kwargs)

Answer a GET to a view that has no template with 405 Method Not Allowed.

Django’s own http_method_not_allowed() never runs for these views, because this class defines get(). Its Allow header would list GET and HEAD, so they are removed.

Parameters:
Return type:

HttpResponse

Returns:

A 405 response whose Allow header lists the methods that the view handles.

get_readonly_csv_file(file_path)

Reads a CSV file and returns its contents as a list of dictionaries, one per row.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the CSV file to read.

Returns:

The rows of the CSV file, one dictionary per row, keyed by the column headers.

Return type:

list[dict]

get_readonly_yaml_file(file_path)

Reads a YAML file and returns its contents as a dictionary.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the YAML file to read.

Returns:

The contents of the YAML file, parsed into a dictionary.

Return type:

dict

property health_check_urls: list[str]

Returns a list of URL paths that are considered health check endpoints.

Returns:

List of health check URL path strings.

Return type:

list[str]

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
http_method_not_allowed(request, *args, **kwargs)
init(*args, **kwargs)

An optional method that can be called after initialization to perform any additional setup.

This is separate from __init__ to allow for more flexible initialization patterns.

Parameters:
  • args – Positional arguments passed to the init method.

  • kwargs – Keyword arguments passed to the init method.

Return type:

None

Returns:

None

invalidate_cached_properties()

Invalidates all cached properties on the instance to force re-evaluation.

This method removes all attributes cached by @cached_property decorators from the instance’s __dict__. It is useful for testing or when the request object changes and you need to ensure that all dependent properties are recalculated.

Example:

from smarter.lib.django.request import SmarterRequestMixin

class Foo(SmarterRequestMixin):
    pass

foo = Foo(request)
foo.invalidate_cached_properties()
property ip_address: str | None

Get the client’s IP address from the request object.

This property attempts to extract the IP address from the request’s META dictionary, using the REMOTE_ADDR key.

Example:

request_mixin = SmarterRequestMixin(request)
ip = request_mixin.ip_address
print(ip)  # e.g., '192.168.1.100'
Returns:

The client’s IP address, the placeholder "ip_address" if REMOTE_ADDR is missing or empty, or None if the request has no META dictionary.

property is_authenticated: bool

Return True if the request’s user is authenticated.

Returns:

The request user’s is_authenticated, or False if there is no request or user, or checking it raises.

property is_config: bool

Return True if the URL resolves to a config endpoint.

Examples:

http://testserver/api/v1/cli/prompt/config/testc7098865f39202d5/
http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a
http://localhost:9357/api/v1/workbench/<int:llmclient_id>/prompt/config/
http://example.api.localhost:9357/config
Returns:

True if the URL is an llmclient url whose path includes config, otherwise False.

property is_dashboard: bool

Return True if the URL resolves to a dashboard endpoint.

Returns:

True if the URL’s path ends with /dashboard/, otherwise False.

property is_default_domain: bool

Return True if the URL is on the default api domain for the environment, e.g. api.alpha.platform.smarter.sh.

Returns:

True if the URL contains the environment’s api domain, otherwise False.

property is_environment_root_domain: bool

Return True if the URL resolves to the environment root domain.

Returns:

True if the URL’s host is the environment’s platform domain and its path is /, otherwise False.

is_internal_api_request(request)

Check if the request is an internal API request.

This method checks for a custom attribute on the request object that indicates whether the request is an internal API request. This can be used to bypass certain authentication or permission checks for internal requests.

Parameters:

request (HttpRequest) – The Django request object.

Return type:

bool

Returns:

True if it’s an internal API request, False otherwise.

property is_llmclient: bool

Return True if the URL resolves to an llmclient endpoint.

Conditions are checked in a lazy sequence to avoid unnecessary processing. The order matters: is_llmclient_named_url loads the url’s account as a side effect.

Examples:

http://localhost:9357/api/v1/prompt/1/prompt/
http://localhost:9357/api/v1/cli/prompt/example/
http://example.3141-5926-5359.api.localhost:9357/
http://localhost:9357/api/v1/llm-clients/1556/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/config/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/manifest/
Returns:

True if the request is qualified and its URL is a named, sandbox, smarter api or cli api llmclient url, otherwise False.

property is_llmclient_cli_api_url: bool

Return True if the URL is of the form http://localhost:9357/api/v1/cli/prompt/example/.

The expected path parts are:

['api', 'v1', 'cli', 'prompt', 'example']
Returns:

True if the URL matches the CLI llmclient API pattern, otherwise False.

property is_llmclient_named_url: bool

Return True if the url is a deployed LLMClient’s own host.

These are the forms of the url:

https://example-username.3141-5926-5359.api.example.com/
http://example-username.3141-5926-5359.api.localhost:9357/
http://example-username.3141-5926-5359.api.localhost:9357/config/
http://example-username.3141-5926-5359.api.localhost:9357/prompt/
http://example-username.3141-5926-5359.api.localhost:9357/jsi18n/

As a side effect, when the url has an account number and account is not set, the account is loaded from the account number.

Returns:

True if the URL matches the named llmclient pattern, otherwise False.

property is_llmclient_sandbox_url: bool

Return True if the URL is an llmclient sandbox endpoint.

Web console urls:

http://localhost:9357/workbench/llm-clients/<str:hashed_id>/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/config/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/manifest/

Api urls:

http://localhost:9357/api/v1/prompt/1/prompt/
Returns:

True if the URL matches an llmclient sandbox endpoint, otherwise False.

property is_llmclient_smarter_api_url: bool

Return True if the URL is a smarter api llmclient endpoint.

These are the forms of the url:

http://localhost:9357/api/v1/llm-clients/32/config/

http://localhost:9357/api/v1/workbench/1/prompt/
path_parts: ['api', 'v1', 'workbench', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/1556/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/rMTAwMDAwNwx/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<str:hashed_id>', 'prompt']
Returns:

True if the URL matches a smarter API llmclient endpoint, otherwise False.

property is_smarter_api: bool

Return True if the URL is of the form http://localhost:9357/api/v1/.

Examples:

path_parts: ['api', 'v1', 'llm-clients', '1', 'prompt']
http://api.localhost:9357/
Returns:

True if api is a segment of the URL’s path or a label of its host, otherwise False.

property is_workbench: bool

Return True if the URL resolves to a workbench endpoint.

Returns:

True if the URL’s path ends with /workbench/, otherwise False.

log_ready_status()

Log the ready status of the view at DEBUG, building the message only when it will be logged.

Return type:

None

Returns:

None.

mask_string(string='', mask_char='*', mask_length=4, string_length=8)

Masks a string for secure logging.

This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.

Parameters:
  • string (str | None) – The string to be masked.

  • mask_char (str) – The character used for masking.

  • mask_length (int) – The number of characters to mask.

  • string_length (int) – The length of the string to consider for masking.

Returns:

The masked string.

Return type:

str

minify_html(html)

Minify an html string, by removing the whitespace between tags.

It is one regular expression, not a parse: HTMLMinifyMiddleware parses every html response anyway.

Parameters:

html (str) – The HTML string to minify.

Return type:

str

Returns:

The minified HTML string.

options(request, *args, **kwargs)

Handle responding to requests for the OPTIONS HTTP verb.

property params: QueryDict

The query string parameters from the Django request object.

This extracts the query string parameters from the request object and converts them to a dictionary. Used in child views to pass optional command-line parameters to the broker.

Example:

request_mixin = SmarterRequestMixin(request)
params = request_mixin.params
print(params)  # e.g., {'session_key': 'abc123', 'uid': 'xyz'}
Returns:

QueryDict containing the query string parameters.

property parsed_url: ParseResult | None

Expose the private ParseResult URL object as a public property.

Example:

request_mixin = SmarterRequestMixin(request)
parsed = request_mixin.parsed_url
print(parsed.netloc)  # e.g., 'example.com'
Returns:

The parsed URL, or None if there is no url.

property path: str | None

Extract the path from the URL.

For example, this url returns '/llm-client/':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The path, / for an empty path, or None if there is no request or url.

property qualified_request: bool

A cursory screening of the WSGI request object to look for any disqualifying conditions that confirm this is not a request that we are interested in.

The request is considered “qualified” if all of the following are true:

  • The request object (self._smarter_request) is present.

  • The URL path is present and non-empty.

  • The request does not originate from an internal AWS Kubernetes subnet (netloc starts with 192.168).

  • The path is not in the list of amnesty_urls.

  • The path does not start with /admin/.

  • The path does not start with /docs/.

  • The path does not end with a static file extension (see STATIC_FILE_EXTENSIONS).

Example:

# True case: a valid llmclient request
request_mixin = SmarterRequestMixin(request)
if request_mixin.qualified_request:
    print("This is a qualified llmclient request.")

# False case: a static asset or admin/docs request
static_request = SmarterRequestMixin(static_asset_request)
if not static_request.qualified_request:
    print("This request is not of interest.")
Returns:

True if the request passes all checks and is of interest, otherwise False.

property ready: bool

Return True if the view is ready to handle requests, False otherwise.

This can be used to check if the necessary context or data is available before processing a request.

Returns:

True if the view is ready.

property ready_state: str

Returns a string representation of the am_ready state.

recursive_sort_dict(data)

Recursively sorts a dictionary by its keys.

This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with all keys sorted.

Return type:

dict[str, Any]

remove_comments(html)

Remove HTML comments from an html string.

Parameters:

html (str) – The HTML string from which to remove comments.

Return type:

str

Returns:

The HTML string without comments.

render_clean_html(request, template_path, context=None)

Render a template as a string, with comments removed and minified.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • template_path (str) – The path to the template to render.

  • context (dict[str, Any] | None) – The context to use for rendering the template, or the view’s context if None or empty.

Return type:

str | HttpResponse

Returns:

The rendered, cleaned HTML string, or a 500 response if the template could not be rendered.

property required_cache_key: str

Return cache_key, for code that reads or writes the cache with it.

cache_key is None only without a request, which a view always has. Rather than read or write the cache under the key None, which every such caller would share, this raises.

Returns:

The cache key.

Raises:

SmarterValueError – If there is no request, so no cache key.

rfc1034_compliant_str(name)

Converts a string to an RFC 1034 compliant format.

This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.

Parameters:

name (str) – The string to convert to RFC 1034 compliant format.

Returns:

The converted string in RFC 1034 compliant format.

Return type:

str

rfc1034_compliant_to_snake(name)

Converts an RFC 1034 compliant string to snake_case.

This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.

Parameters:

name (str) – The RFC 1034 compliant string to convert.

Returns:

The converted string in snake_case.

Return type:

str

property root_domain: str | None

Extract the root domain from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.root_domain)
# For 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/' → 'example.com'
# For 'http://localhost:9357/' → 'localhost'
Returns:

The root domain, or None if not found.

property session_key: str

Getter for the session_key property.

The session_key is a unique identifier for a prompt session. It is used to identify the prompt session across multiple requests. If the session_key is not already set, it attempts to find it in the request (see find_session_key()). Barring that, it generates a new one.

Example:

request_mixin = SmarterRequestMixin(request)
session_key = request_mixin.session_key
print(session_key)  # e.g., '38486326c21ef4bcb7e7bc305bdb062f16ee97ed8d2462dedb4565c860cd8ecc'
Returns:

The session key as a string.

set_is_internal_api_request(request, value=True)

Set the internal API request attribute on the request object.

This method allows you to mark a request as an internal API request by setting a custom attribute on the request object. This can be used in middleware or views to indicate that the request should be treated as internal.

Parameters:
  • request (HttpRequest) – The Django request object, or a DRF request, whose wrapped Django request is flagged too.

  • value (bool) – The value to set for the internal API request attribute (default is True).

Return type:

HttpRequest

Returns:

The modified request object.

Raises:

SmarterValueError – If request is not a Django HttpRequest or a DRF Request.

setup(request, *args, **kwargs)

Set up the view with the request and any additional arguments.

This method initializes the SmarterRequestMixin with the request, and marks the request as not an internal api request.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

None

smarter_build_absolute_uri(request)

Attempts to get the absolute URI from a request object.

This utility function tries to retrieve the request URL from any valid child class of django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implement build_absolute_uri().

Parameters:

request (HttpRequest) – The request object.

Returns:

The absolute request URL.

Return type:

str | None

Raises:

SmarterValueError – If the URI cannot be built from the request.

property smarter_capabilities: str | None

Get the smarter capabilities from the request.

This property checks for the “X-Smarter-Capabilities” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
capabilities = request_mixin.smarter_capabilities
Returns:

The value of the “X-Smarter-Capabilities” header as a string, or None if not present.

property smarter_client: str | None

Get the smarter client name from the request.

This property checks for the “X-Smarter-Client” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_name = request_mixin.smarter_client
Returns:

The value of the “X-Smarter-Client” header as a string, or None if not present.

property smarter_client_type: str | None

Get the smarter client type from the request.

This property checks for the “X-Smarter-ClientType” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_type = request_mixin.smarter_client_type
Returns:

The value of the “X-Smarter-ClientType” header as a string, or None if not present.

property smarter_client_version: str | None

Get the smarter client version from the request.

This property checks for the “X-Smarter-ClientVersion” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_version = request_mixin.smarter_client_version
Returns:

The value of the “X-Smarter-ClientVersion” header as a string, or None if not present.

property smarter_request: Request | HttpRequest | ASGIRequest | MagicMock | None

Returns the current request object.

This property is named to avoid potential name collisions in child classes. This property is preferred over standard Django request types in that it more elegantly resolves idiosyncratic usage like Unit tests, Sphinx docs, and other non-standard request objects.

Example:

request_mixin = SmarterRequestMixin(request)
req = request_mixin.smarter_request
Returns:

The current request object.

property smarter_request_id: str | None

Get the smarter request ID from the request.

This property checks for the “X-Smarter-RequestId” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
request_id = request_mixin.smarter_request_id
Returns:

The value of the “X-Smarter-RequestId” header as a string, or None if not present.

property smarter_request_llmclient_id: int | None

Extract the llmclient id from the URL.

For example, for this url the property decodes the hashed id rMTAwMDAyNwx into the llmclient’s id:

http://localhost:9357/workbench/llm-clients/rMTAwMDAyNwx/prompt/
Returns:

The llmclient id as an integer, or None if not found. A named url and a sandbox url without a hashed id return None.

property smarter_request_llmclient_name: str | None

Extract the llmclient name from the URL.

For example, this url returns "example":

http://example.3141-5926-5359.api.localhost:9357/config
Returns:

The llmclient name as a string, or None if not found.

smarter_request_setup(*args, request=None, user=None, **kwargs)

Initialize the SmarterRequestMixin with the request and user.

A view calls it from its own setup(), after Django’s View.setup(). It isn’t named setup(), because Django’s takes the request positionally, and a view inherits both. It initializes the request and user attributes of the mixin. The request is set using the smarter_request property setter, which also handles URL parsing and user authentication.

Parameters:
  • args – Positional arguments passed to the setup method.

  • request (HttpRequest | None) – The HTTP request object to be associated with this mixin instance.

  • user (AnonymousUser | User | None) – The user associated with the request, if available.

  • kwargs – Keyword arguments passed to the setup method.

Return type:

None

property smarter_request_user: AnonymousUser | User | None

Returns the user associated with the request.

This property is named to avoid potential name collisions in child classes. It retrieves the user from the request object if available.

Example:

request_mixin = SmarterRequestMixin(request)
user = request_mixin.smarter_request_user
Returns:

The user associated with the request, or None if not available.

sorted_dict(data)

Returns a new dictionary with keys sorted.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with sorted keys.

Return type:

dict[str, Any]

property srm_formatted_class_name: str

Returns the class name in a formatted string along with the name of this mixin.

Returns:

Formatted class name string.

property srm_ready: bool

Returns True if the request mixin is srm_ready for processing.

This is a convenience property to check if the request is srm_ready.

Returns:

True if the request mixin is srm_ready, False otherwise.

property subdomain: str | None

Extract the subdomain from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
sub = request_mixin.subdomain
print(sub)  # e.g., 'hr.3141-5926-5359.alpha' for
            # 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/'
Returns:

The subdomain, or None if not found.

template_path: str = ''
property timestamp: datetime

Create a consistent timestamp based on the time that this object was instantiated.

Example:

request_mixin = SmarterRequestMixin(request)
ts = request_mixin.timestamp
print(ts)  # e.g., 2025-12-01 12:34:56.789012
Returns:

The time at which this object was instantiated.

to_camel_case(data, convert_values=False)

Converts a snake_case string to camelCase.

This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The snake_case string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in camelCase.

Return type:

ConvertibleCaseT

to_json()

Serialize the object.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the object, with the auth header and api token masked.

to_snake_case(data, convert_values=False)

Converts a camelCase or PascalCase string to snake_case.

This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The camelCase or PascalCase string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in snake_case.

Return type:

ConvertibleCaseT

property uid: str | None

Unique identifier for the client.

This is assumed to be a combination of the machine MAC address and the hostname.

Example:

request_mixin = SmarterRequestMixin(request)
uid = request_mixin.uid
print(uid)  # e.g., '00:1A:2B:3C:4D:5E-myhost'
Returns:

The client UID as a string, or None if not available.

property unformatted_class_name: str

Returns the raw class name without formatting.

Returns:

The unformatted class name as a string.

Return type:

str

This is useful for logging or serialization where the plain class name is needed.

property unique_client_string: str

Generate a unique string based on several request attributes.

This string is used for generating session_key and client_key.

The unique string is composed of:

  • Account number, when there is an account

  • URL

  • User agent

  • IP address

Example:

request_mixin = SmarterRequestMixin(request)
unique_str = request_mixin.unique_client_string
print(unique_str)
Returns:

A unique string representing the client and request context.

property url: str | None

The string representation of the ParseResult object stored in _parsed_url.

Example:

request_mixin = SmarterRequestMixin(request)
url_str = request_mixin.url
print(url_str)  # e.g., 'https://example.com/path/'
Returns:

The URL as a string.

property url_account_number: str | None

Extract the account number from the URL, using SmarterValidator.VALID_ACCOUNT_NUMBER_PATTERN.

For example, this url returns "3141-5926-5359":

http://example.3141-5926-5359.api.localhost:9357/config
Returns:

The account number as a string, or None if there is no request, the request is not qualified, or the url has no account number.

property url_path_parts: list[str]

Extract the path parts from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
parts = request_mixin.url_path_parts
print(parts)  # e.g., ['api', 'v1', 'workbench', '1', 'prompt']
Returns:

A list of strings representing each part of the URL path.

property user: AnonymousUser | User | None

Returns the user.

Handle lazy instantiation from user_profile or account.

Returns:

The user.

Return type:

User or None

property user_agent: str | None

Get the client’s user agent string from the request object.

This property attempts to extract the user agent from the request’s META dictionary, using the HTTP_USER_AGENT key.

Example:

request_mixin = SmarterRequestMixin(request)
ua = request_mixin.user_agent
print(ua)  # e.g., 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...'
Returns:

The client’s user agent string, the placeholder "user_agent" if the header is missing, or None if the request has no META dictionary.

property user_profile: UserProfile | None

Returns the user_profile for the current user.

Handle lazy instantiation from user or account.

Returns:

The user_profile for the current user.

Return type:

UserProfile or None

view_is_async = False