本文整理汇总了Python中pyramid.util.DottedNameResolver类的典型用法代码示例。如果您正苦于以下问题:Python DottedNameResolver类的具体用法?Python DottedNameResolver怎么用?Python DottedNameResolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DottedNameResolver类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: disqus_comments_view
def disqus_comments_view(context, request):
settings = get_settings_util()
available = settings.get('kotti_disqus-disqus_available_types', [])
available += get_settings()['kotti_disqus.extra_types'].split()
resolver = DottedNameResolver(None)
types = tuple(resolver.resolve(typ) for typ in available)
if not isinstance(context, types):
raise PredicateMismatch()
api = template_api(context, request)
disqus_url = ''
disqus_shortname = settings['kotti_disqus-disqus_shortname']
base_url = settings['kotti_disqus-disqus_base_url'].strip('/')
if base_url:
disqus_url = base_url + api.url(context)[len(request.application_url):]
else:
disqus_url = api.url(context)
return {
'disqus_shortname': disqus_shortname,
'disqus_url': disqus_url,
}
示例2: check_password
def check_password(cls, **kwargs):
if kwargs.has_key('id'):
user = cls.get_by_id(kwargs['id'])
if kwargs.has_key('login'):
user = cls.get_by_login(kwargs['login'])
request = get_current_request()
use_sha256 = asbool(request.registry.settings.get('apex.use_sha256'))
if not user:
return False
try:
if use_sha256:
pw = kwargs['password']
if CRYPTPasswordManager(SHA256CRYPT).check(user.password, pw):
return True
else:
pw = kwargs['password'] + user.salt
if BCRYPTPasswordManager().check(user.password, pw):
return True
except TypeError:
pass
fallback_auth = request.registry.settings.get('apex.fallback_auth')
if fallback_auth:
resolver = DottedNameResolver(fallback_auth.split('.', 1)[0])
fallback = resolver.resolve(fallback_auth)
pw = kwargs['password']
return fallback().check(DBSession, request, user, pw)
return False
示例3: get_storage_factory
def get_storage_factory(settings, prefix='filestore'):
"""Uses a Pyramid deployment settings dictionary to construct and return
an instance of a :class:`FileStorage` subclass.
The `prefix` will be used to extract storage configuration. The package to
use is determined by the `$prefix` config setting, and any setting named
`$prefix.$key` will be passed to the subclass constructor as `$key`.
The `$prefix` config setting may be either the full dotted python name of a
data manager class, or the name of one of the modules in the
floof.model.filestore namespace, currently `local` or `mogilefs`.
"""
# Pull prefix.key out of the config object
kwargs = {}
plen = len(prefix)
for key, val in settings.iteritems():
if key[0:plen] == prefix and len(key) > plen:
kwargs[ key[plen+1:] ] = val
# Resolve the data manager
resolver = DottedNameResolver(None)
manager = settings[prefix]
name = 'floof.model.filestore.' + manager + '.FileStorage'
try:
storage = resolver.resolve(name)
except ImportError:
storage = resolver.resolve(manager)
def storage_factory():
"""Returns an instance of the chosen data manager for attachement to a
request object and use over the life of a single request. The instance
must be manually joined to a Zope-style transaction."""
return storage(transaction.manager, **kwargs)
return storage_factory
示例4: create_mailer
def create_mailer(registry: Registry) -> IMailer:
"""Create a new mailer instance.
"""
settings = registry.settings
# Empty values are not handled gracefully, so mutate them here before passing forward to mailer
if settings.get("mail.username", "x") == "":
settings["mail.username"] = None
if settings.get("mail.password", "x") == "":
settings["mail.password"] = None
mailer_class = settings.get("websauna.mailer", "")
if mailer_class in ("mail", ""):
# TODO: Make mailer_class explicit so we can dynamically load pyramid_mail.Mailer
# Default
from pyramid_mailer import mailer_factory_from_settings
mailer = mailer_factory_from_settings(settings)
else:
# debug backend
resolver = DottedNameResolver()
mailer_cls = resolver.resolve(mailer_class)
mailer = mailer_cls()
return mailer
示例5: get_profile
def get_profile(self, request=None):
"""
Returns AuthUser.profile object, creates record if it doesn't exist.
.. code-block:: python
from apex.models import AuthUser
user = AuthUser.get_by_id(1)
profile = user.get_profile(request)
in **development.ini**
.. code-block:: python
apex.auth_profile =
"""
if not request:
request = get_current_request()
auth_profile = request.registry.settings.get('apex.auth_profile')
if auth_profile:
resolver = DottedNameResolver(auth_profile.split('.')[0])
profile_cls = resolver.resolve(auth_profile)
return get_or_create(DBSession, profile_cls, auth_id=self.id)
示例6: check_password
def check_password(cls, **kwargs):
if 'id' in kwargs:
user = cls.get_by_id(kwargs['id'])
if 'login' in kwargs:
user = cls.get_by_login(kwargs['login'])
if not user:
return False
try:
if BCRYPTPasswordManager().check(user.password,
'%s%s' % (kwargs['password'],
user.salt)):
return True
except TypeError:
pass
request = get_current_request()
fallback_auth = request.registry.settings.get('apex.fallback_auth')
if fallback_auth:
resolver = DottedNameResolver(fallback_auth.split('.', 1)[0])
fallback = resolver.resolve(fallback_auth)
return fallback().check(DBSession, request, user,
kwargs['password'])
return False
示例7: base_config
def base_config(**settings):
from pyramid.authorization import ACLAuthorizationPolicy
resolver = DottedNameResolver()
setup_defaults(settings)
authn_policy = resolver.maybe_resolve(settings['arche.authn_factory'])(settings)
authz_policy = ACLAuthorizationPolicy()
return Configurator(root_factory = root_factory,
settings = settings,
authentication_policy = authn_policy,
authorization_policy = authz_policy,)
示例8: renderer_factory
def renderer_factory(info):
path = info.name
registry = info.registry
settings = info.settings
lookup = registry.queryUtility(IMakoLookup)
if lookup is None:
reload_templates = settings.get('reload_templates', False)
directories = settings.get('mako.directories', None)
module_directory = settings.get('mako.module_directory', None)
input_encoding = settings.get('mako.input_encoding', 'utf-8')
error_handler = settings.get('mako.error_handler', None)
default_filters = settings.get('mako.default_filters', 'h')
imports = settings.get('mako.imports', None)
strict_undefined = settings.get('mako.strict_undefined', 'false')
preprocessor = settings.get('mako.preprocessor', None)
if directories is None:
raise ConfigurationError(
'Mako template used without a ``mako.directories`` setting')
if not is_nonstr_iter(directories):
directories = list(filter(None, directories.splitlines()))
directories = [ abspath_from_asset_spec(d) for d in directories ]
if module_directory is not None:
module_directory = abspath_from_asset_spec(module_directory)
if error_handler is not None:
dotted = DottedNameResolver(info.package)
error_handler = dotted.maybe_resolve(error_handler)
if default_filters is not None:
if not is_nonstr_iter(default_filters):
default_filters = list(filter(
None, default_filters.splitlines()))
if imports is not None:
if not is_nonstr_iter(imports):
imports = list(filter(None, imports.splitlines()))
strict_undefined = asbool(strict_undefined)
if preprocessor is not None:
dotted = DottedNameResolver(info.package)
preprocessor = dotted.maybe_resolve(preprocessor)
lookup = PkgResourceTemplateLookup(directories=directories,
module_directory=module_directory,
input_encoding=input_encoding,
error_handler=error_handler,
default_filters=default_filters,
imports=imports,
filesystem_checks=reload_templates,
strict_undefined=strict_undefined,
preprocessor=preprocessor)
registry_lock.acquire()
try:
registry.registerUtility(lookup, IMakoLookup)
finally:
registry_lock.release()
return MakoLookupTemplateRenderer(path, lookup)
示例9: includeme
def includeme(config):
resolver = DottedNameResolver()
service_name = config.registry.settings.get("sms.service")
if not service_name:
raise SMSConfigurationError("sms.service setting missing")
service_cls = resolver.resolve(service_name)
if not service_cls:
raise SMSConfigurationError("Not a valid sms.service: {}".format(service_name))
config.registry.registerAdapter(factory=service_cls, required=(IRequest,), provided=ISMSService)
示例10: pshell_file_config
def pshell_file_config(self, filename):
resolver = DottedNameResolver(None)
self.loaded_objects = {}
self.object_help = {}
config = self.ConfigParser()
config.read(filename)
try:
items = config.items('pshell')
except ConfigParser.NoSectionError:
return
for k, v in items:
self.loaded_objects[k] = resolver.maybe_resolve(v)
self.object_help[k] = v
示例11: includeme
def includeme(config):
"""
Pyramid entry point
"""
settings = config.registry.settings
config.add_tween('rollbar.contrib.pyramid.rollbar_tween_factory', under=EXCVIEW)
# run patch_debugtoolbar, unless they disabled it
if asbool(settings.get('rollbar.patch_debugtoolbar', True)):
patch_debugtoolbar(settings)
def hook(request, data):
data['framework'] = 'pyramid'
if request:
request.environ['rollbar.uuid'] = data['uuid']
if request.matched_route:
data['context'] = request.matched_route.name
rollbar.BASE_DATA_HOOK = hook
kw = parse_settings(settings)
access_token = kw.pop('access_token')
environment = kw.pop('environment', 'production')
if kw.get('scrub_fields'):
kw['scrub_fields'] = set([str.strip(x) for x in kw.get('scrub_fields').split('\n') if x])
if kw.get('exception_level_filters'):
r = DottedNameResolver()
exception_level_filters = []
for line in kw.get('exception_level_filters').split('\n'):
if line:
dotted_path, level = line.split()
try:
cls = r.resolve(dotted_path)
exception_level_filters.append((cls, level))
except ImportError:
log.error('Could not import %r' % dotted_path)
kw['exception_level_filters'] = exception_level_filters
kw['enabled'] = asbool(kw.get('enabled', True))
rollbar.init(access_token, environment, **kw)
示例12: _find_methods
def _find_methods(worker):
cronjobsentry = worker.app.registry.settings.get('cronjobs')
if cronjobsentry is None:
raise ValueError("cronjobs must exist in application configuration if you want to run this. "
"It should point to methods that can be run by the crontick worker. "
"See voteit.core.scripts.crontick")
resolver = DottedNameResolver(None)
dotteds = [x.strip() for x in cronjobsentry.strip().splitlines()]
methods = []
for dotted in dotteds:
try:
methods.append(resolver.resolve(dotted))
except ImportError, e:
worker.logger.exception(e)
示例13: pshell_file_config
def pshell_file_config(self, loader, defaults):
settings = loader.get_settings('pshell', defaults)
resolver = DottedNameResolver(None)
self.loaded_objects = {}
self.object_help = {}
self.setup = None
for k, v in settings.items():
if k == 'setup':
self.setup = v
elif k == 'default_shell':
self.preferred_shells = [x.lower() for x in aslist(v)]
elif k in ('__file__', 'here'):
continue
else:
self.loaded_objects[k] = resolver.maybe_resolve(v)
self.object_help[k] = v
示例14: __init__
def __init__(self,
app_router: Router,
rest_url: str='http://localhost',
base_path: str='/',
header: dict=None,
user_path: str='',
user_login: str='',
user_password: str='',
):
"""Initialize self."""
self.app_router = app_router
"""The adhocracy wsgi application"""
self.app = TestApp(app_router)
""":class:`webtest.TestApp`to send requests to the backend server."""
self.rest_url = rest_url
"""backend server url to generate request urls."""
self.base_path = base_path
"""path prefix to generate request urls."""
self.header = header or {}
"""default header for requests, mostly for authentication.
If not set, `user_login` and `user_password` is used to login,
the new authentication header is stored in `header`.
"""
if user_password and user_login and not header:
token, user_path = self._get_token_and_user_path(user_login,
user_password)
self.header = {UserTokenHeader: token}
self.user_password = user_password
"""password for authenticated user."""
self.user_login = user_login
"""login name for authenticated user."""
self.user_path = user_path
"""path for authenticated user."""
self._resolver = DottedNameResolver()
示例15: pshell_file_config
def pshell_file_config(self, filename):
config = self.ConfigParser()
config.read(filename)
try:
items = config.items("pshell")
except configparser.NoSectionError:
return
resolver = DottedNameResolver(None)
self.loaded_objects = {}
self.object_help = {}
self.setup = None
for k, v in items:
if k == "setup":
self.setup = v
else:
self.loaded_objects[k] = resolver.maybe_resolve(v)
self.object_help[k] = v