Python django.utils.module_loading.import_string() Examples
The following are 30
code examples of django.utils.module_loading.import_string().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.module_loading
, or try the search function
.
Example #1
Source File: utils.py From bioforum with MIT License | 6 votes |
def __getitem__(self, alias): try: return self._engines[alias] except KeyError: try: params = self.templates[alias] except KeyError: raise InvalidTemplateEngineError( "Could not find config for '{}' " "in settings.TEMPLATES".format(alias)) # If importing or initializing the backend raises an exception, # self._engines[alias] isn't set and this code may get executed # again, so we must preserve the original params. See #24265. params = params.copy() backend = params.pop('BACKEND') engine_cls = import_string(backend) engine = engine_cls(params) self._engines[alias] = engine return engine
Example #2
Source File: views.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
def _get_access_token_jwt(self, request, content): extra_data = {} issuer = settings.JWT_ISSUER payload_enricher = getattr(settings, 'JWT_PAYLOAD_ENRICHER', None) if payload_enricher: fn = import_string(payload_enricher) extra_data = fn(request) if 'scope' in content: extra_data['scope'] = content['scope'] id_attribute = getattr(settings, 'JWT_ID_ATTRIBUTE', None) if id_attribute: token = get_access_token_model().objects.get( token=content['access_token'] ) id_value = getattr(token.user, id_attribute, None) if not id_value: raise MissingIdAttribute() extra_data[id_attribute] = str(id_value) payload = generate_payload(issuer, content['expires_in'], **extra_data) token = encode_jwt(payload) return token
Example #3
Source File: test_backends.py From django-phone-verify with GNU General Public License v3.0 | 6 votes |
def test_send_bulk_sms(client, mocker, backend): with override_settings(PHONE_VERIFICATION=backend): backend_import = settings.PHONE_VERIFICATION["BACKEND"] backend_cls = import_string(backend_import) cls_obj = backend_cls(**settings.PHONE_VERIFICATION["OPTIONS"]) mock_send_sms = mocker.patch(f"{backend_import}.send_sms") numbers = ["+13478379634", "+13478379633", "+13478379632"] message = "Fake message" cls_obj.send_bulk_sms(numbers, message) assert mock_send_sms.called assert mock_send_sms.call_count == 3 mock_send_sms.assert_has_calls( [ mocker.call(number=numbers[0], message=message), mocker.call(number=numbers[1], message=message), mocker.call(number=numbers[2], message=message), ] )
Example #4
Source File: storage.py From django-webdav-storage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def listdir(self, path): if not self.listing_backend: raise NotImplementedError( 'Listing backend not configured. Please set ' 'the WEBDAV_LISTING_BACKEND option in your settings module ' 'or pass the "listing_backend" keyword argument to the ' 'storage constructor' ) try: return import_string(self.listing_backend)(self, path) except ImportError: raise NotImplementedError( 'Unable import the listing backend ' 'as a {0}'.format(self.listing_backend) ) except TypeError: raise NotImplementedError( 'Wrong number of arguments. A listing backend should accept ' 'two args: 1) a storage instance, 2) requested path' )
Example #5
Source File: checker.py From django-healthchecks with MIT License | 6 votes |
def _get_check_functions(name=None, request=None): checks = _get_registered_health_checks() if not checks or (name and name not in checks): raise StopIteration() checks = _filter_checks_on_permission(request, checks) if not checks or (name and name not in checks): raise PermissionDenied() for service, func_string in checks.items(): if name and name != service: continue if callable(func_string): check_func = func_string elif func_string.startswith(('https://', 'http://')): check_func = _http_healthcheck_func(func_string) else: check_func = import_string(func_string) spec = inspect.getargspec(check_func) if spec.args == ['request']: check_func = functools.partial(check_func, request) yield service, check_func
Example #6
Source File: middleware.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
def is_refreshable_url(self, request): """Takes a request and returns whether it triggers a refresh examination :arg HttpRequest request: :returns: boolean """ # Do not attempt to refresh the session if the OIDC backend is not used backend_session = request.session.get(BACKEND_SESSION_KEY) is_oidc_enabled = True if backend_session: auth_backend = import_string(backend_session) is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend) return ( request.method == 'GET' and request.user.is_authenticated and is_oidc_enabled and request.path not in self.exempt_urls )
Example #7
Source File: log.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def configure_logging(logging_config, logging_settings): if not sys.warnoptions: # Route warnings through python logging logging.captureWarnings(True) # RemovedInNextVersionWarning is a subclass of DeprecationWarning which # is hidden by default, hence we force the "default" behavior warnings.simplefilter("default", RemovedInNextVersionWarning) if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings)
Example #8
Source File: utils.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def __getitem__(self, alias): try: return self._engines[alias] except KeyError: try: params = self.templates[alias] except KeyError: raise InvalidTemplateEngineError( "Could not find config for '{}' " "in settings.TEMPLATES".format(alias)) # If importing or initializing the backend raises an exception, # self._engines[alias] isn't set and this code may get executed # again, so we must preserve the original params. See #24265. params = params.copy() backend = params.pop('BACKEND') engine_cls = import_string(backend) engine = engine_cls(params) self._engines[alias] = engine return engine
Example #9
Source File: views.py From django-sudo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def redirect_to_sudo(next_url, sudo_url=None): """ Redirects the user to the login page, passing the given 'next' page """ if sudo_url is None: sudo_url = URL try: # django 1.10 and greater can't resolve the string 'sudo.views.sudo' to a URL # https://docs.djangoproject.com/en/1.10/releases/1.10/#removed-features-1-10 sudo_url = import_string(sudo_url) except (ImportError, ImproperlyConfigured): pass # wasn't a dotted path sudo_url_parts = list(urlparse(resolve_url(sudo_url))) querystring = QueryDict(sudo_url_parts[4], mutable=True) querystring[REDIRECT_FIELD_NAME] = next_url sudo_url_parts[4] = querystring.urlencode(safe="/") return HttpResponseRedirect(urlunparse(sudo_url_parts))
Example #10
Source File: test_docstrings.py From sphinxcontrib-django with Apache License 2.0 | 6 votes |
def test_model_fields(self): lines = [] simple_model_path = 'sphinxcontrib_django.tests.test_docstrings.SimpleModel' if django.VERSION < (3, 0): obj = DeferredAttribute(field_name='dummy_field', model=simple_model_path) else: model = import_string(simple_model_path) obj = DeferredAttribute(field=model._meta.get_field('dummy_field')) docstrings._improve_attribute_docs(obj, '{}.dummy_field'.format(simple_model_path), lines) self.assertEqual( lines, [ "**Model field:** dummy field", ], )
Example #11
Source File: rules.py From django-expiry with MIT License | 6 votes |
def process_rule(rule, **kwargs): """ Processes a rule. Returns `True` if the rule is valid. When the rule is not a callable, tries importing it, assuming it is a function defined in a specific module of the application. Anonymous rules don't contain an user, so we extract it when calling the rule for validation. """ if not callable(rule): rule = import_string(rule) request = kwargs.pop('request') user = kwargs.pop('user', None) return rule(request, user) if user.is_authenticated else rule(request)
Example #12
Source File: jinja2.py From bioforum with MIT License | 6 votes |
def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super().__init__(params) self.context_processors = options.pop('context_processors', []) environment = options.pop('environment', 'jinja2.Environment') environment_cls = import_string(environment) if 'loader' not in options: options['loader'] = jinja2.FileSystemLoader(self.template_dirs) options.setdefault('autoescape', True) options.setdefault('auto_reload', settings.DEBUG) options.setdefault('undefined', jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined) self.env = environment_cls(**options)
Example #13
Source File: auth.py From mozilla-django-oidc with Mozilla Public License 2.0 | 5 votes |
def get_username(self, claims): """Generate username based on claims.""" # bluntly stolen from django-browserid # https://github.com/mozilla/django-browserid/blob/master/django_browserid/auth.py username_algo = self.get_settings('OIDC_USERNAME_ALGO', None) if username_algo: if isinstance(username_algo, six.string_types): username_algo = import_string(username_algo) return username_algo(claims.get('email')) return default_username_algo(claims.get('email'))
Example #14
Source File: utils.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 5 votes |
def get_included_serializers(serializer): included_serializers = copy.copy(getattr(serializer, 'included_serializers', dict())) for name, value in iter(included_serializers.items()): if not isinstance(value, type): if value == 'self': included_serializers[name] = ( serializer if isinstance(serializer, type) else serializer.__class__ ) else: included_serializers[name] = import_class_from_dotted_path(value) return included_serializers
Example #15
Source File: password_validation.py From bioforum with MIT License | 5 votes |
def get_password_validators(validator_config): validators = [] for validator in validator_config: try: klass = import_string(validator['NAME']) except ImportError: msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting." raise ImproperlyConfigured(msg % validator['NAME']) validators.append(klass(**validator.get('OPTIONS', {}))) return validators
Example #16
Source File: __init__.py From bioforum with MIT License | 5 votes |
def load_backend(path): return import_string(path)()
Example #17
Source File: finders.py From bioforum with MIT License | 5 votes |
def get_finder(import_path): """ Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder)) return Finder()
Example #18
Source File: base.py From bioforum with MIT License | 5 votes |
def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False self.serializer = import_string(settings.SESSION_SERIALIZER)
Example #19
Source File: selenium.py From bioforum with MIT License | 5 votes |
def import_webdriver(cls, browser): return import_string("selenium.webdriver.%s.webdriver.WebDriver" % browser)
Example #20
Source File: integrations.py From zulip with Apache License 2.0 | 5 votes |
def __init__(self, name: str, categories: List[str], client_name: Optional[str]=None, logo: Optional[str]=None, secondary_line_text: Optional[str]=None, function: Optional[str]=None, url: Optional[str]=None, display_name: Optional[str]=None, doc: Optional[str]=None, stream_name: Optional[str]=None, legacy: bool=False, config_options: Sequence[Tuple[str, str, Validator[object]]]=[]) -> None: if client_name is None: client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title()) super().__init__( name, client_name, categories, logo=logo, secondary_line_text=secondary_line_text, display_name=display_name, stream_name=stream_name, legacy=legacy, config_options=config_options, ) if function is None: function = self.DEFAULT_FUNCTION_PATH.format(name=name) if isinstance(function, str): function = import_string(function) self.function = function if url is None: url = self.DEFAULT_URL.format(name=name) self.url = url if doc is None: doc = self.DEFAULT_DOC_PATH.format(name=name, ext='md') self.doc = doc
Example #21
Source File: jinja2.py From bioforum with MIT License | 5 votes |
def template_context_processors(self): return [import_string(path) for path in self.context_processors]
Example #22
Source File: base.py From django-ra-erp with GNU Affero General Public License v3.0 | 5 votes |
def get_report_list_class(request, base_model): from ra.base.app_settings import RA_REPORT_LIST_MAP from ra.reporting.views import ReportList klass = RA_REPORT_LIST_MAP.get(base_model, False) if klass: klass = import_string(klass) if callable(klass): return klass(request, base_model=base_model) else: klass = ReportList return klass.as_view()(request, base_model=base_model)
Example #23
Source File: engine.py From bioforum with MIT License | 5 votes |
def find_template_loader(self, loader): if isinstance(loader, (tuple, list)): args = list(loader[1:]) loader = loader[0] else: args = [] if isinstance(loader, str): loader_class = import_string(loader) return loader_class(self, *args) else: raise ImproperlyConfigured( "Invalid value in template loaders configuration: %r" % loader)
Example #24
Source File: utils.py From bioforum with MIT License | 5 votes |
def routers(self): if self._routers is None: self._routers = settings.DATABASE_ROUTERS routers = [] for r in self._routers: if isinstance(r, str): router = import_string(r)() else: router = r routers.append(router) return routers
Example #25
Source File: state.py From bioforum with MIT License | 5 votes |
def construct_managers(self): """Deep-clone the managers using deconstruction.""" # Sort all managers by their creation counter sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter) for mgr_name, manager in sorted_managers: as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct() if as_manager: qs_class = import_string(qs_path) yield mgr_name, qs_class.as_manager() else: manager_class = import_string(manager_path) yield mgr_name, manager_class(*args, **kwargs)
Example #26
Source File: log.py From bioforum with MIT License | 5 votes |
def configure_logging(logging_config, logging_settings): if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) logging.config.dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings)
Example #27
Source File: renderers.py From bioforum with MIT License | 5 votes |
def get_default_renderer(): renderer_class = import_string(settings.FORM_RENDERER) return renderer_class()
Example #28
Source File: debug.py From bioforum with MIT License | 5 votes |
def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)()
Example #29
Source File: osoite.py From linkedevents with MIT License | 5 votes |
def pk_get(self, resource_name, res_id=None): # support all munigeo resources, not just addresses Klass = import_string('munigeo.models.' + resource_name) if res_id is not None: return Klass.objects.get(origin_id=res_id) return Klass.objects.all()
Example #30
Source File: transforms.py From waliki with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_transforms(self): transforms = [import_string(transform) for transform in WALIKI_RST_TRANSFORMS] return Reader.get_transforms(self) + transforms