ox.utils

ox.utils.apps

class ox.utils.apps.DiscoverModules(module_names=None, **handlers)[source]

Utility function used to discover sub-modules in applications.

For each declared sub-module, there must be an equivalent method handler with the following signature: handle_{module_name}(self, app, module, **kw) (where dots in module_name are replace by _)

get_app_module(app, module_name)[source]

Yield app, sub_module for each sub-module found for apps.

get_handler(module_name)[source]

Return handler function for the provided

get_module_names()[source]

Return modules names as an iterable

Return type:

Iterable[str]

module_names: Union[str, Iterable[str]] = ''

A single or a list of module names to look-up for.

run(app_configs=None, **kw)[source]

Run handler over all modules.

run_handler(module_name, app_configs=None, **kw)[source]

Run handler over app config looking for the provided module.

ox.utils.apps.get_or_create_app_config(module)[source]

Get AppConfig based on app module.

It looks up in apps registry, if not found tries to import it (using AppConfig.create).

Parameters:

module (str) – app module path

Return type:

AppConfig

Returns:

the AppConfig instance

Raises:
  • ImportError – module couldn’t be imported;

  • ImproperlyConfigured – app was not configured properly;

ox.utils.apps.order_apps_dependencies(app_configs=None)[source]

Return applications ordered by dependencies (topological sort).

Parameters:

app_configs (Optional[Iterable[AppConfig | str]]) – an iterable of AppConfig to look dependencies for (defaults to apps registry)

Return type:

list[AppConfig]

Returns:

a list of ordered app configs by dependencies.

ox.utils.conf

class ox.utils.conf.Settings(key, source=<LazySettings "ox.settings.dev">)[source]

This class provide settings configuration with default values.

Configuration keys are declared and document under subclass of this one as UPPERCASED attributes. This allows to document them.

User can still import the class in settings.py in order to reuse already existing values.

Example myapp.conf

from ox.utils import conf

__all__ = ("MyAppSettings", "app_settings")

class MyAppSettings(conf.Settings):
    ALLOWED_TAGS = ["a", "b", "br"]
    """ Tags allowed for this application. """
    SOME_VALUE = 123
    """ Other documented setting. """

# this is the actual instance used to retrieve settings
app_settings = MyAppSettings("MYAPP")

In project settings.py:

from myapp.settings import MyAppSettings

MYAPP = {
    "ALLOWED_TAGS": [*MyAppSettings.ALLOWED_TAGS, "p"],
}

Usage:

from myapp.conf import app_settings

# Just print it out...
print(app_settings.ALLOWED_TAGS, app_settings.SOME_VALUE)
class ox.utils.conf.SettingsEditor(name, dir=None)[source]

Helper class to work with dynaconf settings files.

classmethod from_app(app, *args, **kwargs)[source]

Return SettingsEditor for the provided file.

read()[source]

Read data from settings.

Return type:

dict[str, Any] | None

write(data)[source]

Write data to settings file.

ox.utils.commands

class ox.utils.commands.AppsCommand(stdout=None, stderr=None, no_color=False, force_color=False)[source]

Base command class adding features to select applications.

add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

apps: list[AppConfig]

User selected apps

set_options(**options)[source]

Set class instance values based on user’s options.

class ox.utils.commands.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]

Oxylus management command.

add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

handle(func=None, **kwargs)[source]

Default implementation will run provided function.

Flowchart:

  • set_options

  • func(**kwargs)

log(msg, level=1)[source]

Log provided message.

set_options(**options)[source]

Set class instance values based on user’s options.

ox.utils.functional

class ox.utils.functional.Owned[source]

Class designed to be owned by a parent one, referencing it.

The _owner attribute is set after instanciation, using contribute(). This method ensure to create a shallow copy of self that can be referenced by owner class.

contribute(owner)[source]

Copy self, assign owner and return.

ox.utils.functional.dependency_order(items, attr='dependencies')[source]
Return type:

list[Any]

Returns:

a list of items topologically sorted by dependency.

ox.utils.jwt

class ox.utils.jwt.JWToken(**data)[source]

A JSON Web Token to encode or decode.

It is a pydantic model whose values are decoded from raw string / is used to serialize the token.

When expiration is provided, model validation checks that it is not expired.

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ox.utils.jwt.JWTokenViewMixin[source]

View mixin that validate input jwt.

The JWT is provided as url argument (string) or GET parameter, and is read at dispatch. PermissionDenied is raised if an error occurs. Otherwise, sets jwt to the decoded token.

get_jwt(value)[source]

Get JWT from the provided string.

Yield PermissionDenied:

an error occurred decoding the token.

jwt: JWToken = None

The JWT read from url if any.

jwt_str: str = None

The provided JWT string.

jwtoken_class: Type[JWToken] = None

JWToken class to invoke

ox.utils.jwt.decode(value, algorithms=['HS256'], **kwargs)[source]

Simple wrapper around pyjwt’s decode, using configured key (and fallback keys).

It will try to run over all keys provided by JWT_KEY and JWT_KEY_FALLBACKS settings. If none succeed, will re-raise error that happened on the decoding using JWT_KEY.

