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 inmodule_nameare replace by_)-
module_names:
Union[str,Iterable[str]] = '' A single or a list of module names to look-up for.
-
module_names:
- 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.pyin order to reuse already existing values.Example
myapp.conffrom 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)
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.
-
apps:
list[AppConfig] User selected apps
-
apps:
ox.utils.functional
- class ox.utils.functional.Owned[source]
Class designed to be owned by a parent one, referencing it.
The
_ownerattribute is set after instanciation, usingcontribute(). This method ensure to create a shallow copy of self that can be referenced by owner class.
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
expirationis 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
jwtto the decoded token.- get_jwt(value)[source]
Get JWT from the provided string.
- Yield PermissionDenied:
an error occurred decoding the token.
-
jwt_str:
str= None The provided JWT string.
- 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_KEYandJWT_KEY_FALLBACKSsettings. If none succeed, will re-raise error that happened on the decoding usingJWT_KEY.- Parameters:
jwt – the token to be decoded.
**kwargs –
extra parameters to pass to
jwt.decode.
- Return type:
dict[str,Any] |JWToken
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
- 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 propertyClassPath.clsused to get the targetted class.
- class ox.utils.models.ClassPath(path_or_cls)[source]
This object represent a class stored in the database.
The class is accessed through the
clsproperty.
- class ox.utils.models.Colored(*args, **kwargs)[source]
Provide a
ColorFieldnamedcolor.
- 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.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.- 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
SaveHookmodel 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.
- 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
modelname, using provided registry if any.- Return type:
Model
- ox.utils.models.get_models(models, apps=None)[source]
Return a list of model provided by
modelsnames.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_nameapps (
Apps|None) – apps registry to use
:return a list of models (ordered by input ones)