Skip to main content

OpenWISP 2 Utilities

Project description

ci build Test coverage Requirements Status pypi downloads support chat code style: black

Python and Django functions, classes and settings re-used across different OpenWISP modules, stored here with the aim of avoiding code duplication and ease maintenance.

Don’t repeat yourself!

Current features

Install stable version from pypi

Install from pypi:

pip install openwisp-utils

# install optional dependencies for REST framework
pip install openwisp-utils[rest]

# install optional dependencies for tests (flake8, black and isort)
pip install openwisp-utils[qa]

# or install everything
pip install openwisp-utils[rest,qa]

Install development version

Install tarball:

pip install

Alternatively you can install via pip using git:

pip install -e git+git://

Using the admin_theme

The admin theme requires Django >= 2.2..

Add openwisp_utils.admin_theme to INSTALLED_APPS in


    'openwisp_utils.admin_theme',    # <----- add this

    # admin

Using DependencyLoader and DependencyFinder

Add the list of all packages extended to EXTENDED_APPS in

For example, if you’ve extended django_x509:

EXTENDED_APPS = ['django_x509']


This is a static finder which looks for static files in the static directory of the apps listed in settings.EXTENDED_APPS.

Add openwisp_utils.staticfiles.DependencyFinder to STATICFILES_FINDERS in

    'openwisp_utils.staticfiles.DependencyFinder',    # <----- add this


This is a template loader which looks for templates in the templates directory of the apps listed in settings.EXTENDED_APPS.

