netbox/netbox/netbox/settings.py

796 lines
29 KiB
Python
Raw Normal View History

2022-05-12 15:35:13 +02:00
import hashlib
2020-02-29 08:23:01 +01:00
import importlib
import importlib.util
2016-03-01 17:23:03 +01:00
import os
import platform
import sys
import warnings
from urllib.parse import urlencode, urlsplit
2016-03-01 17:23:03 +01:00
import django
import requests
from django.contrib.messages import constants as messages
2020-03-13 15:20:09 +01:00
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import URLValidator
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
2024-03-22 19:59:04 +01:00
from netbox.config import PARAMS as CONFIG_PARAMS
2022-12-08 15:58:52 +01:00
from netbox.constants import RQ_QUEUE_DEFAULT, RQ_QUEUE_HIGH, RQ_QUEUE_LOW
from netbox.plugins import PluginConfig
2024-03-22 19:59:04 +01:00
from utilities.string import trailing_slash
#
# Environment setup
#
2024-04-22 21:35:34 +02:00
VERSION = '4.0-beta2'
HOSTNAME = platform.node()
# Set the base directory two levels up
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
2019-12-10 19:44:45 +01:00
# Validate Python version
if sys.version_info < (3, 10):
raise RuntimeError(
f"NetBox requires Python 3.10 or later. (Currently installed: Python {platform.python_version()})"
2021-11-04 18:32:52 +01:00
)
#
# Configuration import
#
2024-03-22 19:59:04 +01:00
# Import the configuration module
config_path = os.getenv('NETBOX_CONFIGURATION', 'netbox.configuration')
2016-05-24 17:46:55 +02:00
try:
configuration = importlib.import_module(config_path)
except ModuleNotFoundError as e:
if getattr(e, 'name') == config_path:
raise ImproperlyConfigured(
f"Specified configuration module ({config_path}) not found. Please define netbox/netbox/configuration.py "
f"per the documentation, or specify an alternate module in the NETBOX_CONFIGURATION environment variable."
)
raise
2016-05-24 17:46:55 +02:00
2024-03-22 19:59:04 +01:00
# Check for missing required configuration parameters
for parameter in ('ALLOWED_HOSTS', 'DATABASE', 'SECRET_KEY', 'REDIS'):
if not hasattr(configuration, parameter):
raise ImproperlyConfigured(f"Required parameter {parameter} is missing from configuration.")
2016-05-24 17:46:55 +02:00
2021-10-25 20:42:20 +02:00
# Set static config parameters
2016-05-24 20:24:35 +02:00
ADMINS = getattr(configuration, 'ADMINS', [])
ALLOW_TOKEN_RETRIEVAL = getattr(configuration, 'ALLOW_TOKEN_RETRIEVAL', True)
2024-03-22 19:59:04 +01:00
ALLOWED_HOSTS = getattr(configuration, 'ALLOWED_HOSTS') # Required
AUTH_PASSWORD_VALIDATORS = getattr(configuration, 'AUTH_PASSWORD_VALIDATORS', [])
2024-03-22 19:59:04 +01:00
BASE_PATH = trailing_slash(getattr(configuration, 'BASE_PATH', ''))
CHANGELOG_SKIP_EMPTY_CHANGES = getattr(configuration, 'CHANGELOG_SKIP_EMPTY_CHANGES', True)
CENSUS_REPORTING_ENABLED = getattr(configuration, 'CENSUS_REPORTING_ENABLED', True)
CORS_ORIGIN_ALLOW_ALL = getattr(configuration, 'CORS_ORIGIN_ALLOW_ALL', False)
CORS_ORIGIN_REGEX_WHITELIST = getattr(configuration, 'CORS_ORIGIN_REGEX_WHITELIST', [])
CORS_ORIGIN_WHITELIST = getattr(configuration, 'CORS_ORIGIN_WHITELIST', [])
CSRF_COOKIE_NAME = getattr(configuration, 'CSRF_COOKIE_NAME', 'csrftoken')
2024-03-22 19:59:04 +01:00
CSRF_COOKIE_PATH = f'/{BASE_PATH.rstrip("/")}'
CSRF_COOKIE_SECURE = getattr(configuration, 'CSRF_COOKIE_SECURE', False)
CSRF_TRUSTED_ORIGINS = getattr(configuration, 'CSRF_TRUSTED_ORIGINS', [])
DATA_UPLOAD_MAX_MEMORY_SIZE = getattr(configuration, 'DATA_UPLOAD_MAX_MEMORY_SIZE', 2621440)
2024-03-22 19:59:04 +01:00
DATABASE = getattr(configuration, 'DATABASE') # Required
DEBUG = getattr(configuration, 'DEBUG', False)
DEFAULT_DASHBOARD = getattr(configuration, 'DEFAULT_DASHBOARD', None)
DEFAULT_PERMISSIONS = getattr(configuration, 'DEFAULT_PERMISSIONS', {
# Permit users to manage their own bookmarks
'extras.view_bookmark': ({'user': '$user'},),
'extras.add_bookmark': ({'user': '$user'},),
'extras.change_bookmark': ({'user': '$user'},),
'extras.delete_bookmark': ({'user': '$user'},),
# Permit users to manage their own API tokens
'users.view_token': ({'user': '$user'},),
'users.add_token': ({'user': '$user'},),
'users.change_token': ({'user': '$user'},),
'users.delete_token': ({'user': '$user'},),
})
DEVELOPER = getattr(configuration, 'DEVELOPER', False)
DJANGO_ADMIN_ENABLED = getattr(configuration, 'DJANGO_ADMIN_ENABLED', False)
DOCS_ROOT = getattr(configuration, 'DOCS_ROOT', os.path.join(os.path.dirname(BASE_DIR), 'docs'))
EMAIL = getattr(configuration, 'EMAIL', {})
EVENTS_PIPELINE = getattr(configuration, 'EVENTS_PIPELINE', (
'extras.events.process_event_queue',
))
2021-10-26 17:39:39 +02:00
EXEMPT_VIEW_PERMISSIONS = getattr(configuration, 'EXEMPT_VIEW_PERMISSIONS', [])
FIELD_CHOICES = getattr(configuration, 'FIELD_CHOICES', {})
FILE_UPLOAD_MAX_MEMORY_SIZE = getattr(configuration, 'FILE_UPLOAD_MAX_MEMORY_SIZE', 2621440)
HTTP_PROXIES = getattr(configuration, 'HTTP_PROXIES', None)
INTERNAL_IPS = getattr(configuration, 'INTERNAL_IPS', ('127.0.0.1', '::1'))
JINJA2_FILTERS = getattr(configuration, 'JINJA2_FILTERS', {})
LANGUAGE_CODE = getattr(configuration, 'DEFAULT_LANGUAGE', 'en-us')
2024-03-22 19:59:04 +01:00
LANGUAGE_COOKIE_PATH = CSRF_COOKIE_PATH
LOGGING = getattr(configuration, 'LOGGING', {})
2021-10-26 17:39:39 +02:00
LOGIN_PERSISTENCE = getattr(configuration, 'LOGIN_PERSISTENCE', False)
LOGIN_REQUIRED = getattr(configuration, 'LOGIN_REQUIRED', False)
LOGIN_TIMEOUT = getattr(configuration, 'LOGIN_TIMEOUT', None)
LOGOUT_REDIRECT_URL = getattr(configuration, 'LOGOUT_REDIRECT_URL', 'home')
MEDIA_ROOT = getattr(configuration, 'MEDIA_ROOT', os.path.join(BASE_DIR, 'media')).rstrip('/')
2021-10-26 17:39:39 +02:00
METRICS_ENABLED = getattr(configuration, 'METRICS_ENABLED', False)
PLUGINS = getattr(configuration, 'PLUGINS', [])
2020-02-29 08:23:01 +01:00
PLUGINS_CONFIG = getattr(configuration, 'PLUGINS_CONFIG', {})
QUEUE_MAPPINGS = getattr(configuration, 'QUEUE_MAPPINGS', {})
2024-03-22 19:59:04 +01:00
REDIS = getattr(configuration, 'REDIS') # Required
2021-10-26 17:39:39 +02:00
RELEASE_CHECK_URL = getattr(configuration, 'RELEASE_CHECK_URL', None)
REMOTE_AUTH_AUTO_CREATE_GROUPS = getattr(configuration, 'REMOTE_AUTH_AUTO_CREATE_GROUPS', False)
2024-03-22 19:59:04 +01:00
REMOTE_AUTH_AUTO_CREATE_USER = getattr(configuration, 'REMOTE_AUTH_AUTO_CREATE_USER', False)
2020-06-01 19:47:34 +02:00
REMOTE_AUTH_BACKEND = getattr(configuration, 'REMOTE_AUTH_BACKEND', 'netbox.authentication.RemoteUserBackend')
REMOTE_AUTH_DEFAULT_GROUPS = getattr(configuration, 'REMOTE_AUTH_DEFAULT_GROUPS', [])
REMOTE_AUTH_DEFAULT_PERMISSIONS = getattr(configuration, 'REMOTE_AUTH_DEFAULT_PERMISSIONS', {})
REMOTE_AUTH_ENABLED = getattr(configuration, 'REMOTE_AUTH_ENABLED', False)
REMOTE_AUTH_GROUP_HEADER = getattr(configuration, 'REMOTE_AUTH_GROUP_HEADER', 'HTTP_REMOTE_USER_GROUP')
2024-03-22 19:59:04 +01:00
REMOTE_AUTH_GROUP_SEPARATOR = getattr(configuration, 'REMOTE_AUTH_GROUP_SEPARATOR', '|')
REMOTE_AUTH_GROUP_SYNC_ENABLED = getattr(configuration, 'REMOTE_AUTH_GROUP_SYNC_ENABLED', False)
2024-03-22 19:59:04 +01:00
REMOTE_AUTH_HEADER = getattr(configuration, 'REMOTE_AUTH_HEADER', 'HTTP_REMOTE_USER')
REMOTE_AUTH_SUPERUSER_GROUPS = getattr(configuration, 'REMOTE_AUTH_SUPERUSER_GROUPS', [])
REMOTE_AUTH_SUPERUSERS = getattr(configuration, 'REMOTE_AUTH_SUPERUSERS', [])
2024-03-22 19:59:04 +01:00
REMOTE_AUTH_USER_EMAIL = getattr(configuration, 'REMOTE_AUTH_USER_EMAIL', 'HTTP_REMOTE_USER_EMAIL')
REMOTE_AUTH_USER_FIRST_NAME = getattr(configuration, 'REMOTE_AUTH_USER_FIRST_NAME', 'HTTP_REMOTE_USER_FIRST_NAME')
REMOTE_AUTH_USER_LAST_NAME = getattr(configuration, 'REMOTE_AUTH_USER_LAST_NAME', 'HTTP_REMOTE_USER_LAST_NAME')
REMOTE_AUTH_STAFF_GROUPS = getattr(configuration, 'REMOTE_AUTH_STAFF_GROUPS', [])
REMOTE_AUTH_STAFF_USERS = getattr(configuration, 'REMOTE_AUTH_STAFF_USERS', [])
# Required by extras/migrations/0109_script_models.py
REPORTS_ROOT = getattr(configuration, 'REPORTS_ROOT', os.path.join(BASE_DIR, 'reports')).rstrip('/')
RQ_DEFAULT_TIMEOUT = getattr(configuration, 'RQ_DEFAULT_TIMEOUT', 300)
RQ_RETRY_INTERVAL = getattr(configuration, 'RQ_RETRY_INTERVAL', 60)
RQ_RETRY_MAX = getattr(configuration, 'RQ_RETRY_MAX', 0)
2019-08-09 18:33:33 +02:00
SCRIPTS_ROOT = getattr(configuration, 'SCRIPTS_ROOT', os.path.join(BASE_DIR, 'scripts')).rstrip('/')
2022-10-21 19:16:16 +02:00
SEARCH_BACKEND = getattr(configuration, 'SEARCH_BACKEND', 'netbox.search.backends.CachedValueSearchBackend')
2024-03-22 19:59:04 +01:00
SECRET_KEY = getattr(configuration, 'SECRET_KEY') # Required
SECURE_HSTS_INCLUDE_SUBDOMAINS = getattr(configuration, 'SECURE_HSTS_INCLUDE_SUBDOMAINS', False)
SECURE_HSTS_PRELOAD = getattr(configuration, 'SECURE_HSTS_PRELOAD', False)
SECURE_HSTS_SECONDS = getattr(configuration, 'SECURE_HSTS_SECONDS', 0)
SECURE_SSL_REDIRECT = getattr(configuration, 'SECURE_SSL_REDIRECT', False)
SENTRY_DSN = getattr(configuration, 'SENTRY_DSN', None)
2022-05-11 20:13:50 +02:00
SENTRY_ENABLED = getattr(configuration, 'SENTRY_ENABLED', False)
SENTRY_SAMPLE_RATE = getattr(configuration, 'SENTRY_SAMPLE_RATE', 1.0)
2022-05-11 20:13:50 +02:00
SENTRY_TAGS = getattr(configuration, 'SENTRY_TAGS', {})
2024-03-22 19:59:04 +01:00
SENTRY_TRACES_SAMPLE_RATE = getattr(configuration, 'SENTRY_TRACES_SAMPLE_RATE', 0)
SESSION_COOKIE_NAME = getattr(configuration, 'SESSION_COOKIE_NAME', 'sessionid')
2024-03-22 19:59:04 +01:00
SESSION_COOKIE_PATH = CSRF_COOKIE_PATH
SESSION_COOKIE_SECURE = getattr(configuration, 'SESSION_COOKIE_SECURE', False)
2024-03-22 19:59:04 +01:00
SESSION_FILE_PATH = getattr(configuration, 'SESSION_FILE_PATH', None)
STORAGE_BACKEND = getattr(configuration, 'STORAGE_BACKEND', None)
STORAGE_CONFIG = getattr(configuration, 'STORAGE_CONFIG', {})
TIME_ZONE = getattr(configuration, 'TIME_ZONE', 'UTC')
2024-03-22 19:59:04 +01:00
# Load any dynamic configuration parameters which have been hard-coded in the configuration file
for param in CONFIG_PARAMS:
2021-10-25 20:42:20 +02:00
if hasattr(configuration, param.name):
globals()[param.name] = getattr(configuration, param.name)
2024-03-22 19:59:04 +01:00
# Enforce minimum length for SECRET_KEY
if type(SECRET_KEY) is not str:
raise ImproperlyConfigured(f"SECRET_KEY must be a string (found {type(SECRET_KEY).__name__})")
if len(SECRET_KEY) < 50:
raise ImproperlyConfigured(
f"SECRET_KEY must be at least 50 characters in length. To generate a suitable key, run the following command:\n"
f" python {BASE_DIR}/generate_secret_key.py"
)
2020-03-13 15:20:09 +01:00
# Validate update repo URL and timeout
if RELEASE_CHECK_URL:
try:
2024-03-22 19:59:04 +01:00
URLValidator()(RELEASE_CHECK_URL)
except ValidationError as e:
raise ImproperlyConfigured(
"RELEASE_CHECK_URL must be a valid URL. Example: https://api.github.com/repos/netbox-community/netbox"
)
2020-03-13 15:20:09 +01:00
#
# Database
#
2016-07-08 23:09:35 +02:00
2024-03-22 19:59:04 +01:00
# Set the database engine
if 'ENGINE' not in DATABASE:
if METRICS_ENABLED:
2024-03-22 19:59:04 +01:00
DATABASE.update({'ENGINE': 'django_prometheus.db.backends.postgresql'})
else:
2024-03-22 19:59:04 +01:00
DATABASE.update({'ENGINE': 'django.db.backends.postgresql'})
2016-07-08 23:09:35 +02:00
2024-03-22 19:59:04 +01:00
# Define the DATABASES setting for Django
2016-05-24 17:46:55 +02:00
DATABASES = {
'default': DATABASE,
2016-05-24 17:46:55 +02:00
}
2019-11-03 12:16:12 +01:00
#
2024-03-22 19:59:04 +01:00
# Storage backend
2019-11-03 12:16:12 +01:00
#
if STORAGE_BACKEND is not None:
DEFAULT_FILE_STORAGE = STORAGE_BACKEND
2019-11-03 12:16:12 +01:00
# django-storages
if STORAGE_BACKEND.startswith('storages.'):
try:
import storages.utils # type: ignore
except ModuleNotFoundError as e:
if getattr(e, 'name') == 'storages':
raise ImproperlyConfigured(
f"STORAGE_BACKEND is set to {STORAGE_BACKEND} but django-storages is not present. It can be "
f"installed by running 'pip install django-storages'."
)
raise e
# Monkey-patch django-storages to fetch settings from STORAGE_CONFIG
def _setting(name, default=None):
if name in STORAGE_CONFIG:
return STORAGE_CONFIG[name]
return globals().get(name, default)
storages.utils.setting = _setting
if STORAGE_CONFIG and STORAGE_BACKEND is None:
warnings.warn(
"STORAGE_CONFIG has been set in configuration.py but STORAGE_BACKEND is not defined. STORAGE_CONFIG will be "
"ignored."
)
#
# Redis
#
# Background task queuing
if 'tasks' not in REDIS:
2024-03-22 19:59:04 +01:00
raise ImproperlyConfigured("REDIS section in configuration.py is missing the 'tasks' subsection.")
TASKS_REDIS = REDIS['tasks']
TASKS_REDIS_HOST = TASKS_REDIS.get('HOST', 'localhost')
TASKS_REDIS_PORT = TASKS_REDIS.get('PORT', 6379)
TASKS_REDIS_SENTINELS = TASKS_REDIS.get('SENTINELS', [])
TASKS_REDIS_USING_SENTINEL = all([
isinstance(TASKS_REDIS_SENTINELS, (list, tuple)),
len(TASKS_REDIS_SENTINELS) > 0
2020-02-13 14:53:46 +01:00
])
TASKS_REDIS_SENTINEL_SERVICE = TASKS_REDIS.get('SENTINEL_SERVICE', 'default')
TASKS_REDIS_SENTINEL_TIMEOUT = TASKS_REDIS.get('SENTINEL_TIMEOUT', 10)
2022-12-29 16:31:06 +01:00
TASKS_REDIS_USERNAME = TASKS_REDIS.get('USERNAME', '')
TASKS_REDIS_PASSWORD = TASKS_REDIS.get('PASSWORD', '')
TASKS_REDIS_DATABASE = TASKS_REDIS.get('DATABASE', 0)
TASKS_REDIS_SSL = TASKS_REDIS.get('SSL', False)
TASKS_REDIS_SKIP_TLS_VERIFY = TASKS_REDIS.get('INSECURE_SKIP_TLS_VERIFY', False)
TASKS_REDIS_CA_CERT_PATH = TASKS_REDIS.get('CA_CERT_PATH', False)
2020-02-13 14:53:46 +01:00
# Caching
if 'caching' not in REDIS:
2024-03-22 19:59:04 +01:00
raise ImproperlyConfigured("REDIS section in configuration.py is missing caching subsection.")
CACHING_REDIS_HOST = REDIS['caching'].get('HOST', 'localhost')
CACHING_REDIS_PORT = REDIS['caching'].get('PORT', 6379)
CACHING_REDIS_DATABASE = REDIS['caching'].get('DATABASE', 0)
2022-12-29 16:31:06 +01:00
CACHING_REDIS_USERNAME = REDIS['caching'].get('USERNAME', '')
CACHING_REDIS_USERNAME_HOST = '@'.join(filter(None, [CACHING_REDIS_USERNAME, CACHING_REDIS_HOST]))
CACHING_REDIS_PASSWORD = REDIS['caching'].get('PASSWORD', '')
CACHING_REDIS_SENTINELS = REDIS['caching'].get('SENTINELS', [])
CACHING_REDIS_SENTINEL_SERVICE = REDIS['caching'].get('SENTINEL_SERVICE', 'default')
CACHING_REDIS_PROTO = 'rediss' if REDIS['caching'].get('SSL', False) else 'redis'
CACHING_REDIS_SKIP_TLS_VERIFY = REDIS['caching'].get('INSECURE_SKIP_TLS_VERIFY', False)
CACHING_REDIS_CA_CERT_PATH = REDIS['caching'].get('CA_CERT_PATH', False)
2024-03-22 19:59:04 +01:00
CACHING_REDIS_URL = f'{CACHING_REDIS_PROTO}://{CACHING_REDIS_USERNAME_HOST}:{CACHING_REDIS_PORT}/{CACHING_REDIS_DATABASE}'
2024-03-22 19:59:04 +01:00
# Configure Django's default cache to use Redis
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
2024-03-22 19:59:04 +01:00
'LOCATION': CACHING_REDIS_URL,
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'PASSWORD': CACHING_REDIS_PASSWORD,
}
}
}
if CACHING_REDIS_SENTINELS:
DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory'
CACHES['default']['LOCATION'] = f'{CACHING_REDIS_PROTO}://{CACHING_REDIS_SENTINEL_SERVICE}/{CACHING_REDIS_DATABASE}'
CACHES['default']['OPTIONS']['CLIENT_CLASS'] = 'django_redis.client.SentinelClient'
CACHES['default']['OPTIONS']['SENTINELS'] = CACHING_REDIS_SENTINELS
if CACHING_REDIS_SKIP_TLS_VERIFY:
CACHES['default']['OPTIONS'].setdefault('CONNECTION_POOL_KWARGS', {})
CACHES['default']['OPTIONS']['CONNECTION_POOL_KWARGS']['ssl_cert_reqs'] = False
if CACHING_REDIS_CA_CERT_PATH:
CACHES['default']['OPTIONS'].setdefault('CONNECTION_POOL_KWARGS', {})
CACHES['default']['OPTIONS']['CONNECTION_POOL_KWARGS']['ssl_ca_certs'] = CACHING_REDIS_CA_CERT_PATH
2024-03-22 19:59:04 +01:00
#
# Sessions
#
if LOGIN_TIMEOUT is not None:
# Django default is 1209600 seconds (14 days)
SESSION_COOKIE_AGE = LOGIN_TIMEOUT
SESSION_SAVE_EVERY_REQUEST = bool(LOGIN_PERSISTENCE)
if SESSION_FILE_PATH is not None:
SESSION_ENGINE = 'django.contrib.sessions.backends.file'
#
2016-05-24 20:24:35 +02:00
# Email
#
2016-05-24 20:24:35 +02:00
EMAIL_HOST = EMAIL.get('SERVER')
2016-05-24 20:37:50 +02:00
EMAIL_HOST_USER = EMAIL.get('USERNAME')
2016-05-24 20:24:35 +02:00
EMAIL_HOST_PASSWORD = EMAIL.get('PASSWORD')
EMAIL_PORT = EMAIL.get('PORT', 25)
EMAIL_SSL_CERTFILE = EMAIL.get('SSL_CERTFILE')
EMAIL_SSL_KEYFILE = EMAIL.get('SSL_KEYFILE')
EMAIL_SUBJECT_PREFIX = '[NetBox] '
EMAIL_USE_SSL = EMAIL.get('USE_SSL', False)
EMAIL_USE_TLS = EMAIL.get('USE_TLS', False)
2016-05-24 20:24:35 +02:00
EMAIL_TIMEOUT = EMAIL.get('TIMEOUT', 10)
SERVER_EMAIL = EMAIL.get('FROM_EMAIL')
#
2024-03-22 19:59:04 +01:00
# Django core settings
#
INSTALLED_APPS = [
2024-03-22 19:59:04 +01:00
'django.contrib.admin',
2016-03-01 17:23:03 +01:00
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.forms',
'corsheaders',
2016-03-01 17:23:03 +01:00
'debug_toolbar',
'django_filters',
'django_htmx',
2016-03-01 17:23:03 +01:00
'django_tables2',
'django_prometheus',
9856 Replace graphene with Strawberry (#15141) * 9856 base strawberry integration * 9856 user and group * 9856 user and circuits base * 9856 extras and mixins * 9856 fk * 9856 update strawberry version * 9856 update imports * 9856 compatability fixes * 9856 compatability fixes * 9856 update strawberry types * 9856 update strawberry types * 9856 core schema * 9856 dcim schema * 9856 extras schema * 9856 ipam and tenant schema * 9856 virtualization, vpn, wireless schema * 9856 fix old decorator * 9856 cleanup * 9856 cleanup * 9856 fixes to circuits type specifiers * 9856 fixes to circuits type specifiers * 9856 update types * 9856 GFK working * 9856 GFK working * 9856 _name * 9856 misc fixes * 9856 type updates * 9856 _name to types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 GraphQLView * 9856 GraphQLView * 9856 fix OrganizationalObjectType * 9856 single item query for schema * 9856 circuits graphql tests working * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 test fix vpn * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 circuits test sans DjangoModelType * 9856 core test sans DjangoModelType * 9856 temp checkin * 9856 fix extas FK * 9856 fix tenancy FK * 9856 fix virtualization FK * 9856 fix vpn FK * 9856 fix wireless FK * 9856 fix ipam FK * 9856 fix partial dcim FK * 9856 fix dcim FK * 9856 fix virtualization FK * 9856 fix tests / remove debug code * 9856 fix test imagefield * 9856 cleanup graphene * 9856 fix plugin schema * 9856 fix requirements * 9856 fix requirements * 9856 fix docs * 9856 fix docs * 9856 temp fix tests * 9856 first filterset * 9856 first filterset * 9856 fix tests * 9856 fix tests * 9856 working auto filter generation * 9856 filter types * 9856 filter types * 9856 filter types * 9856 fix graphiql test * 9856 fix counter fields and merge feature * 9856 temp fix tests * 9856 fix tests * 9856 fix tenancy, ipam filter definitions * 9856 cleanup * 9856 cleanup * 9856 cleanup * 9856 review changes * 9856 review changes * 9856 review changes * 9856 fix base-requirements * 9856 add wrapper to graphiql * 9856 remove old graphiql debug toolbar * 9856 review changes * 9856 update strawberry * 9856 remove superfluous check --------- Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2024-03-22 17:56:30 +01:00
'strawberry_django',
2017-02-28 22:10:53 +01:00
'mptt',
2016-03-01 17:23:03 +01:00
'rest_framework',
2021-10-29 23:06:14 +02:00
'social_django',
'taggit',
'timezone_field',
'core',
'account',
2016-03-01 17:23:03 +01:00
'circuits',
'dcim',
'ipam',
'extras',
2016-07-26 20:58:37 +02:00
'tenancy',
2016-03-01 17:23:03 +01:00
'users',
'utilities',
'virtualization',
'vpn',
'wireless',
'django_rq', # Must come after extras to allow overriding management commands
'drf_spectacular',
'drf_spectacular_sidecar',
]
2024-03-22 19:59:04 +01:00
if not DJANGO_ADMIN_ENABLED:
INSTALLED_APPS.remove('django.contrib.admin')
# Middleware
MIDDLEWARE = [
9856 Replace graphene with Strawberry (#15141) * 9856 base strawberry integration * 9856 user and group * 9856 user and circuits base * 9856 extras and mixins * 9856 fk * 9856 update strawberry version * 9856 update imports * 9856 compatability fixes * 9856 compatability fixes * 9856 update strawberry types * 9856 update strawberry types * 9856 core schema * 9856 dcim schema * 9856 extras schema * 9856 ipam and tenant schema * 9856 virtualization, vpn, wireless schema * 9856 fix old decorator * 9856 cleanup * 9856 cleanup * 9856 fixes to circuits type specifiers * 9856 fixes to circuits type specifiers * 9856 update types * 9856 GFK working * 9856 GFK working * 9856 _name * 9856 misc fixes * 9856 type updates * 9856 _name to types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 GraphQLView * 9856 GraphQLView * 9856 fix OrganizationalObjectType * 9856 single item query for schema * 9856 circuits graphql tests working * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 test fix vpn * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 circuits test sans DjangoModelType * 9856 core test sans DjangoModelType * 9856 temp checkin * 9856 fix extas FK * 9856 fix tenancy FK * 9856 fix virtualization FK * 9856 fix vpn FK * 9856 fix wireless FK * 9856 fix ipam FK * 9856 fix partial dcim FK * 9856 fix dcim FK * 9856 fix virtualization FK * 9856 fix tests / remove debug code * 9856 fix test imagefield * 9856 cleanup graphene * 9856 fix plugin schema * 9856 fix requirements * 9856 fix requirements * 9856 fix docs * 9856 fix docs * 9856 temp fix tests * 9856 first filterset * 9856 first filterset * 9856 fix tests * 9856 fix tests * 9856 working auto filter generation * 9856 filter types * 9856 filter types * 9856 filter types * 9856 fix graphiql test * 9856 fix counter fields and merge feature * 9856 temp fix tests * 9856 fix tests * 9856 fix tenancy, ipam filter definitions * 9856 cleanup * 9856 cleanup * 9856 cleanup * 9856 review changes * 9856 review changes * 9856 review changes * 9856 fix base-requirements * 9856 add wrapper to graphiql * 9856 remove old graphiql debug toolbar * 9856 review changes * 9856 update strawberry * 9856 remove superfluous check --------- Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2024-03-22 17:56:30 +01:00
"strawberry_django.middlewares.debug_toolbar.DebugToolbarMiddleware",
'django_prometheus.middleware.PrometheusBeforeMiddleware',
'corsheaders.middleware.CorsMiddleware',
2016-03-01 17:23:03 +01:00
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
2016-03-01 17:23:03 +01:00
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django_htmx.middleware.HtmxMiddleware',
'netbox.middleware.RemoteUserMiddleware',
'netbox.middleware.CoreMiddleware',
'netbox.middleware.MaintenanceModeMiddleware',
'django_prometheus.middleware.PrometheusAfterMiddleware',
]
2024-03-22 19:59:04 +01:00
# URLs
2016-03-01 17:23:03 +01:00
ROOT_URLCONF = 'netbox.urls'
2024-03-22 19:59:04 +01:00
# Templates
TEMPLATES_DIR = BASE_DIR + '/templates'
2016-03-01 17:23:03 +01:00
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR],
2016-03-01 17:23:03 +01:00
'APP_DIRS': True,
'OPTIONS': {
'builtins': [
'utilities.templatetags.builtins.filters',
'utilities.templatetags.builtins.tags',
],
2016-03-01 17:23:03 +01:00
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
2016-03-01 17:23:03 +01:00
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'netbox.context_processors.settings_and_registry',
2016-03-01 17:23:03 +01:00
],
},
},
]
# This allows us to override Django's stock form widget templates
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
# Set up authentication backends
if type(REMOTE_AUTH_BACKEND) not in (list, tuple):
REMOTE_AUTH_BACKEND = [REMOTE_AUTH_BACKEND]
AUTHENTICATION_BACKENDS = [
*REMOTE_AUTH_BACKEND,
2020-06-01 19:47:34 +02:00
'netbox.authentication.ObjectPermissionBackend',
]
2024-03-22 19:59:04 +01:00
# Use our custom User model
AUTH_USER_MODEL = 'users.User'
2024-03-22 19:59:04 +01:00
# Authentication URLs
LOGIN_URL = f'/{BASE_PATH}login/'
LOGIN_REDIRECT_URL = f'/{BASE_PATH}'
# Use timezone-aware datetime objects
USE_TZ = True
# WSGI
WSGI_APPLICATION = 'netbox.wsgi.application'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
USE_X_FORWARDED_HOST = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = BASE_DIR + '/static'
STATIC_URL = f'/{BASE_PATH}static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'project-static', 'dist'),
os.path.join(BASE_DIR, 'project-static', 'img'),
os.path.join(BASE_DIR, 'project-static', 'js'),
('docs', os.path.join(BASE_DIR, 'project-static', 'docs')), # Prefix with /docs
)
2024-03-22 19:59:04 +01:00
# Media URL
MEDIA_URL = f'/{BASE_PATH}media/'
# Disable default limit of 1000 fields per request. Needed for bulk deletion of objects. (Added in Django 1.10.)
DATA_UPLOAD_MAX_NUMBER_FIELDS = None
# Messages
MESSAGE_TAGS = {
messages.ERROR: 'danger',
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
2021-02-25 01:00:14 +01:00
2024-03-22 19:59:04 +01:00
SERIALIZATION_MODULES = {
'json': 'utilities.serializers.json',
}
#
# Permissions & authentication
#
# Exclude potentially sensitive models from wildcard view exemption. These may still be exempted
# by specifying the model individually in the EXEMPT_VIEW_PERMISSIONS configuration parameter.
EXEMPT_EXCLUDE_MODELS = (
('extras', 'configrevision'),
('users', 'group'),
('users', 'objectpermission'),
('users', 'token'),
('users', 'user'),
)
2021-10-29 23:06:14 +02:00
# All URLs starting with a string listed here are exempt from login enforcement
AUTH_EXEMPT_PATHS = (
2021-10-29 23:06:14 +02:00
f'/{BASE_PATH}api/',
f'/{BASE_PATH}graphql/',
f'/{BASE_PATH}login/',
f'/{BASE_PATH}oauth/',
f'/{BASE_PATH}metrics',
2021-10-29 23:06:14 +02:00
)
# All URLs starting with a string listed here are exempt from maintenance mode enforcement
MAINTENANCE_EXEMPT_PATHS = (
f'/{BASE_PATH}admin/',
f'/{BASE_PATH}extras/config-revisions/', # Allow modifying the configuration
LOGIN_URL,
LOGIN_REDIRECT_URL,
LOGOUT_REDIRECT_URL
)
2021-10-29 23:06:14 +02:00
2022-05-11 20:13:50 +02:00
#
# Sentry
#
if SENTRY_ENABLED:
try:
2024-03-22 19:59:04 +01:00
import sentry_sdk
except ModuleNotFoundError:
raise ImproperlyConfigured("SENTRY_ENABLED is True but the sentry-sdk package is not installed.")
2022-05-11 20:13:50 +02:00
if not SENTRY_DSN:
raise ImproperlyConfigured("SENTRY_ENABLED is True but SENTRY_DSN has not been defined.")
# Initialize the SDK
2022-05-11 20:13:50 +02:00
sentry_sdk.init(
dsn=SENTRY_DSN,
release=VERSION,
2024-03-22 19:59:04 +01:00
integrations=[sentry_sdk.integrations.django.DjangoIntegration()],
sample_rate=SENTRY_SAMPLE_RATE,
traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
2022-05-11 20:13:50 +02:00
send_default_pii=True,
http_proxy=HTTP_PROXIES.get('http') if HTTP_PROXIES else None,
https_proxy=HTTP_PROXIES.get('https') if HTTP_PROXIES else None
)
# Assign any configured tags
2022-05-11 20:13:50 +02:00
for k, v in SENTRY_TAGS.items():
sentry_sdk.set_tag(k, v)
#
# Census collection
#
2024-03-22 19:59:04 +01:00
# Calculate a unique deployment ID from the secret key
DEPLOYMENT_ID = hashlib.sha256(SECRET_KEY.encode('utf-8')).hexdigest()[:16]
CENSUS_URL = 'https://census.netbox.dev/api/v1/'
CENSUS_PARAMS = {
'version': VERSION,
'python_version': sys.version.split()[0],
'deployment_id': DEPLOYMENT_ID,
}
if CENSUS_REPORTING_ENABLED and not DEBUG and 'test' not in sys.argv:
try:
# Report anonymous census data
requests.get(f'{CENSUS_URL}?{urlencode(CENSUS_PARAMS)}', timeout=3, proxies=HTTP_PROXIES)
except requests.exceptions.RequestException:
pass
2021-10-29 23:06:14 +02:00
#
# Django social auth
#
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'netbox.authentication.user_default_groups_handler',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
# Load all SOCIAL_AUTH_* settings from the user configuration
for param in dir(configuration):
if param.startswith('SOCIAL_AUTH_'):
globals()[param] = getattr(configuration, param)
# Force usage of PostgreSQL's JSONB field for extra data
SOCIAL_AUTH_JSONFIELD_ENABLED = True
2022-10-31 17:18:50 +01:00
SOCIAL_AUTH_CLEAN_USERNAME_FUNCTION = 'users.utils.clean_username'
SOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL
#
# Django Prometheus
#
PROMETHEUS_EXPORT_MIGRATIONS = False
#
# Django filters
#
FILTERS_NULL_CHOICE_LABEL = 'None'
FILTERS_NULL_CHOICE_VALUE = 'null'
#
2017-01-27 20:54:12 +01:00
# Django REST framework (API)
#
REST_FRAMEWORK_VERSION = '.'.join(VERSION.split('-')[0].split('.')[:2]) # Use major.minor as API version
2016-03-01 17:23:03 +01:00
REST_FRAMEWORK = {
2017-08-15 21:30:45 +02:00
'ALLOWED_VERSIONS': [REST_FRAMEWORK_VERSION],
'COERCE_DECIMAL_TO_STRING': False,
2017-03-07 23:17:39 +01:00
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'netbox.api.authentication.TokenAuthentication',
2017-03-07 23:17:39 +01:00
),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
2017-03-07 23:17:39 +01:00
),
'DEFAULT_METADATA_CLASS': 'netbox.api.metadata.BulkOperationMetadata',
'DEFAULT_PAGINATION_CLASS': 'netbox.api.pagination.OptionalLimitOffsetPagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.MultiPartParser',
),
2017-03-07 23:17:39 +01:00
'DEFAULT_PERMISSION_CLASSES': (
'netbox.api.authentication.TokenPermissions',
2017-03-07 23:17:39 +01:00
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'netbox.api.renderers.FormlessBrowsableAPIRenderer',
),
'DEFAULT_SCHEMA_CLASS': 'core.api.schema.NetBoxAutoSchema',
2017-03-20 17:33:42 +01:00
'DEFAULT_VERSION': REST_FRAMEWORK_VERSION,
2017-03-02 22:20:16 +01:00
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
'SCHEMA_COERCE_METHOD_NAMES': {
# Default mappings
'retrieve': 'read',
'destroy': 'delete',
# Custom operations
'bulk_destroy': 'bulk_delete',
},
'VIEW_NAME_FUNCTION': 'utilities.api.get_view_name',
2016-03-01 17:23:03 +01:00
}
#
# DRF Spectacular
#
SPECTACULAR_SETTINGS = {
2023-05-01 16:45:19 +02:00
'TITLE': 'NetBox REST API',
'LICENSE': {'name': 'Apache v2 License'},
'VERSION': VERSION,
'COMPONENT_SPLIT_REQUEST': True,
'REDOC_DIST': 'SIDECAR',
2023-05-01 16:45:19 +02:00
'SERVERS': [{
'url': BASE_PATH,
'description': 'NetBox',
}],
'SWAGGER_UI_DIST': 'SIDECAR',
'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
'POSTPROCESSING_HOOKS': [],
}
#
# Django RQ (events backend)
#
if TASKS_REDIS_USING_SENTINEL:
RQ_PARAMS = {
'SENTINELS': TASKS_REDIS_SENTINELS,
'MASTER_NAME': TASKS_REDIS_SENTINEL_SERVICE,
2020-02-13 14:53:46 +01:00
'SOCKET_TIMEOUT': None,
'CONNECTION_KWARGS': {
'socket_connect_timeout': TASKS_REDIS_SENTINEL_TIMEOUT
2020-02-13 14:53:46 +01:00
},
}
else:
RQ_PARAMS = {
'HOST': TASKS_REDIS_HOST,
'PORT': TASKS_REDIS_PORT,
'SSL': TASKS_REDIS_SSL,
'SSL_CERT_REQS': None if TASKS_REDIS_SKIP_TLS_VERIFY else 'required',
}
RQ_PARAMS.update({
'DB': TASKS_REDIS_DATABASE,
2022-12-29 16:31:06 +01:00
'USERNAME': TASKS_REDIS_USERNAME,
'PASSWORD': TASKS_REDIS_PASSWORD,
'DEFAULT_TIMEOUT': RQ_DEFAULT_TIMEOUT,
})
if TASKS_REDIS_CA_CERT_PATH:
RQ_PARAMS.setdefault('REDIS_CLIENT_KWARGS', {})
RQ_PARAMS['REDIS_CLIENT_KWARGS']['ssl_ca_certs'] = TASKS_REDIS_CA_CERT_PATH
2024-03-22 19:59:04 +01:00
# Define named RQ queues
RQ_QUEUES = {
2022-12-08 15:58:52 +01:00
RQ_QUEUE_HIGH: RQ_PARAMS,
RQ_QUEUE_DEFAULT: RQ_PARAMS,
RQ_QUEUE_LOW: RQ_PARAMS,
}
# Add any queues defined in QUEUE_MAPPINGS
RQ_QUEUES.update({
queue: RQ_PARAMS for queue in set(QUEUE_MAPPINGS.values()) if queue not in RQ_QUEUES
})
#
# Localization
#
2024-03-22 19:59:04 +01:00
# Supported translation languages
LANGUAGES = (
('en', _('English')),
('es', _('Spanish')),
('fr', _('French')),
('ja', _('Japanese')),
('pt', _('Portuguese')),
('ru', _('Russian')),
('tr', _('Turkish')),
)
2023-08-07 20:34:56 +02:00
LOCALE_PATHS = (
BASE_DIR + '/translations',
)
9856 Replace graphene with Strawberry (#15141) * 9856 base strawberry integration * 9856 user and group * 9856 user and circuits base * 9856 extras and mixins * 9856 fk * 9856 update strawberry version * 9856 update imports * 9856 compatability fixes * 9856 compatability fixes * 9856 update strawberry types * 9856 update strawberry types * 9856 core schema * 9856 dcim schema * 9856 extras schema * 9856 ipam and tenant schema * 9856 virtualization, vpn, wireless schema * 9856 fix old decorator * 9856 cleanup * 9856 cleanup * 9856 fixes to circuits type specifiers * 9856 fixes to circuits type specifiers * 9856 update types * 9856 GFK working * 9856 GFK working * 9856 _name * 9856 misc fixes * 9856 type updates * 9856 _name to types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 GraphQLView * 9856 GraphQLView * 9856 fix OrganizationalObjectType * 9856 single item query for schema * 9856 circuits graphql tests working * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 test fix vpn * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 circuits test sans DjangoModelType * 9856 core test sans DjangoModelType * 9856 temp checkin * 9856 fix extas FK * 9856 fix tenancy FK * 9856 fix virtualization FK * 9856 fix vpn FK * 9856 fix wireless FK * 9856 fix ipam FK * 9856 fix partial dcim FK * 9856 fix dcim FK * 9856 fix virtualization FK * 9856 fix tests / remove debug code * 9856 fix test imagefield * 9856 cleanup graphene * 9856 fix plugin schema * 9856 fix requirements * 9856 fix requirements * 9856 fix docs * 9856 fix docs * 9856 temp fix tests * 9856 first filterset * 9856 first filterset * 9856 fix tests * 9856 fix tests * 9856 working auto filter generation * 9856 filter types * 9856 filter types * 9856 filter types * 9856 fix graphiql test * 9856 fix counter fields and merge feature * 9856 temp fix tests * 9856 fix tests * 9856 fix tenancy, ipam filter definitions * 9856 cleanup * 9856 cleanup * 9856 cleanup * 9856 review changes * 9856 review changes * 9856 review changes * 9856 fix base-requirements * 9856 add wrapper to graphiql * 9856 remove old graphiql debug toolbar * 9856 review changes * 9856 update strawberry * 9856 remove superfluous check --------- Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2024-03-22 17:56:30 +01:00
#
# Strawberry (GraphQL)
#
STRAWBERRY_DJANGO = {
"TYPE_DESCRIPTION_FROM_MODEL_DOCSTRING": True,
"USE_DEPRECATED_FILTERS": True,
9856 Replace graphene with Strawberry (#15141) * 9856 base strawberry integration * 9856 user and group * 9856 user and circuits base * 9856 extras and mixins * 9856 fk * 9856 update strawberry version * 9856 update imports * 9856 compatability fixes * 9856 compatability fixes * 9856 update strawberry types * 9856 update strawberry types * 9856 core schema * 9856 dcim schema * 9856 extras schema * 9856 ipam and tenant schema * 9856 virtualization, vpn, wireless schema * 9856 fix old decorator * 9856 cleanup * 9856 cleanup * 9856 fixes to circuits type specifiers * 9856 fixes to circuits type specifiers * 9856 update types * 9856 GFK working * 9856 GFK working * 9856 _name * 9856 misc fixes * 9856 type updates * 9856 _name to types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 update types * 9856 GraphQLView * 9856 GraphQLView * 9856 fix OrganizationalObjectType * 9856 single item query for schema * 9856 circuits graphql tests working * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 test fix vpn * 9856 test fixes * 9856 test fixes * 9856 test fixes * 9856 circuits test sans DjangoModelType * 9856 core test sans DjangoModelType * 9856 temp checkin * 9856 fix extas FK * 9856 fix tenancy FK * 9856 fix virtualization FK * 9856 fix vpn FK * 9856 fix wireless FK * 9856 fix ipam FK * 9856 fix partial dcim FK * 9856 fix dcim FK * 9856 fix virtualization FK * 9856 fix tests / remove debug code * 9856 fix test imagefield * 9856 cleanup graphene * 9856 fix plugin schema * 9856 fix requirements * 9856 fix requirements * 9856 fix docs * 9856 fix docs * 9856 temp fix tests * 9856 first filterset * 9856 first filterset * 9856 fix tests * 9856 fix tests * 9856 working auto filter generation * 9856 filter types * 9856 filter types * 9856 filter types * 9856 fix graphiql test * 9856 fix counter fields and merge feature * 9856 temp fix tests * 9856 fix tests * 9856 fix tenancy, ipam filter definitions * 9856 cleanup * 9856 cleanup * 9856 cleanup * 9856 review changes * 9856 review changes * 9856 review changes * 9856 fix base-requirements * 9856 add wrapper to graphiql * 9856 remove old graphiql debug toolbar * 9856 review changes * 9856 update strawberry * 9856 remove superfluous check --------- Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
2024-03-22 17:56:30 +01:00
}
2020-02-29 08:23:01 +01:00
#
# Plugins
#
2024-03-22 19:59:04 +01:00
# Register any configured plugins
for plugin_name in PLUGINS:
try:
2024-03-22 19:59:04 +01:00
# Import the plugin module
plugin = importlib.import_module(plugin_name)
except ModuleNotFoundError as e:
if getattr(e, 'name') == plugin_name:
raise ImproperlyConfigured(
2024-03-22 19:59:04 +01:00
f"Unable to import plugin {plugin_name}: Module not found. Check that the plugin module has been "
f"installed within the correct Python environment."
)
raise e
try:
2024-03-22 19:59:04 +01:00
# Load the PluginConfig
plugin_config: PluginConfig = plugin.config
except AttributeError:
raise ImproperlyConfigured(
2024-03-22 19:59:04 +01:00
f"Plugin {plugin_name} does not provide a 'config' variable. This should be defined in the plugin's "
f"__init__.py file and point to the PluginConfig subclass."
)
2022-09-29 00:11:10 +02:00
plugin_module = "{}.{}".format(plugin_config.__module__, plugin_config.__name__) # type: ignore
# Gather additional apps to load alongside this plugin
django_apps = plugin_config.django_apps
if plugin_name in django_apps:
django_apps.pop(plugin_name)
if plugin_module not in django_apps:
django_apps.append(plugin_module)
# Test if we can import all modules (or its parent, for PluginConfigs and AppConfigs)
for app in django_apps:
if "." in app:
parts = app.split(".")
spec = importlib.util.find_spec(".".join(parts[:-1]))
else:
spec = importlib.util.find_spec(app)
if spec is None:
raise ImproperlyConfigured(
f"Failed to load django_apps specified by plugin {plugin_name}: {django_apps} "
f"The module {app} cannot be imported. Check that the necessary package has been "
2024-03-22 19:59:04 +01:00
f"installed within the correct Python environment."
)
INSTALLED_APPS.extend(django_apps)
2024-03-22 19:59:04 +01:00
# Preserve uniqueness of the INSTALLED_APPS list, we keep the last occurrence
sorted_apps = reversed(list(dict.fromkeys(reversed(INSTALLED_APPS))))
INSTALLED_APPS = list(sorted_apps)
# Validate user-provided configuration settings and assign defaults
if plugin_name not in PLUGINS_CONFIG:
PLUGINS_CONFIG[plugin_name] = {}
plugin_config.validate(PLUGINS_CONFIG[plugin_name], VERSION)
# Add middleware
plugin_middleware = plugin_config.middleware
if plugin_middleware and type(plugin_middleware) in (list, tuple):
MIDDLEWARE.extend(plugin_middleware)
# Create RQ queues dedicated to the plugin
# we use the plugin name as a prefix for queue name's defined in the plugin config
# ex: mysuperplugin.mysuperqueue1
if type(plugin_config.queues) is not list:
2024-03-22 19:59:04 +01:00
raise ImproperlyConfigured(f"Plugin {plugin_name} queues must be a list.")
RQ_QUEUES.update({
f"{plugin_name}.{queue}": RQ_PARAMS for queue in plugin_config.queues
})