本文整理匯總了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
示例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
示例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),
]
)
示例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)
示例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
示例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)
示例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)
示例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",
],
)
示例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))
示例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
)
示例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'
)
示例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"])
示例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
示例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()
示例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)