Add openwisp_utils.loaders.DependencyLoader to template loaders in as shown below.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'OPTIONS': {
            'loaders': [
                # ... other loaders ...
                'openwisp_utils.loaders.DependencyLoader',    # <----- add this
            'context_processors': [
                # ... omitted ...

Supplying custom CSS and JS for the admin theme

Add openwisp_utils.admin_theme.context_processor.admin_theme_settings to template context_processors in as shown below. This will allow to set OPENWISP_ADMIN_THEME_LINKS and OPENWISP_ADMIN_THEME_JS settings to provide CSS and JS files to customise admin theme.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'OPTIONS': {
            'loaders': [
                # ... omitted ...
            'context_processors': [
                # ... other context processors ...
                'openwisp_utils.admin_theme.context_processor.admin_theme_settings'    # <----- add this


You will have to deploy these static files on your own.

In order to make django able to find and load these files you may want to use the STATICFILES_DIR setting in

You can learn more in the Django documentation.

Model utilities


Model class which provides a UUID4 primary key.


Model class inheriting UUIDModel which provides two additional fields:

  • created
  • modified

Which use respectively AutoCreatedField, AutoLastModifiedField from model_utils.fields (self-updating fields providing the creation date-time and the last modified date-time).


A model field whic provides a random key or token, widely used across openwisp modules.

Admin utilities


Admin mixin which adds two readonly fields created and modified.

This is an admin mixin for models inheriting TimeStampedEditableModel which adds the fields created and modified to the database.


A read-only ModelAdmin base class.


A mixin designed for inline items and model forms, ensures the item is created even if the default values are unchanged.

Without this, when creating new objects, inline items won’t be saved unless users change the default values.


An admin class that provides the UUID of the object as a read-only input field (to make it easy and quick to copy/paste).


An admin class that provides an URL as a read-only input field (to make it easy and quick to copy/paste).

Code utilities


Generates an random string of 32 characters.


Returns a new dict which is the result of the merge of the two dictionaries, all elements are deep-copied to avoid modifying the original data structures.


from openwisp_utils.utils import deep_merge_dicts

mergd_dict = deep_merge_dicts(dict1, dict2)


If the program is being executed during automated tests the value supplied in the test argument will be returned, otherwise the one supplied in the value argument is returned.

from openwisp_utils.utils import default_or_test

THROTTLE_RATE = getattr(
    default_or_test(value='20/day', test=None),


default colors: ['white_bold', 'green_bold', 'yellow_bold', 'red_bold']

If you want to print a string in Red Bold, you can do it as below.

from openwisp_utils.utils import print_color

print_color('This is the printed in Red Bold', color_name='red_bold')

You may also provide the end arguement similar to built-in print method.

REST API utilities


A model serializer which calls the model instance full_clean().


If you’re creating an OpenWISP module which provides a REST API built with Django REST Framework, chances is that you may need to define some default settings to control its throttling or other aspects.

Here’s how to easily do it:

from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from openwisp_utils.api.apps import ApiAppConfig

class MyModuleConfig(ApiAppConfig):
    name = 'my_openwisp_module'
    label = 'my_module'
    verbose_name = _('My OpenWISP Module')

    # assumes API is enabled by default
    API_ENABLED = getattr(settings, 'MY_OPENWISP_MODULE_API_ENABLED', True)
    # set throttling rates for your module here
        'DEFAULT_THROTTLE_RATES': {'my_module': '400/hour'},

Every openwisp module which has an API should use this class to configure its own default settings, which will be merged with the settings of the other modules.

Test utilities


This method can be used to mock a signal call inorder to easily verify that the signal has been called.

Usage example as a context-manager:

from openwisp_utils.tests import catch_signal

with catch_signal(openwisp_signal) as handler:


This class extends the default test runner provided by Django and logs the time spent by each test, making it easier to spot slow tests by highlighting time taken by it in yellow (time shall be highlighted in red if it crosses the second threshold).

By default tests are considered slow if they take more than 0.3 seconds but you can control this with OPENWISP_SLOW_TEST_THRESHOLD.

In order to switch to this test runner you have set the following in your

TEST_RUNNER = 'openwisp_utils.tests.TimeLoggingTestRunner'

Quality Assurance Checks

This package contains some common QA checks that are used in the automated builds of different OpenWISP modules.


Shell script to automatically format Python code. It runs isort and black.


Shell script to run the following quality assurance checks:

If a check requires a flag, it can be passed forward in the same way.

Usage example:

openwisp-qa-check --migration-path <path> --message <commit-message>

Any unneeded checks can be skipped by passing --skip-<check-name>

Usage example:

openwisp-qa-check --skip-isort

You can do multiple checkmigrations by passing the arguments with space-delimited string.

For example, this multiple checkmigrations:

checkmigrations --migrations-to-ignore 3 \
                --migration-path ./openwisp_users/migrations/ || exit 1

checkmigrations --migrations-to-ignore 2 \
                --migration-path ./tests/testapp/migrations/ || exit 1

Can be changed with:

openwisp-qa-check --migrations-to-ignore "3 2" \
        --migration-path "./openwisp_users/migrations/ ./tests/testapp/migrations/"


Ensures the latest migrations created have a human readable name.

We want to avoid having many migrations named like

This way we can reconstruct the evolution of our database schemas faster, with less efforts and hence less costs.

Usage example:

checkmigrations --migration-path ./django_freeradius/migrations/


Ensures the last commit message follows our commit message style guidelines.

We want to keep the commit log readable, consistent and easy to scan in order to make it easy to analyze the history of our modules, which is also a very important activity when performing maintenance.

Usage example:

checkcommit --message "$(git log --format=%B -n 1)"

If, for some reason, you wish to skip this QA check for a specific commit message you can add #noqa to the end of your commit message.

Usage example:

[qa] Improved #20

Simulation of a special unplanned case


Ensures that a blank line is kept at the end of each file.


Ensures there django migrations are up to date and no new migrations need to be created.

It accepts an optional --migration-module flag indicating the django app name that should be passed to ./ makemigrations, eg: ./ makemigrations $MIGRATION_MODULE.



default: openwisp_utils.admin_theme.admin.OpenwispAdminSite

If you need to use a customized admin site class, you can use this setting.


default: OpenWISP Admin

Title value used in the <title> HTML tag of the admin site.


default: OpenWISP

Heading text used in the main <h1> HTML tag (the logo) of the admin site.


default: Network administration

Title shown to users in the index page of the admin site.


default: []

Allows to pass a custom list of menu items to display in the admin menu.

If passed, overrides the default menu which is built by different openwisp modules.

The list should not include “home”, “change password” and “log out”, because those are automatically added and cannot be removed.

Example usage:

    {'model': 'config.Device'},
    {'model': 'config.Template'},
    {'model': 'openwisp_users.User'},
        'model': 'openwisp_radius.Accounting',
        'label': 'Radius sessions'  # custom label


default: []

Allows to override the default CSS and favicon, as well as add extra <link> HTML elements if needed.

This setting overrides the default theme, you can reuse the default CSS or replace it entirely.

The following example shows how to keep using the default CSS, supply an additional CSS and replace the favicon.

Example usage:

    {'type': 'text/css', 'href': '/static/admin/css/openwisp.css', 'rel': 'stylesheet', 'media': 'all'},
    {'type': 'text/css', 'href': '/static/admin/css/custom-theme.css', 'rel': 'stylesheet', 'media': 'all'},
    {'type': 'image/x-icon', 'href': '/static/favicon.png', 'rel': 'icon'}


default: []

Allows to pass a list of strings representing URLs of custom JS files to load.

Example usage:



default: True

Whether the OpenAPI documentation is enabled.

When enabled, you can view the available documentation using the Swagger endpoint at /api/v1/docs/.

You also need to add the following url to your project

urlpatterns += [
    url(r'^api/v1/', include('openwisp_utils.api.urls')),



    'title': 'OpenWISP API',
    'default_version': 'v1',
    'description': 'OpenWISP REST API',

Define OpenAPI general information. NOTE: This setting requires OPENWISP_API_DOCS = True to take effect.

For more information about optional parameters check the drf-yasg documentation.


default: [0.3, 1] (seconds)

It can be used to change the thresholds used by TimeLoggingTestRunner to detect slow tests (0.3s by default) and highlight the slowest ones (1s by default) amongst them.

Installing for development

Install sqlite:

sudo apt-get install sqlite3 libsqlite3-dev

Install your forked repo:

git clone git://<your_fork>/openwisp-utils
cd openwisp-utils/
python develop

Install test requirements:

pip install -r requirements-test.txt

Create database:

cd tests/
./ migrate
./ createsuperuser

Run development server:

cd tests/
./ runserver

You can access the admin interface of the test project at

Run tests with:

./ --parallel


Please refer to the OpenWISP contributing guidelines.





Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for openwisp-utils, version 0.5.1
Filename, size File type Python version Upload date Hashes
Filename, size openwisp_utils-0.5.1-py2.py3-none-any.whl (70.3 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size openwisp-utils-0.5.1.tar.gz (74.8 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page