def __init__(self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None): self._location = location self._base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode setting_changed.connect(self._clear_cached_properties)
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, prefix): """ Loads our settings from django.conf.settings, applying defaults for any that are omitted. """ self.prefix = prefix setting_changed.connect(self._handler)
def __init__(self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None): self._location = location if base_url is not None and not base_url.endswith("/"): base_url += "/" self._base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode setting_changed.connect(self._clear_cached_properties)
def ready(self): set_read_only() for alias in connections: connection = connections[alias] install_hook(connection) connection_created.connect(install_hook) setting_changed.connect(reset_read_only)
def __init__(self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None): self._location = location if base_url is not None and not base_url.endswith('/'): base_url += '/' self._base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode setting_changed.connect(self._clear_cached_properties)
def __init__(self, prefix): self.prefix = prefix from django.conf import settings self.django_settings = settings for name, default in six.iteritems(self.defaults): prefix_name = (self.prefix + '_' + name).upper() value = getattr(self.django_settings, prefix_name, default) self._set_attr(prefix_name, value) setting_changed.connect(self._handler)
def __init__(self): """ Initialization method. The ``invalidate_cache`` method will be connected to the Django ``setting_changed`` signal in this method, with the dispatch UID being the id of this very object (``id(self)``). """ if self.__class__ == AppSettings: raise RuntimeError("Do not use AppSettings class as itself, " "use it as a base for subclasses") setting_changed.connect(self.invalidate_cache, dispatch_uid=id(self)) self._cache = {}
def __init__(self, **kwargs): # Check for unknown kwargs. for kwarg_key in kwargs.keys(): if (kwarg_key.upper() not in self.default_auth_settings and kwarg_key.upper() not in self.default_s3_settings): raise ImproperlyConfigured( "Unknown S3Storage parameter: {}".format(kwarg_key)) # Set up the storage. self._kwargs = kwargs self._setup() # Re-initialize the storage if an AWS setting changes. setting_changed.connect(self._setting_changed_received) # All done! super(S3Storage, self).__init__()
def ready(self): # import at ready time to prevent model loading before app ready from dynamic_logging.scheduler import main_scheduler try: main_scheduler.reload( 2 ) # 2 sec to prevent unit-tests to load the production database except OperationalError: # pragma: nocover pass # no trigger table exists atm. we don't care since there is no Trigger to pull. # setup signals for Trigger changes. it will reload the current trigger and next one self.auto_signal_handler.apply(get_setting('signals_auto')) self.setup_propagator() setting_changed.connect(self.on_settings_changed)
def __init__(self): self.__module_path_split = self.__class__.__module__.split('.') self._set_prefix() # Load values from defaults module self._load_defaults() # Load deprecation data self._prepare_deprecation_data() # This will create the dictionaries if they don't already exist self.reset_caches() # Define 'attribute reference' shortcuts self.models = AttrReferToMethodHelper(self, 'get_model') self.modules = AttrReferToMethodHelper(self, 'get_module') self.objects = AttrReferToMethodHelper(self, 'get_object') setting_changed.connect(self.reset_caches, dispatch_uid=id(self))
def __init__(self): self.backends = {} setting_changed.connect(self._reset_backends)
from typing import Any import uuid import django.test.signals from django.contrib.auth import authenticate, get_user_model from django.contrib.auth.hashers import MD5PasswordHasher from django.core.signals import setting_changed from django.test import TestCase, override_settings from fd_dj_accounts.auth_backends import AuthUserModelAuthBackend from . import utils # warning: this is critical for being able to mess with 'AUTH_USER_MODEL' in the tests. setting_changed.disconnect(receiver=django.test.signals.user_model_swapped) setting_changed.connect(receiver=utils.auth_user_model_swapped_receiver) class CountingMD5PasswordHasher(MD5PasswordHasher): """Hasher that counts how many times it computes a hash.""" calls = 0 def encode(self, *args, **kwargs): # type: ignore type(self).calls += 1 return super().encode(*args, **kwargs) class AuthUserModelAuthBackendTestMixin: """ Base class for test cases of ``AuthUserModelAuthBackend``.
def ready(self): setting_changed.connect(update_level_tags)
def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError('Invalid Elasticsearch backend setting: \'%s\'' % attr) try: value = self.user_settings[attr] except KeyError: value = self.defaults[attr] # Cache the setting setattr(self, attr, value) return value @property def user_settings(self): if not getattr(self, '_user_settings'): self._user_settings = getattr(settings, 'ES_BACKEND_SETTINGS', {}) return self._user_settings es_settings = ESSettings(None, DEFAULTS) def reload_es_settings(*args, **kwargs): global es_settings setting, value = kwargs['setting'], kwargs['value'] if setting == 'ES_BACKEND_SETTINGS': es_settings = ESSettings(value, DEFAULTS) setting_changed.connect(reload_es_settings)
self.defaults = defaults self.user_settings = user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid JSON API setting: '%s'" % attr) value = getattr(self.user_settings, JSON_API_SETTINGS_PREFIX + attr, self.defaults[attr]) # Cache the result setattr(self, attr, value) return value json_api_settings = JSONAPISettings() def reload_json_api_settings(*args, **kwargs): django_setting = kwargs['setting'] setting = django_setting.replace(JSON_API_SETTINGS_PREFIX, '') value = kwargs['value'] if setting in DEFAULTS.keys(): if value is not None: setattr(json_api_settings, setting, value) elif hasattr(json_api_settings, setting): delattr(json_api_settings, setting) setting_changed.connect(reload_json_api_settings)
def pytest_configure(config): setting_changed.connect(clear_caches, dispatch_uid="shuup_test_clear_caches") settings.SHUUP_TELEMETRY_ENABLED = False
# Cache the result setattr(self, name, value) return value def get_setting(self, setting): django_setting = 'FILTERS_%s' % setting if setting in DEPRECATED_SETTINGS and hasattr(dj_settings, django_setting): deprecate("The '%s' setting has been deprecated." % django_setting) return getattr(dj_settings, django_setting, DEFAULTS[setting]) def change_setting(self, setting, value, enter, **kwargs): if not setting.startswith('FILTERS_'): return setting = setting[8:] # strip 'FILTERS_' # ensure a valid app setting is being overridden if setting not in DEFAULTS: return # if exiting, delete value to repopulate if enter: setattr(self, setting, value) else: delattr(self, setting) settings = Settings() setting_changed.connect(settings.change_setting)
class Settings(object): FIXED_SETTINGS = ('VIEW_NAME', ) def __init__(self, default): setattr(self, 'default', default) user_settings = getattr(django_settings, 'TAGGIT_FORMS', {}) self._update(user_settings) def _update(self, user_settings): for key in self.default: if key in user_settings and key not in self.FIXED_SETTINGS: self.default[key] = user_settings[key] def __getattr__(self, name): if name in self.default: return self.default[name] raise AttributeError settings = Settings(TAGGIT_FORMS) def update_settings(*args, **kwargs): if kwargs['setting'] == 'TAGGIT_FORMS': value = kwargs['value'] if value: settings._update(value) setting_changed.connect(update_settings)
def ready(self): _configure() checks.register(check_migrations, "migrations") setting_changed.connect(_watch_settings)
def ready(self): # Connect the settings_changed signal so that we can # pick up changes from django settings. setting_changed.connect(load_settings)
# This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shoop.xtheme.theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shoop.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("View %r not callable" % view) return view def get_view_by_name(theme, view_name): if not theme: return None cache_key = (theme.identifier, view_name)
def ready(self): self.configure_sendable_emails() setting_changed.connect(self._on_setting_changed)
FILE_CACHE_DIR = '/tmp/cacheops_file_cache' FILE_CACHE_TIMEOUT = 60*60*24*30 class Settings(object): def __getattr__(self, name): res = getattr(base_settings, name, getattr(Defaults, name)) if name == 'CACHEOPS_PREFIX': res = res if callable(res) else import_string(res) # Save to dict to speed up next access, __getattr__ won't be called self.__dict__[name] = res return res settings = Settings() setting_changed.connect(lambda setting, **kw: settings.__dict__.pop(setting, None), weak=False) @memoize def prepare_profiles(): """ Prepares a dict 'app.model' -> profile, for use in model_profile() """ profile_defaults = { 'ops': (), 'local_get': False, 'db_agnostic': True, 'lock': False, } profile_defaults.update(settings.CACHEOPS_DEFAULTS)
# -*- coding: utf-8 -*- from django.conf import settings from django.core.signals import setting_changed from django.utils.module_loading import import_string IGNORE_EXCEPTIONS = [] class Config(object): _ignore_exceptions = [] def update_config(sender=None, setting=None, value=None, enter=False, **kwargs): conf._ignore_exceptions = [import_string(a) for a in (getattr(settings, 'CRASHLOG_IGNORE_EXCEPTIONS', IGNORE_EXCEPTIONS))] conf = Config() update_config() setting_changed.connect(update_config)
# This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shuup.xtheme._theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("Error! View `%r` is not callable." % view) return view def get_view_by_name(theme, view_name): if not theme: return None cache_key = (theme.identifier, view_name)
value = getattr(self.user_settings, JSON_API_SETTINGS_PREFIX + attr, self.defaults[attr]) # Cache the result setattr(self, attr, value) return value @property def format_type(self): if self.FORMAT_KEYS is not None: return self.FORMAT_KEYS return self.FORMAT_FIELD_NAMES json_api_settings = JSONAPISettings() def reload_json_api_settings(*args, **kwargs): django_setting = kwargs['setting'] setting = django_setting.replace(JSON_API_SETTINGS_PREFIX, '') value = kwargs['value'] if setting in DEFAULTS.keys(): if value is not None: setattr(json_api_settings, setting, value) elif hasattr(json_api_settings, setting): delattr(json_api_settings, setting) setting_changed.connect(reload_json_api_settings)
user_settings=None, defaults=None, import_strings=None, removed_settings=None settings_key=None, settings_doc=None ): self._settings_doc = settings_doc or 'https://www.django-rest-framework.org/api-guide/settings/' self._removed_settings = removed_settings or REMOVED_SETTINGS if user_settings: self._user_settings = self.__check_user_settings(user_settings) self.defaults = defaults or DEFAULTS self.import_strings = import_strings or IMPORT_STRINGS self._settings_key = settings_key or 'REST_FRAMEWORK' self._cached_attrs = set() setting_changed.connect(self.reload_api_settings) def __del__(self): setting_changed.disconnect(self.reload_api_settings) @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(settings, self._settings_key, {}) return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid API setting: '%s'" % attr) try:
res = res if callable(res) else import_string(res) # Convert old list of classes to list of strings if name == 'CACHEOPS_SKIP_FIELDS': [ f if isinstance(f, str) else f.get_internal_type(res) for f in res ] # Save to dict to speed up next access, __getattr__ won't be called self.__dict__[name] = res return res settings = Settings() setting_changed.connect( lambda setting, **kw: settings.__dict__.pop(setting, None), weak=False) @memoize def prepare_profiles(): """ Prepares a dict 'app.model' -> profile, for use in model_profile() """ profile_defaults = { 'ops': (), 'local_get': False, 'db_agnostic': True, 'lock': False, } profile_defaults.update(settings.CACHEOPS_DEFAULTS)
msg = "'%s' object has no attribute '%s'" raise AttributeError(msg % (self.__class__.__name__, name)) value = self.get_setting(name) setattr(self, name, value) return value def get_setting(self, setting): django_setting = self.prefix + setting return getattr(dj_settings, django_setting, DEFAULTS[setting]) def change_setting(self, setting, value, enter, **kwargs): if not setting.startswith(self.prefix): return setting = setting.replace(self.prefix, '') if setting not in DEFAULTS: return if enter: setattr(self, setting, value) else: delattr(self, setting) if not hasattr(dj_settings, 'SIMPLE_LOG_MODEL'): setattr(dj_settings, 'SIMPLE_LOG_MODEL', DEFAULTS['MODEL']) settings = Settings() setting_changed.connect(settings.change_setting)
def can_post_datum(self, request): return True def can_edit_slides(self, request): user = getattr(request, "user", None) if user: return bool(getattr(user, "is_staff", False)) return False _POLICY_CLASS = None def get_policy(): """ :rtype: infotv.policy.BasePolicy """ global _POLICY_CLASS if not _POLICY_CLASS: policy_class_name = getattr(settings, "INFOTV_POLICY_CLASS", "infotv.policy.DefaultPolicy") _POLICY_CLASS = import_string(policy_class_name) return _POLICY_CLASS() def _sig_clear_cached_policy(**kwargs): global _POLICY_CLASS _POLICY_CLASS = None setting_changed.connect(_sig_clear_cached_policy)
def pytest_configure(config): setting_changed.connect(clear_caches, dispatch_uid="shoop_test_clear_caches")
def __init__(self, *args, **kwargs): self._dispatch_uid = uuid.uuid4() super(LDAPBackend, self).__init__(*args, **kwargs) setting_changed.connect(self._on_setting_changed, dispatch_uid=self._dispatch_uid)
def __init__(self, location=None, base_url=None, options=None): self._base_location = location self._base_url = base_url setting_changed.connect(self._clear_cached_properties)
raise ImproperlyConfigured("Missing host_patterns in '%s'" % hostconf) def clear_host_caches(): get_hostconf.cache_clear() get_hostconf_module.cache_clear() get_host.cache_clear() get_host_patterns.cache_clear() def setting_changed_receiver(setting, enter, **kwargs): if setting in {'ROOT_HOSTCONF', 'DEFAULT_HOST'}: clear_host_caches() setting_changed.connect(setting_changed_receiver) def reverse_host(host, args=None, kwargs: dict = None): """ Given the host name and the appropriate parameters, reverses the host, e.g.:: >>> from django.conf import settings >>> settings.ROOT_HOSTCONF = 'mysite.hosts' >>> settings.PARENT_HOST = 'example.com' >>> from django_hosts.resolvers import reverse_host >>> reverse_host('with_username', args=('jezdez',)) 'jezdez.example.com' :param name: the name of the host as specified in the hostconf
self._user_settings = getattr(settings, SETTING_NAMESPACE, {}) return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid 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] # Cache the result setattr(self, attr, val) return val surveys_settings = AppSettings(None, DEFAULTS) def reload_settings(*args, **kwargs): # pylint:disable=unused-argument global surveys_settings setting, value = kwargs['setting'], kwargs['value'] if setting == SETTING_NAMESPACE: surveys_settings = AppSettings(value, DEFAULTS) setting_changed.connect(reload_settings)
def clear_settings_cache(): global settings_cache settings_cache = None def get_cached_setting_key(key): setup_settings_cache() return settings_cache[key] def settings_changed_handler(setting, **kwargs): if setting == settings_attr: clear_settings_cache() setting_changed.connect(settings_changed_handler) class CachedSettingsMixin(object): def __init__(self, *args, **kwargs): self.update_patterns() super(CachedSettingsMixin, self).__init__(*args, **kwargs) def update_patterns(self): if not self.js_assets_repl_enabled: return esc_tag = re.escape(self.js_assets_repl_tag) self.patterns += (("*.js", (( r"""(/\*!\s*%s(?:\((.*?)\))?\s*\*/\s*['"](.*?)['"]\s*/\*!\s*end%s\s*\*/(\n)?)""" % (esc_tag, esc_tag), """'%s'"""), )), )
raise ImproperlyConfigured("Missing host_patterns in '%s'" % hostconf) def clear_host_caches(): get_hostconf.cache_clear() get_hostconf_module.cache_clear() get_host.cache_clear() get_host_patterns.cache_clear() def setting_changed_receiver(setting, enter, **kwargs): if setting in {'ROOT_HOSTCONF', 'DEFAULT_HOST'}: clear_host_caches() setting_changed.connect(setting_changed_receiver) def reverse_host(host, args=None, kwargs=None): """ Given the host name and the appropriate parameters, reverses the host, e.g.:: >>> from django.conf import settings >>> settings.ROOT_HOSTCONF = 'mysite.hosts' >>> settings.PARENT_HOST = 'example.com' >>> from django_hosts.resolvers import reverse_host >>> reverse_host('with_username', args=('jezdez',)) 'jezdez.example.com' :param name: the name of the host as specified in the hostconf
def pytest_configure(config): setting_changed.connect(clear_caches, dispatch_uid="E-Commerce_test_clear_caches") settings.E-Commerce_TELEMETRY_ENABLED = False