Parameters:
  • jwt – the token to be decoded.

  • **kwargs

    extra parameters to pass to jwt.decode.

Return type:

dict[str, Any] | JWToken

ox.utils.jwt.encode(payload, headers=None, json_encoder=None, algorithm='HS256')[source]

Simple wrapper around pyjwt’s encode, using configured key and HS256 algorithm.

ox.utils.models

This module provide fields and models that can be reused among all applications.

class ox.utils.models.ChildOwned(*args, **kwargs)[source]

Add parenting mechanism for parent-child relations, checking that owner is the same on parent and child.

Parent and child MUST both inherit from django-caps’ Owned.

Access

alias of ChildOwnedAccess

on_save(fields=None)[source]

Hook called when model is saved.

parent_attr = 'parent'

Field name used for parenting.

class ox.utils.models.ChildOwnedQuerySet(model=None, query=None, using=None, hints=None)[source]

Queryset for ChildOwned.

class ox.utils.models.ClassField(*args, **kwargs)[source]

Allows user to target a class using provided path.

Important note: this field should NEVER be editable by users.

The python object is ClassPath, which provides a property ClassPath.cls used to get the targetted class.

contribute_to_class(cls, name, private_only=False)[source]

Register the field with the model class it belongs to.

If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model.

get_prep_value(value)[source]

Perform preliminary non-db specific value checks and conversions.

to_python(value)[source]

Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can’t be converted. Return the converted value. Subclasses should override this.

class ox.utils.models.ClassPath(path_or_cls)[source]

This object represent a class stored in the database.

The class is accessed through the cls property.

property cls: type | None[source]

Resolve and return the actual class object.

:yield ImportError when import failed

class ox.utils.models.ColorField(*args, **kwargs)[source]

CharField taking a color as input.

formfield(**kwargs)[source]

Return a django.forms.Field instance for this field.

class ox.utils.models.Colored(*args, **kwargs)[source]

Provide a ColorField named color.

class ox.utils.models.Created(*args, **kwargs)[source]

Provide updated field, which specifies the last model update datetime.

class ox.utils.models.Described(*args, **kwargs)[source]

Provide name (mandatory) and description field.

class ox.utils.models.LongNamed(*args, **kwargs)[source]

Provide mandatory name field (long name: 128).

class ox.utils.models.Named(*args, **kwargs)[source]

Provide mandatory name field.

class ox.utils.models.OnlyDescribed(*args, **kwargs)[source]

Provide description field.

class ox.utils.models.PackageInfo(*args, **kwargs)[source]
class ox.utils.models.SaveHook(*args, **kwargs)[source]

Provide on_save hook called when model is saved. This is called on related queryset methods too.

When using this class, if you need to have custom queryset, you’ll have to subclass it from SaveHookQuerySet.

async on_asave(fields=None)[source]

Hook called when model is saved (async).

on_save(fields=None)[source]

Hook called when model is saved.

save(*args, **kwargs)[source]

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

class ox.utils.models.SaveHookQuerySet(model=None, query=None, using=None, hints=None)[source]

This is the QuerySet used for SaveHook model and sub-models.

bulk_create(objs, *a, **kw)[source]

Insert each of the instances into the database. Do not call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported.

bulk_update(objs, fields, *a, **kw)[source]

Update the given fields in each of the given objects in the database.

class ox.utils.models.SerializerField(*args, serializer_class, many=False, **kwargs)[source]

This field is a JSONField validated using Django Rest Framework serializer.

Though serializers already do the work, this ensures that data stays correct when users uses django admin interface or forms.

Note

Validation is made at field clean, so whenever you actually want to validate data, you must call model’s full_clean() (which is by Django forms).

clean(value, model_instance)[source]

Convert the value’s type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised.

serializer_class: Type[Serializer] = None

Django Rest Framework serializer class.

class ox.utils.models.Timestamped(*args, **kwargs)[source]

Provide both created and updated fields.

class ox.utils.models.Updated(*args, **kwargs)[source]

Provide updated field, which specifies the last model update datetime.

class ox.utils.models.Versioned(*args, **kwargs)[source]

Provide version field, which specifies a version.

ox.utils.models.get_model(model, apps=None)[source]

Return a model provided by model name, using provided registry if any.

Return type:

Model

ox.utils.models.get_models(models, apps=None)[source]

Return a list of model provided by models names.

When apps registry is provided use this specific registry, otherwise use default application registry.

This method is usefull to provide function that can be run both in migrations (using RunPython) and as is.

Return type:

list[Model]

Parameters:
  • models_refs – list of app_name.model_name

  • apps (Apps | None) – apps registry to use

:return a list of models (ordered by input ones)

ox.utils.tests

class ox.utils.tests.Mock(**attrs)[source]

Provide a class to mock class and values.

ox.utils.tests.track_calls(obj, name, returns=None)[source]

Spoof object’s method to keep track of its calls.

Parameters:
  • obj – object to spoof method from

  • name – method name

  • retuns – return value

Return a list in which calls will be stored. For each call:

(args, kwargs).