def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings if hasattr(settings, 'CONCURRENCY_SANITY_CHECK'): warnings.warn( 'Starting from concurrency 0.7 `CONCURRENCY_SANITY_CHECK` has no effect and will be removed in 0.8' ) if hasattr(Model, '_do_update'): self.defaults['PROTOCOL'] = 2 for name, default in self.defaults.items(): if name != 'SANITY_CHECK': prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self.__class__, setting=prefix_name, value=value, enter=True) setting_changed.connect(self._handler)
def ready(self): setting_changed.connect(uninstall_if_needed) # Connections may already exist before we are called. for conn in connections.all(): if conn.vendor == 'postgresql': conn.introspection.data_types_reverse.update({ 3802: 'django.contrib.postgres.fields.JSONField', 3904: 'django.contrib.postgres.fields.IntegerRangeField', 3906: 'django.contrib.postgres.fields.DecimalRangeField', 3910: 'django.contrib.postgres.fields.DateTimeRangeField', 3912: 'django.contrib.postgres.fields.DateRangeField', 3926: 'django.contrib.postgres.fields.BigIntegerRangeField', }) if conn.connection is not None: register_type_handlers(conn) connection_created.connect(register_type_handlers) CharField.register_lookup(Unaccent) TextField.register_lookup(Unaccent) CharField.register_lookup(SearchLookup) TextField.register_lookup(SearchLookup) CharField.register_lookup(TrigramSimilar) TextField.register_lookup(TrigramSimilar)
def ready(self): setting_changed.connect(uninstall_if_needed) # Connections may already exist before we are called. for conn in connections.all(): if conn.vendor == 'postgresql': conn.introspection.data_types_reverse.update({ 3904: 'django.contrib.postgres.fields.IntegerRangeField', 3906: 'django.contrib.postgres.fields.DecimalRangeField', 3910: 'django.contrib.postgres.fields.DateTimeRangeField', 3912: 'django.contrib.postgres.fields.DateRangeField', 3926: 'django.contrib.postgres.fields.BigIntegerRangeField', }) if conn.connection is not None: register_type_handlers(conn) connection_created.connect(register_type_handlers) CharField.register_lookup(Unaccent) TextField.register_lookup(Unaccent) CharField.register_lookup(SearchLookup) TextField.register_lookup(SearchLookup) CharField.register_lookup(TrigramSimilar) TextField.register_lookup(TrigramSimilar) CharField.register_lookup(TrigramWordSimilar) TextField.register_lookup(TrigramWordSimilar) MigrationWriter.register_serializer(RANGE_TYPES, RangeSerializer) IndexExpression.register_wrappers(OrderBy, OpClass, Collate)
def __init__(self): self.translations_updater = TranslationsUpdater() self.translations_loader = TranslationsLoader() self.translations_updater_watcher = FileWatcher(self.translations_updater) self.translations_loader_watcher = FileWatcher(self.translations_loader) self.reconfigure() setting_changed.connect(self._reconfigure) self.waiting_for_first_request = True
def __init__(self, name, defaults, settings): self.name = name self.defaults = defaults self.keys = set(defaults.keys()) self._cache = {} self._reload(getattr(settings, self.name, {})) setting_changed.connect(self._settings_changed)
def __init__(self, settings_key, *, defaults=None, settings_to_import=None, raise_if_not_exist=True): """Set defaults settings and empty cache.""" self.settings_key = settings_key self.defaults = defaults or {} self.settings_to_import = set(settings_to_import or []) self.raise_if_not_exist = raise_if_not_exist self._cached_attrs = set() self._user_settings = None # register the reloading method of this class to the signal reload_this_api_settings = partial(APISettings.reload, self) setting_changed.connect(reload_this_api_settings)
def get_swagger_settings(): from django.test.signals import setting_changed from rest_framework.settings import APISettings DEFAULTS = { 'USE_SESSION_AUTH': True, 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', 'DOC_EXPANSION': None, 'APIS_SORTER': None, 'OPERATIONS_SORTER': None, 'JSON_EDITOR': False, 'SHOW_REQUEST_HEADERS': False, 'SUPPORTED_SUBMIT_METHODS': ['get', 'post', 'put', 'delete', 'patch'], 'VALIDATOR_URL': '', 'ACCEPT_HEADER_VERSION': None, # e.g. '1.0' 'CUSTOM_HEADERS': {} # A dictionary of key/vals to override headers } IMPORT_STRINGS = [] swagger_settings = APISettings(user_settings=getattr( settings, 'SWAGGER_SETTINGS', {}), defaults=DEFAULTS, import_strings=IMPORT_STRINGS) def reload_settings(*args, **kwargs): # pragma: no cover """ Reloads settings during unit tests if override_settings decorator is used. (Taken from DRF) """ # pylint: disable=W0603 global swagger_settings if kwargs['setting'] == 'LOGIN_URL': swagger_settings.LOGIN_URL = kwargs['value'] if kwargs['setting'] == 'LOGOUT_URL': swagger_settings.LOGOUT_URL = kwargs['value'] if kwargs['setting'] != 'SWAGGER_SETTINGS': return swagger_settings = APISettings(kwargs['value'], DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_settings) return swagger_settings
def __init__(self): if self.REQUIRED_SETTINGS or self.OPTIONAL_SETTINGS: for key in self.REQUIRED_SETTINGS: if hasattr(django.conf.settings, key): self.load_setting(key, getattr(django.conf.settings, key)) else: raise django.core.exceptions.ImproperlyConfigured( self.__class__.__name__ + " requires setting " + key) for key in self.OPTIONAL_SETTINGS: self.load_setting(key, getattr(django.conf.settings, key, None)) setting_changed.connect(self._on_setting_changed)
def ready(self): self.update_scout_config_from_django_settings() setting_changed.connect(self.on_setting_changed) # Finish installing the agent. If the agent isn't installed for any # reason, return without installing instruments installed = scout_apm.core.install() if not installed: return self.install_middleware() # Setup Instruments ensure_sql_instrumented() ensure_templates_instrumented()
def __init__(self): if not self.REQUIRED_SETTINGS and not self.OPTIONAL_SETTINGS: return for key in self.REQUIRED_SETTINGS: if hasattr(django.conf.settings, key): self.load_setting(key, getattr(django.conf.settings, key)) else: raise ImproperlyConfigured(self.__class__.__name__ + " requires setting " + key) for key in self.OPTIONAL_SETTINGS: self.load_setting(key, getattr(django.conf.settings, key, None)) setting_changed.connect(self._on_setting_changed)
def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings for name, default in self.defaults.items(): prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self.__class__, setting=prefix_name, value=value, enter=True) setting_changed.connect(self._handler)
def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings for name, default in self.defaults.items(): prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self, setting=prefix_name, value=value) setting_changed.connect(self._handler)
def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings for name, default in self.defaults.items(): prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self.__class__, setting=prefix_name, value=value, enter=True) setting_changed.connect(self._handler) if not os.path.isdir(self.CACHE): raise ImproperlyConfigured('%s is not a valid directory. Please change `settings.GEO_CACHE` value or create it', self.CACHE)
def ready(self): self.update_scout_config_from_django_settings() setting_changed.connect(self.on_setting_changed) # Finish installing the agent. If the agent isn't installed for any # reason, return without installing instruments installed = scout_apm.core.install() if not installed: return if scout_config.value("errors_enabled"): got_request_exception.connect(self.on_got_request_exception) self.install_middleware() # Setup Instruments ensure_huey_instrumented() ensure_sql_instrumented() ensure_templates_instrumented()
def __init__(self, get_response=None): self.get_response = get_response if not self.REQUIRED_SETTINGS and not self.OPTIONAL_SETTINGS: return for key in self.REQUIRED_SETTINGS: if hasattr(django.conf.settings, key): self.load_setting(key, getattr(django.conf.settings, key)) else: raise ImproperlyConfigured( self.__class__.__name__ + " requires setting " + key ) for key in self.OPTIONAL_SETTINGS: self.load_setting( key, getattr(django.conf.settings, key, None) ) setting_changed.connect(self._on_setting_changed)
def __init__(self, user_settings=None, defaults=None, import_strings=None, namespace=None): """ Initialize the settings. :param user_settings: The pre-set user settings. :type user_settings: dict | None :param defaults: The default settings to use :type defaults: dict | None :param import_strings: The names of the importable settings :type import_strings: iterable of str | None :param namespace: The namespace of the settings or "CUSTOM" :type namespace: str | None """ APISettings.__init__(self, user_settings, defaults, import_strings) self.namespace = namespace or "CUSTOM" setting_changed.connect(self.reload_settings)
def test_signals(self, settings): result = [] def assert_signal(signal, sender, setting, value, enter): result.append((setting, value, enter)) from django.test.signals import setting_changed setting_changed.connect(assert_signal) result = [] settings.SECRET_KEY = "change 1" settings.SECRET_KEY = "change 2" assert result == [ ("SECRET_KEY", "change 1", True), ("SECRET_KEY", "change 2", True), ] result = [] settings.FOOBAR = "abc123" assert sorted(result) == [("FOOBAR", "abc123", True)]
def test_signals(self, settings): result = [] def assert_signal(signal, sender, setting, value, enter): result.append((setting, value, enter)) from django.test.signals import setting_changed setting_changed.connect(assert_signal) result = [] settings.SECRET_KEY = 'change 1' settings.SECRET_KEY = 'change 2' assert result == [ ('SECRET_KEY', 'change 1', True), ('SECRET_KEY', 'change 2', True), ] result = [] settings.FOOBAR = 'abc123' assert sorted(result) == [ ('FOOBAR', 'abc123', True), ]
def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings for name, default in self.defaults.items(): prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self.__class__, setting=prefix_name, value=value, enter=True) setting_changed.connect(self._handler) if not os.path.isdir(self.CACHE): raise ImproperlyConfigured( '%s is not a valid directory. Please change `settings.GEO_CACHE` value or create it', self.CACHE)
def __init__(self, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix from django.conf import settings if hasattr(settings, 'CONCURRENCY_SANITY_CHECK'): warnings.warn( 'Starting from concurrency 0.7 `CONCURRENCY_SANITY_CHECK` has no effect and will be removed in 0.8') if hasattr(Model, '_do_update'): self.defaults['PROTOCOL'] = 2 for name, default in self.defaults.items(): if name != 'SANITY_CHECK': prefix_name = (self.prefix + '_' + name).upper() value = getattr(settings, prefix_name, default) self._set_attr(prefix_name, value) setattr(settings, prefix_name, value) setting_changed.send(self.__class__, setting=prefix_name, value=value, enter=True) setting_changed.connect(self._handler)
# Support the old-style settings if getattr(settings, 'QUERYCOUNT_THRESHOLDS', False): QC_SETTINGS['THRESHOLDS'] = settings.QUERYCOUNT_THRESHOLDS # Apply new-style settings if not getattr(settings, 'QUERYCOUNT', False): return # Duplicate display is a special case, configure it specifically if 'DISPLAY_DUPLICATES' in settings.QUERYCOUNT: duplicate_settings = settings.QUERYCOUNT['DISPLAY_DUPLICATES'] if duplicate_settings is not None: duplicate_settings = int(duplicate_settings) QC_SETTINGS['DISPLAY_DUPLICATES'] = duplicate_settings # Apply the rest of the setting overrides for key in ['THRESHOLDS', 'IGNORE_REQUEST_PATTERNS', 'IGNORE_SQL_PATTERNS', 'IGNORE_PATTERNS', 'RESPONSE_HEADER']: if key in settings.QUERYCOUNT: QC_SETTINGS[key] = settings.QUERYCOUNT[key] # Perform initial load of settings _process_settings() # Subscribe to setting changes, via unit tests, etc setting_changed.connect(_process_settings)
def setup(): global env env = make_environment() initialize(env) setting_changed.connect(testing_reinitialize_signal)
if attr not in self.defaults: raise AttributeError("Invalid Graphene setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val graphene_settings = GrapheneSettings(None, DEFAULTS, IMPORT_STRINGS) def reload_graphene_settings(*args, **kwargs): global graphene_settings setting, value = kwargs["setting"], kwargs["value"] if setting == "GRAPHENE": graphene_settings = GrapheneSettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_graphene_settings)
# Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if val and attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val def dumps(self): data = {} for key in self.defaults.iterkeys(): data[key] = serialize_objects(getattr(self, key)) return json.dumps(data) require_js_settings = RequireJSSettings(USER_SETTINGS) def reload_require_js_settings(*args, **kwargs): global require_js_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'REQUIREJS': require_js_settings = RequireJSSettings(value) setting_changed.connect(reload_require_js_settings)
id='hvad.settings.W01')) else: errors.extend(checker(value)) return errors #=============================================================================== def _build(): """ Build hvad settings from django settings """ user_settings = getattr(djsettings, 'HVAD', {}) hvad_settings = _default_settings.copy() hvad_settings.update({ 'FALLBACK_LANGUAGES': tuple(code for code, name in user_settings.get('LANGUAGES', djsettings.LANGUAGES)), }) hvad_settings.update(user_settings) # Ensure settings are frozen hvad_settings['LANGUAGES'] = tuple(hvad_settings['LANGUAGES']) hvad_settings['FALLBACK_LANGUAGES'] = tuple(hvad_settings['FALLBACK_LANGUAGES']) return namedtuple('HvadSettings', hvad_settings.keys())(*hvad_settings.values()) hvad_settings = SimpleLazyObject(_build) #=============================================================================== def invalidate_settings(**kwargs): """ Empty hvad_settings so next lookup rebuilds them from django settings """ hvad_settings._wrapped = empty setting_changed.connect(invalidate_settings)
# print("20180502 save() {}".format(dd.obj2str(self, True))) super(SiteConfig, self).save(*args, **kw) settings.SITE.clear_site_config() def my_handler(sender, **kw): # print("20180502 {} my_handler calls clear_site_config()".format( # settings.SITE)) settings.SITE.clear_site_config() #~ kw.update(sender=sender) # dd.database_connected.send(sender) #~ dd.database_connected.send(sender,**kw) from django.test.signals import setting_changed from lino.utils.djangotest import testcase_setup setting_changed.connect(my_handler) testcase_setup.connect(my_handler) dd.connection_created.connect(my_handler) models.signals.post_migrate.connect(my_handler) class SiteConfigs(dd.Table): """ The table used to present the :class:`SiteConfig` row in a Detail form. See also :meth:`lino.Lino.get_site_config`. Deserves more documentation. """ model = 'system.SiteConfig' required_roles = dd.login_required(SiteStaff) # default_action = actions.ShowDetail()
def settings_updater(func): func() setting_changed.connect(func, dispatch_uid=id(func)) return func
msg = ("You MUST set the TOKEN_SETTINGS['API_BASE_URL']" "value in your settings file") raise AttributeError(msg) def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid Token Consumer setting: '{}'".format(attr)) try: # Get project specific version val = self.project_settings[attr] except KeyError: val = self.defaults[attr] # Cache the result setattr(self, attr, val) return val token_settings = TokenSettings(None) def reload_token_settings(*args, **kwargs): global token_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'TOKEN_CONSUMER': token_settings = TokenSettings(value) setting_changed.connect(reload_token_settings)
# coding: utf-8 from django.core.urlresolvers import clear_url_caches from django.dispatch import Signal try: from django.test.signals import setting_changed except ImportError: # Make our own signal that can be used any library that's interested and # wants to work in Django <1.4. Having this allows code to assume # `setting_changed` exists, making it simpler. setting_changed = Signal(providing_args=["setting", "value"]) def urlconf_caching(sender, setting, value, **kwargs): if setting == "ROOT_URLCONF": clear_url_caches() setting_changed.connect(urlconf_caching)
super(SiteConfig, self).save(*args, **kw) settings.SITE.clear_site_config() def my_handler(sender, **kw): # print("20180502 {} my_handler calls clear_site_config()".format( # settings.SITE)) settings.SITE.clear_site_config() #~ kw.update(sender=sender) # dd.database_connected.send(sender) #~ dd.database_connected.send(sender,**kw) from django.test.signals import setting_changed from lino.core.signals import testcase_setup setting_changed.connect(my_handler) testcase_setup.connect(my_handler) dd.connection_created.connect(my_handler) models.signals.post_migrate.connect(my_handler) class SiteConfigs(dd.Table): model = 'system.SiteConfig' required_roles = dd.login_required(SiteStaff) # default_action = actions.ShowDetail() #~ has_navigator = False hide_top_toolbar = True #~ can_delete = perms.never detail_layout = """ default_build_method
from django.contrib.auth.models import User from django.core import mail from django.test import TestCase from django.test.signals import setting_changed from django.test.utils import override_settings def update_login_canary_settings(**kwargs): setting = kwargs['setting'] if setting.startswith('LOGIN_CANARY_'): from login_canary import settings setting = setting[13:] setattr(settings, setting, kwargs['value']) setting_changed.connect(update_login_canary_settings) class LoggedInTests(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( 'user', '*****@*****.**', 'password', ) def test_user_login(self): self.assertEqual(len(mail.outbox), 0) self.client.login(username='******', password='******') self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertEqual(message.subject, 'Successful login on Test Service')
if attr not in self.defaults: raise AttributeError("Invalid Graphene setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val graphene_settings = GrapheneSettings(None, DEFAULTS, IMPORT_STRINGS) def reload_graphene_settings(*args, **kwargs): global graphene_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'GRAPHENE': graphene_settings = GrapheneSettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_graphene_settings)
from django import VERSION as django_version from django.core.management import call_command from django.test import TestCase, override_settings from django.test.signals import setting_changed from cities.models import (Country, Region, Subregion, City, District, PostalCode, AlternativeName) from ..mixins import ( NoInvalidSlugsMixin, CountriesMixin, RegionsMixin, SubregionsMixin, CitiesMixin, DistrictsMixin, AlternativeNamesMixin, PostalCodesMixin) from ..utils import reload_cities_settings setting_changed.connect(reload_cities_settings, dispatch_uid='reload_cities_settings') @override_settings(CITIES_SKIP_CITIES_WITH_EMPTY_REGIONS=True) class SkipCitiesWithEmptyRegionsManageCommandTestCase( NoInvalidSlugsMixin, CountriesMixin, RegionsMixin, SubregionsMixin, CitiesMixin, DistrictsMixin, TestCase): num_countries = 250 num_regions = 171 num_ad_regions = 7 num_ua_regions = 27 num_subregions = 4928 num_cities = 117 num_ua_cities = 50 num_districts = 3
if attr in self.import_strings: val = perform_import(val, attr) # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val def __check_user_settings(self, user_settings): return user_settings def reload(self): for attr in self._cached_attrs: delattr(self, attr) self._cached_attrs.clear() if hasattr(self, '_user_settings'): delattr(self, '_user_settings') crmify_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) def reload_crmify_settings(*args, **kwargs): setting = kwargs['setting'] if setting == 'CRMIFY': crmify_settings.reload() setting_changed.connect(reload_crmify_settings)
""" if self.OIDC_ISS_ENDPOINT: return self.OIDC_ISS_ENDPOINT if isinstance(request, HttpRequest): django_request = request elif isinstance(request, Request): django_request = _PhonyHttpRequest() django_request.META = request.headers if request.headers.get("X_DJANGO_OAUTH_TOOLKIT_SECURE", False): django_request._scheme = "https" else: raise TypeError( "request must be a django or oauthlib request: got %r" % request) abs_url = django_request.build_absolute_uri( reverse("oauth2_provider:oidc-connect-discovery-info")) return abs_url[:-len("/.well-known/openid-configuration/")] oauth2_settings = OAuth2ProviderSettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS, MANDATORY) def reload_oauth2_settings(*args, **kwargs): setting = kwargs["setting"] if setting == "OAUTH2_PROVIDER": oauth2_settings.reload() setting_changed.connect(reload_oauth2_settings)
raise AttributeError('Invalid SEARCH setting: {}'.format(attr)) try: val = self.user_settings[attr] except KeyError: val = self.defaults[attr] # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val def reload(self): for attr in self._cached_attrs: delattr(self, attr) self._cached_attrs.clear() if hasattr(self, '_user_settings'): delattr(self, '_user_settings') app_settings = APISettings(None, DEFAULTS) def reload_search_settings(*args, **kwargs): setting = kwargs['setting'] if setting == 'SEARCH': app_settings.reload() setting_changed.connect(reload_search_settings)
# Merge app dict settings with defaults if isinstance(val, dict): default_bundle = OrderedDict(self.defaults[attr]) default_bundle.update(val) val = default_bundle except KeyError: # Fall back to defaults val = self.defaults[attr] if isinstance(val, tuple): try: val = OrderedDict(val) except ValueError: raise ValueError(_("Invalid %s settings value. Please check the settings documentation http://django-map-widgets.readthedocs.io/en/latest/widgets/settings.html" % attr)) # Cache the result setattr(self, attr, val) return val mw_settings = MapWidgetSettings(None, DEFAULTS) def reload_widget_settings(*args, **kwargs): global mw_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'MAP_WIDGETS' and value: mw_settings = MapWidgetSettings(None, DEFAULTS) setting_changed.connect(reload_widget_settings)
def _setup(self, explicit_overriden_settings=None): self._wrapped = Settings(default_settings, explicit_overriden_settings) def get(self, key): """ This function is here only to provide backwards compatibility in case anyone uses old settings interface. It is strongly encouraged to use dot notation. """ warnings.warn( 'The settings.get(key) is superseded by the dot attribute access.', PendingDeprecationWarning) try: return getattr(self, key) except AttributeError: raise ImproperlyConfigured('Missing settings: {}[\'{}\']'.format( DJOSER_SETTINGS_NAMESPACE, key)) settings = LazySettings() def reload_djoser_settings(*args, **kwargs): global settings setting, value = kwargs['setting'], kwargs['value'] if setting == DJOSER_SETTINGS_NAMESPACE: settings._setup(explicit_overriden_settings=value) setting_changed.connect(reload_djoser_settings)
if fbf is None: feature_enabled = _feature_enabled_impl else: fbf = fbf.split('.') modulepath = '.'.join(fbf[:-1]) fcn = fbf[-1] mod = __import__(modulepath, fromlist=[fcn]) feature_enabled = getattr(mod, fcn) return feature_enabled def feature_enabled(instance, feature): # Cache the function global _feature_enabled if _feature_enabled is None: _feature_enabled = _resolve_feature_function() return _feature_enabled(instance, feature) def _reset_feature_fn(sender, setting, value, **kwargs): global _feature_enabled if setting == 'FEATURE_BACKEND_FUNCTION': _feature_enabled = None setting_changed.connect(_reset_feature_fn)
'CACHE_TIMEOUT': 300 # seconds (default 5 min) } # List of settings that may be in string import notation. IMPORT_STRINGS = ('DEFAULT_PAGINATION_CLASS', ) class GraphQLAPISettings(APISettings): MODULE_DOC = "https://github.com/eamigo86/graphene-django-extras" @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(settings, 'GRAPHENE_DJANGO_EXTRAS', {}) return self._user_settings graphql_api_settings = GraphQLAPISettings(None, DEFAULTS, IMPORT_STRINGS) def reload_graphql_api_settings(*args, **kwargs): global graphql_api_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'GRAPHENE_DJANGO_EXTRAS': graphql_api_settings = GraphQLAPISettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_graphql_api_settings)
def raises_500(request): """A view that causes a 500 server error.""" raise ValueError("something busted.") urlpatterns = patterns("", url("^500/$", raises_500)) def _clear_url_caches(setting, value, **kwargs): if setting == "ROOT_URLCONF": clear_url_caches() def fake_sentry_handler(request=None, **kwargs): if request: request.sentry = {"id": "the-sentry-id"} setting_changed.connect(_clear_url_caches) got_request_exception.connect(fake_sentry_handler) def test_sentry_500_handler(client): """500 handler puts request in template context.""" with override_settings(ROOT_URLCONF="portfoliyo.tests.view.test_urls", DEBUG_PROPAGATE_EXCEPTIONS=False): response = client.get("/500/", status=500) response.mustcontain("the-sentry-id")
self=self, attr=attr)) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val registration_settings = NestedSettings(None, DEFAULTS, IMPORT_STRINGS, root_setting_name='REST_REGISTRATION') def settings_changed_handler(*args, **kwargs): registration_settings.reset_user_settings() registration_settings.reset_attr_cache() setting_changed.connect(settings_changed_handler)
def get(self, key): """ This function is here only to provide backwards compatibility in case anyone uses old settings interface. It is strongly encouraged to use dot notation. """ warnings.warn( 'The settings.get(key) is superseded by the dot attribute access.', PendingDeprecationWarning ) try: return getattr(self, key) except AttributeError: raise ImproperlyConfigured('Missing settings: {}[\'{}\']'.format( DJOSER_SETTINGS_NAMESPACE, key) ) settings = LazySettings() def reload_djoser_settings(*args, **kwargs): global settings setting, value = kwargs['setting'], kwargs['value'] if setting == DJOSER_SETTINGS_NAMESPACE: settings._setup(explicit_overriden_settings=value) setting_changed.connect(reload_djoser_settings)
'PUSH_SANDBOX': False, 'STORAGE_CLASS': django_settings.DEFAULT_FILE_STORAGE, 'STORAGE_HTTP_REDIRECT': False, 'UPLOAD_TO': 'passes', } class ConfigManager(UserDict): def update_conf(self): self.data = DEFAULTS new = django_settings.WALLETPASS if 'CERT_PATH' in new: new['CERT_CONTENT'] = open(new['CERT_PATH'], 'rb').read() if 'KEY_PATH' in new: new['KEY_CONTENT'] = open(new['KEY_PATH'], 'rb').read() if 'APPLE_WWDRCA_CERT_PATH' in new: new['WWDRCA_CONTENT'] = open(new['APPLE_WWDRCA_CERT_PATH'], 'rb').read() self.data.update(new) dwpconfig = ConfigManager(DEFAULTS) dwpconfig.update_conf() def update_conf(*args, **kwargs): if kwargs['setting'] == 'WALLETPASS': dwpconfig.update_conf() setting_changed.connect(update_conf)
def get_swagger_settings(): from django.test.signals import setting_changed from rest_framework.settings import APISettings DEFAULTS = { 'USE_SESSION_AUTH': True, 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'LOGIN_URL': 'rest_framework:login', 'LOGOUT_URL': 'rest_framework:logout', 'DOC_EXPANSION': None, 'APIS_SORTER': None, 'OPERATIONS_SORTER': None, 'JSON_EDITOR': False, 'SHOW_REQUEST_HEADERS': False, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], 'VALIDATOR_URL': '', 'ACCEPT_HEADER_VERSION': None, # e.g. '1.0' 'CUSTOM_HEADERS': {} # A dictionary of key/vals to override headers } IMPORT_STRINGS = [] swagger_settings = APISettings( user_settings=getattr(settings, 'SWAGGER_SETTINGS', {}), defaults=DEFAULTS, import_strings=IMPORT_STRINGS ) def reload_settings(*args, **kwargs): # pragma: no cover """ Reloads settings during unit tests if override_settings decorator is used. (Taken from DRF) """ # pylint: disable=W0603 global swagger_settings if kwargs['setting'] == 'LOGIN_URL': swagger_settings.LOGIN_URL = kwargs['value'] if kwargs['setting'] == 'LOGOUT_URL': swagger_settings.LOGOUT_URL = kwargs['value'] if kwargs['setting'] != 'SWAGGER_SETTINGS': return swagger_settings = APISettings( kwargs['value'], DEFAULTS, IMPORT_STRINGS ) setting_changed.connect(reload_settings) return swagger_settings
def settings_updater(func): #pragma: no cover ''' Decorator for setting globals depending on django settings ''' func() setting_changed.connect(func, dispatch_uid=id(func)) return func
CONTENTEDITABLE_MODELS = None # CONTENTEDITABLE_MODELS gets transformed below into two internally used # settings: editable_models and e_models # editable_models is just the dict version of CONTENTEDITABLE_MODELS # and e_models is just a convenience for getting the full app+model name # from just the model name try: if not CONTENTEDITABLE_ENABLED: # don't even bother trying to figure out what's editable raise AttributeError CONTENTEDITABLE_MODELS = getattr(settings, 'CONTENTEDITABLE_MODELS') editable_models = dict(CONTENTEDITABLE_MODELS) # build model to app.model lookup dict e_models = dict() for appmodel, _ in CONTENTEDITABLE_MODELS: _, model = appmodel.split(".") e_models[model] = appmodel except AttributeError: editable_models = None e_models = None def settings_modified(sender, setting, value, **kwargs): """ signal handler for testing """ global CONTENTEDITABLE_ENABLED if setting == 'CONTENTEDITABLE_ENABLED': CONTENTEDITABLE_ENABLED = value setting_changed.connect(settings_modified)
} # List of settings that may be in string import notation. IMPORT_STRINGS = ( 'DEFAULT_PAGINATION_CLASS', ) class GraphQLAPISettings(APISettings): MODULE_DOC = "https://github.com/eamigo86/graphene-django-extras" @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(settings, 'GRAPHENE_DJANGO_EXTRAS', {}) return self._user_settings graphql_api_settings = GraphQLAPISettings(None, DEFAULTS, IMPORT_STRINGS) def reload_graphql_api_settings(*args, **kwargs): global graphql_api_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'GRAPHENE_DJANGO_EXTRAS': graphql_api_settings = GraphQLAPISettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_graphql_api_settings)
if attr not in self.defaults.keys(): raise AttributeError("Invalid API setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if val and attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) def reload_api_settings(*args, **kwargs): global api_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'REST_FRAMEWORK': api_settings = APISettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_api_settings)
value = self.defaults[attr] if attr in self.string_imports: value = self._import_setting_from_string(attr, value) self._cached_attrs.add(attr) setattr(self, attr, value) return value def reload(self): update_registry = bool(REGISTRY_SETTINGS & self._cached_attrs) for attr in self._cached_attrs: delattr(self, attr) self._cached_attrs.clear() if hasattr(self, '_user_settings'): delattr(self, '_user_settings') if update_registry: from .registry import registry registry.update_from_settings() trails_settings = TrailsSettings() def reload_trails_settings(sender, **kwargs): from .utils import log_trace log_trace('setting changed: %r, %r', sender, kwargs) if kwargs['setting'] == 'TRAILS': trails_settings.reload() setting_changed.connect(reload_trails_settings)
attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val graphene_django_plus_settings = GrapheneDjangoPlusSettings( None, DEFAULTS, IMPORT_STRINGS) def reload_graphene_django_plus_settings(*args, **kwargs): setting = kwargs["setting"] if setting == "GRAPHENE_DJANGO_PLUS": graphene_django_plus_settings.reload() setting_changed.connect(reload_graphene_django_plus_settings)
class APISettings(_APISettings): # pragma: no cover def __check_user_settings(self, user_settings): SETTINGS_DOC = 'https://github.com/davesque/django-rest-framework-simplejwt#settings' for setting in REMOVED_SETTINGS: if setting in user_settings: raise RuntimeError( format_lazy( _("The '{}' setting has been removed. Please refer to '{}' for available settings." ), setting, SETTINGS_DOC, )) return user_settings api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) def reload_api_settings(*args, **kwargs): # pragma: no cover global api_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'SIMPLE_JWT': api_settings = APISettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_api_settings)
return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid Graph Auth setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result setattr(self, attr, val) return val graph_auth_settings = GraphAuthSettings(None, DEFAULTS, IMPORT_STRINGS) def reload_graph_auth_settings(*args, **kwargs): global graph_auth_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'GRAPH_AUTH': graph_auth_settings = GraphAuthSettings(value, DEFAULTS, IMPORT_STRINGS) setting_changed.connect(reload_graph_auth_settings)