当前位置: 首页>>代码示例>>Python>>正文


Python module_loading.import_string方法代码示例

本文整理汇总了Python中django.utils.module_loading.import_string方法的典型用法代码示例。如果您正苦于以下问题:Python module_loading.import_string方法的具体用法?Python module_loading.import_string怎么用?Python module_loading.import_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.module_loading的用法示例。


在下文中一共展示了module_loading.import_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_access_token_jwt

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:26,代码来源:views.py

示例2: _get_check_functions

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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 
开发者ID:mvantellingen,项目名称:django-healthchecks,代码行数:27,代码来源:checker.py

示例3: test_send_bulk_sms

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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),
            ]
        ) 
开发者ID:CuriousLearner,项目名称:django-phone-verify,代码行数:22,代码来源:test_backends.py

示例4: configure_logging

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:log.py

示例5: __getitem__

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:utils.py

示例6: __init__

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:20,代码来源:jinja2.py

示例7: process_rule

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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) 
开发者ID:ramonsaraiva,项目名称:django-expiry,代码行数:18,代码来源:rules.py

示例8: test_model_fields

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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",
            ],
        ) 
开发者ID:edoburu,项目名称:sphinxcontrib-django,代码行数:18,代码来源:test_docstrings.py

示例9: redirect_to_sudo

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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)) 
开发者ID:mattrobenolt,项目名称:django-sudo,代码行数:23,代码来源:views.py

示例10: is_refreshable_url

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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
        ) 
开发者ID:mozilla,项目名称:mozilla-django-oidc,代码行数:23,代码来源:middleware.py

示例11: listdir

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
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'
            ) 
开发者ID:marazmiki,项目名称:django-webdav-storage,代码行数:23,代码来源:storage.py

示例12: get_sms_backend

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
def get_sms_backend(phone_number):
    if not backend:

        if settings.PHONE_VERIFICATION.get("BACKEND", None):
            backend_import = settings.PHONE_VERIFICATION["BACKEND"]
        else:
            raise ImproperlyConfigured(
                "Please specify BACKEND in PHONE_VERIFICATION within your settings"
            )

        backend_cls = import_string(backend_import)
        return backend_cls(**settings.PHONE_VERIFICATION["OPTIONS"]) 
开发者ID:CuriousLearner,项目名称:django-phone-verify,代码行数:14,代码来源:__init__.py

示例13: get_sparql_providers

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
def get_sparql_providers(endpoint=None):
    sparql_providers = {}
    for provider in settings.SPARQL_ENDPOINT_PROVIDERS:
        Provider = import_string(provider["SPARQL_ENDPOINT_PROVIDER"])()
        sparql_providers[Provider.endpoint] = Provider

    if endpoint:
        return sparql_providers[endpoint]
    else:
        return sparql_providers 
开发者ID:archesproject,项目名称:arches,代码行数:12,代码来源:concept.py

示例14: install

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
def install(self, package_name):
        """
        Runs the setup.py file found in the package root

        """

        install = import_string("%s.setup.install" % package_name)
        install() 
开发者ID:archesproject,项目名称:arches,代码行数:10,代码来源:packages.py

示例15: resend

# 需要导入模块: from django.utils import module_loading [as 别名]
# 或者: from django.utils.module_loading import import_string [as 别名]
def resend(self):
        """
        Re-sends the notification by calling the notification class' resend method
        """

        notification_class = import_string(self.notification_class)
        notification_class.resend(self) 
开发者ID:worthwhile,项目名称:django-herald,代码行数:9,代码来源:models.py


注:本文中的django.utils.module_loading.import_string方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。