def formfield_for_dbfield(self, db_field, request, **kwargs):
"""
Overloaded from ModelAdmin so that an OpenLayersWidget is used
for viewing/editing 2D GeometryFields (OpenLayers 2 does not support
3D editing).
"""
if isinstance(db_field, models.GeometryField) and db_field.dim < 3:
if not HAS_GDAL and db_field.srid != self.map_srid:
raise ImproperlyConfigured(
"Map SRID is %s and SRID of `%s` is %s. GDAL must be "
"installed to perform the transformation."
% (self.map_srid, db_field, db_field.srid)
)
# Setting the widget with the newly defined widget.
kwargs['widget'] = self.get_map_widget(db_field)
return db_field.formfield(**kwargs)
else:
return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)
python类ImproperlyConfigured()的实例源码
def test_translate_model_with_existing_field(self):
class TestModel2(models.Model):
title = models.CharField(max_length=100)
title_nl = models.CharField(max_length=100)
i18n = TranslationField(fields=('title', ))
class Meta:
app_label = 'django-modeltrans_tests'
expected_message = (
'Error adding translation field. Model "TestModel2" already '
'contains a field named "title_nl".'
)
with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
translate_model(TestModel2)
def get_available_languages_setting():
'''
list of available languages for modeltrans translations.
defaults to the list of language codes extracted from django setting LANGUAGES
'''
languages = tuple(set(getattr(
settings,
'MODELTRANS_AVAILABLE_LANGUAGES',
(code for code, _ in getattr(settings, 'LANGUAGES'))
)))
if not all(isinstance(x, six.string_types) for x in languages):
raise ImproperlyConfigured('MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings')
# make sure LANGUAGE_CODE is not in available languages
return (lang for lang in languages if lang != get_default_language())
def __init__(self, model_lookup, path_field='path', parent_field='parent',
order_by=None, max_siblings=DEFAULT_MAX_SIBLINGS):
self.model_lookup = model_lookup
self.path_field = path_field
self.parent_field = parent_field
if path_field in order_by:
raise ImproperlyConfigured(
'Cannot use `%s` in `CreateTreeTrigger.order_by`.'
% path_field)
self.order_by = () if order_by is None else tuple(order_by)
if not (isinstance(max_siblings, int) and max_siblings > 0):
raise ImproperlyConfigured(
'`max_siblings` must be a positive integer, not %s.'
% repr(max_siblings))
self.max_siblings = max_siblings
i = self.max_siblings
n = 0
while i > 1.0:
i /= ALPHANUM_LEN
n += 1
self.label_size = n
def get_cache(cache=None):
"""Return ``cache`` or the 'default' cache if ``cache`` is not specified or
``cache`` is not configured.
:param cache: The name of the requested cache.
"""
try:
# Check for proper Redis persistent backends
# FIXME: this logic needs to be a system sanity check
if (not settings.DEBUG and cache in PERSISTENT_STORES and
(cache not in settings.CACHES or 'RedisCache' not in
settings.CACHES[cache]['BACKEND'] or
settings.CACHES[cache].get('TIMEOUT', '') is not None)):
raise ImproperlyConfigured(
'Pootle requires a Redis-backed caching backend for %r '
'with `TIMEOUT: None`. Please review your settings.' % cache
)
return caches[cache]
except InvalidCacheBackendError:
return default_cache
def check_config_for(cls, config_dict, username, require_email_fields=False):
"""Ensures the invoice configuration dictionary `config_dict` contains
the required fields.
:param username: Username owning the configuration.
:param validate_email: Whether to also require email-related fields.
"""
required_fields = (
list(sum(cls.required_config_fields, ())) if require_email_fields else
cls.required_config_fields[0]
)
missing_required_fields = [
field for field in required_fields
if field not in config_dict
]
if len(missing_required_fields) > 0:
raise ImproperlyConfigured(
'The configuration for user %s is missing the following required '
'fields: %s.\n'
'Please double-check your configuration.'
% (username, u', '.join(missing_required_fields))
)
return config_dict
def import_func(path):
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing module %s: "%s"'
% (module, e))
try:
func = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured(
'Module "%s" does not define a "%s" callable function'
% (module, attr))
return func
def get_pool():
"""
Use this method to acquire connection pool.
Example usage:
from coreservices.core.rpc import get_pool
# ...
with get_pool().next() as rpc:
rpc.mailer.send_mail(foo='bar')
"""
create_pool_lock.acquire()
global pool
if not pool:
# Lazy instantiation
if not hasattr(settings, 'NAMEKO_CONFIG') or not settings.NAMEKO_CONFIG:
raise ImproperlyConfigured('NAMEKO_CONFIG must be specified and should include at least "AMQP_URL" key.')
pool = ClusterRpcProxyPool(settings.NAMEKO_CONFIG)
pool.start()
create_pool_lock.release()
return pool
def check_dependencies(self):
"""
Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.
"""
from django.contrib.contenttypes.models import ContentType
if not ContentType._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
"in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def __init__(self, start, end, telescopes=None, sites=None, instrument_types=None):
try:
self.es = Elasticsearch([settings.ELASTICSEARCH_URL])
except LocationValueError:
logger.error('Could not find host. Make sure ELASTICSEARCH_URL is set.')
raise ImproperlyConfigured('ELASTICSEARCH_URL')
self.instrument_types = instrument_types
self.available_telescopes = self._get_available_telescopes()
sites = list({tk.site for tk in self.available_telescopes}) if not sites else sites
telescopes = list({tk.telescope for tk in self.available_telescopes if tk.site in sites}) \
if not telescopes else telescopes
self.start = start.replace(tzinfo=timezone.utc).replace(microsecond=0)
self.end = end.replace(tzinfo=timezone.utc).replace(microsecond=0)
cached_event_data = cache.get('tel_event_data')
if cached_event_data:
self.event_data = cached_event_data
else:
self.event_data = self._get_es_data(sites, telescopes)
cache.set('tel_event_data', self.event_data, 1800)
def ready(self):
self.schema = getattr(settings, 'SWAGGER_SCHEMA', None)
if not self.schema:
raise ImproperlyConfigured('You have to provide SWAGGER_SCHEMA setting pointing to desired schema')
else:
self.module = getattr(settings, 'SWAGGER_MODULE', None)
self.swagger = Swagger(self.schema, self.module)
def handle(self, *args, **options):
schema = getattr(settings, 'SWAGGER_SCHEMA', None)
module = getattr(settings, 'SWAGGER_MODULE', None)
if not schema:
raise ImproperlyConfigured('You have to provide SWAGGER_SCHEMA setting pointing to desired schema')
if not module:
raise ImproperlyConfigured('You have to specify desired controller module name in SWAGGER_MODULE setting')
router = SwaggerRouter()
print('Inspecting available controllers...')
router.update(True)
router.process()
print()
print('Following classes and methods are going to be generated:')
enum = router.get_enum()
for name in enum:
print("{} : {}".format(name, [x['method'] for x in enum[name]['methods']]))
if(options['generate']):
template = Template()
filename = module.split('.')[-1] + '.py'
structure = [{ 'name' : name, 'data' : data } for name, data in six.iteritems(enum)]
print('Generating handlers ({})...'.format(filename))
with codecs.open(filename, 'w', 'utf-8') as f:
f.write(template.render(template_name = 'view.jinja', names = structure))
print('Done.')
else:
print()
print('Use --generate option to create them')
def test_build_version_missing_package_name(self, pkg):
setattr(settings, 'HEARTBEAT', pkg)
with pytest.raises(ImproperlyConfigured) as e:
build.check(request=None)
msg = 'Missing package_name key from heartbeat configuration'
assert msg in str(e)
def test_prepare_redis(self):
delattr(settings, 'CACHEOPS_REDIS')
HEARTBEAT = {'checkers': ['heartbeat.checkers.redis_status']}
with pytest.raises(ImproperlyConfigured) as e:
heartbeat_settings.prepare_redis(HEARTBEAT)
assert 'Missing CACHEOPS_REDIS in project settings' in str(e)
def test_missing_auth_configuration(self):
self.heartbeat.pop('auth')
with pytest.raises(ImproperlyConfigured) as e:
request = self.factory.get(reverse('1337'))
details(request)
msg = 'Missing auth configuration for heartbeat'
assert msg == str(e.value)
def test_missing_auth_credentials(self):
self.heartbeat['auth'] = {'blow': 'fish'}
with pytest.raises(ImproperlyConfigured) as e:
request = self.factory.get(reverse('1337'))
details(request)
msg = ('Username or password missing from auth configuration '
'for heartbeat')
assert msg == str(e.value)
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key from heartbeat configuration')
sys_path_distros = WorkingSet()
package_req = Requirement.parse(package_name)
distro = sys_path_distros.find(package_req)
if not distro:
return dict(error='no distribution found for {}'.format(package_name))
return dict(name=distro.project_name, version=distro.version)
def prepare_credentials(auth):
if not all([auth.get('username'), auth.get('password')]):
raise ImproperlyConfigured(
'Username or password missing from auth configuration '
'for heartbeat')
def prepare_redis(heartbeat):
if 'heartbeat.checkers.redis_status' in heartbeat['checkers']:
redis = getattr(settings, 'CACHEOPS_REDIS', None)
if redis is None:
raise ImproperlyConfigured(
'Missing CACHEOPS_REDIS in project settings')
def plugin(self):
"""
Returns (instance, plugin) for the source plugin if found, else 404.
"""
try:
plugin_id = int(self.kwargs.get('plugin_id'))
cms_plugin_instance = CMSPlugin.objects.get(pk=plugin_id)
except (KeyError, TypeError, CMSPlugin.DoesNotExist):
raise ImproperlyConfigured('Source form plugin not found.')
return cms_plugin_instance.get_plugin_instance()