本文整理汇总了Python中pyramid.path.DottedNameResolver.resolve方法的典型用法代码示例。如果您正苦于以下问题:Python DottedNameResolver.resolve方法的具体用法?Python DottedNameResolver.resolve怎么用?Python DottedNameResolver.resolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.path.DottedNameResolver
的用法示例。
在下文中一共展示了DottedNameResolver.resolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse_settings
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def _parse_settings(settings):
rawes_args = {}
defaults = {
'url': 'http://localhost:9200',
'timeout': 30,
'path': '',
'json_encoder': encode_date_optional_time,
}
rawes_args = defaults.copy()
# set string settings
for short_key_name in ('path',):
key_name = 'rawes.%s' % (short_key_name,)
if key_name in settings:
rawes_args[short_key_name] = \
settings.get(key_name, defaults.get(short_key_name))
# set list settings
for short_key_name in ('url',):
key_name = 'rawes.%s' % (short_key_name,)
if key_name in settings:
rawes_args[short_key_name] = \
(aslist(settings.get(key_name, defaults.get(short_key_name)))
if len(aslist(settings.get(key_name, defaults.get(short_key_name)))) > 1
else settings.get(key_name, defaults.get(short_key_name)).strip())
# integer settings
for short_key_name in ('timeout',):
key_name = 'rawes.%s' % (short_key_name,)
if key_name in settings:
rawes_args[short_key_name] = \
int(settings.get(key_name, defaults.get(short_key_name)))
# function settings
for short_key_name in ('json_encoder',):
key_name = 'rawes.%s' % (short_key_name,)
r = DottedNameResolver()
if key_name in settings:
rawes_args[short_key_name] = \
r.resolve(settings.get(key_name))
for short_key_name in ('json_decoder',):
key_name = 'rawes.%s' % (short_key_name,)
r = DottedNameResolver()
if key_name in settings:
rawes_args[short_key_name] = \
r.resolve(settings.get(key_name))().decode
# removed settings
for short_key_name in ('connection_type', 'except_on_error'):
key_name = 'rawes.%s' % (short_key_name,)
if key_name in settings:
warnings.warn(
'%s is no longer supported, please remove from your settings.',
UserWarning
)
return rawes_args
示例2: configure_task
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def configure_task(task_name):
global _config
config = _config[task_name]
tc = util.prefixed_keys(config, 'kombu.')
tc.update(util.prefixed_keys(config, 'task.'))
resolver = DottedNameResolver()
cls = resolver.resolve(tc['class'])
if 'queues' in tc:
tc['queues'] = dict(
(k, get_queue(q)) for k, q in util.as_dict(tc['queues']).items())
else:
tc['exchanges'] = {}
if 'exchanges' in tc:
tc['exchanges'] = dict(
(e, get_exchange(e)) for e in util.as_list(tc['exchanges']))
else:
tc['exchanges'] = {}
if 'schedule' in tc:
tc['schedule'] = _parse_schedule(util.as_dict(tc['schedule']))
if 'rate' in tc:
tc['rate'] = {
'rate': float(tc['rate'].strip()),
'capacity': float(tc['capacity'])
}
cls.configure(**tc)
return cls
示例3: debug
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def debug(request, registry, settings):
"""Invoke pdb breakpoint from a template.
Example:
.. code-block:: html+jinja
<h1>{{ site_name }}</h1>
{{ debug() }}
This will invoke function from :ref:`websauna.template_debugger` setting. The debugger is turned on only on :ref:`development.ini`. If there is no debugger configured, a warning is given.
"""
def _dummy():
logger.warn("{{ debug() }} invoked, but websauna.template_debugger not set")
return ""
template_debugger = settings.get("websauna.template_debugger")
if not template_debugger:
debugger = _dummy
else:
r = DottedNameResolver()
debugger = r.resolve(template_debugger)
def _inner():
debugger()
return ""
return _inner
示例4: debug
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def debug(request, registry, settings):
"""Invoke pdb breakpoint from a template.
Example:
.. code-block:: html+jinja
<h1>{{ site_name }}</h1>
{{ debug() }}
This will invoke function from :ref:`websauna.template_debugger` setting. The debugger is turned on only on :ref:`development.ini`. If there is no debugger configured, nothing happens.
"""
def _dummy():
return ""
template_debugger = settings.get("websauna.template_debugger")
if not template_debugger:
return _dummy()
r = DottedNameResolver()
debugger = r.resolve(template_debugger)
assert debugger, "Could not find debugger in websauna.template_debugger setting: {}".format(template_debugger)
def _inner():
debugger()
return ""
return _inner
示例5: configure_mailer
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def configure_mailer(self, settings):
"""Configure outgoing email backend based on the INI settings."""
settings = settings.copy()
# 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)
self.config.registry.registerUtility(mailer, IMailer)
else:
# debug backend
resolver = DottedNameResolver()
mailer_cls = resolver.resolve(mailer_class)
mailer = mailer_cls()
self.config.registry.registerUtility(mailer, IMailer)
示例6: get_init
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def get_init(global_config, settings, init_cls=None) -> Initializer:
"""Get Initializer class instance for WSGI-like app.
TODO: Deprecated. Use Pyramid's ``bootstrap()`` instead.
Reads reference to the initializer from settings, resolves it and creates the initializer instance.
Example 1::
config_uri = argv[1]
init = get_init(dict(__file__=config_uri), settings)
:param global_config: Global config dictionary, having __file__ entry as given by Paster
:param settings: Settings dictionary
:param init_cls: Explicitly give the Initializer class to use, otherwise read ``websauna.init`` settings.
"""
assert "websauna.init" in settings, "You must have websauna.init setting pointing to your Initializer class"
assert "__file__" in global_config
if not init_cls:
init_cls = settings.get("websauna.init")
if not init_cls:
raise RuntimeError("INI file lacks websauna.init option")
resolver = DottedNameResolver()
init_cls = resolver.resolve(init_cls)
init = init_cls(global_config, settings)
return init
示例7: includeme
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def includeme(config):
"""Bind to the db engine specifed in ``config.registry.settings``.
Setup::
>>> from mock import Mock
>>> import pyramid_basemodel
>>> _engine_from_config = pyramid_basemodel.engine_from_config
>>> _bind_engine = pyramid_basemodel.bind_engine
>>> pyramid_basemodel.engine_from_config = Mock()
>>> pyramid_basemodel.engine_from_config.return_value = 'engine'
>>> pyramid_basemodel.bind_engine = Mock()
>>> mock_config = Mock()
>>> mock_config.registry.settings = {}
Calls ``bind_engine`` with the configured ``engine``::
>>> includeme(mock_config)
>>>
>>> mock_config.action.assert_called_with(None,
... pyramid_basemodel.bind_engine,
... ('engine',),
... {'should_create': False, 'should_drop': False})
Unless told not to::
>>> pyramid_basemodel.bind_engine = Mock()
>>> mock_config = Mock()
>>> mock_config.registry.settings = {'basemodel.should_bind_engine': False}
>>> includeme(mock_config)
>>> mock_config.action.called
False
Teardown::
>>> pyramid_basemodel.engine_from_config = _engine_from_config
>>> pyramid_basemodel.bind_engine = _bind_engine
"""
# Bind the engine.
settings = config.get_settings()
engine_kwargs_factory = settings.pop('sqlalchemy.engine_kwargs_factory', None)
if engine_kwargs_factory:
kwargs_factory = config.maybe_dotted(engine_kwargs_factory)
engine_kwargs = kwargs_factory(config.registry)
else:
engine_kwargs = {}
pool_class = settings.pop('sqlalchemy.pool_class', None)
if pool_class:
dotted_name = DottedNameResolver()
engine_kwargs['poolclass'] = dotted_name.resolve(pool_class)
should_bind = asbool(settings.get('basemodel.should_bind_engine', True))
should_create = asbool(settings.get('basemodel.should_create_all', False))
should_drop = asbool(settings.get('basemodel.should_drop_all', False))
if should_bind:
engine = engine_from_config(settings, 'sqlalchemy.', **engine_kwargs)
config.action(None, bind_engine, (engine,), {
'should_create': should_create,
'should_drop': should_drop})
示例8: configure_mailer
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def configure_mailer(self):
"""Configure outgoing email backend and email test views."""
from pyramid_mailer import IMailer
settings = self.settings.copy()
# 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)
self.config.registry.registerUtility(mailer, IMailer)
else:
# debug backend
resolver = DottedNameResolver()
mailer_cls = resolver.resolve(mailer_class)
mailer = mailer_cls()
self.config.registry.registerUtility(mailer, IMailer)
if settings.get("websauna.sample_html_email", False):
from websauna.system.mail import views
self.config.scan(views)
self.config.add_jinja2_search_path('websauna.system:mail/templates', name='.html')
示例9: includeme
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def includeme(config):
""" Let extdirect be included by config.include(). """
settings = config.registry.settings
extdirect_config = dict()
names = ("api_path", "router_path", "namespace", "descriptor",
"expose_exceptions", "debug_mode", "json_encoder")
for name in names:
qname = "pyramid_extdirect.{}".format(name)
value = settings.get(qname, None)
if name == "expose_exceptions" or name == "debug_mode":
value = (value == "true")
if name == "json_encoder" and value:
from pyramid.path import DottedNameResolver
resolver = DottedNameResolver()
value = resolver.resolve(value)
if value is not None:
extdirect_config[name] = value
extd = Extdirect(**extdirect_config)
config.registry.registerUtility(extd, IExtdirect)
api_view_perm = settings.get("pyramid_extdirect.api_view_permission")
config.add_route('extapi', extd.api_path)
config.add_view(api_view, route_name='extapi', permission=api_view_perm)
router_view_perm = settings.get("pyramid_extdirect.router_view_permission")
config.add_route('extrouter', extd.router_path)
config.add_view(router_view, route_name='extrouter', permission=router_view_perm)
示例10: run
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def run(self):
"""Run the initialization and prepare Pyramid subsystems.
This is the main entry for ramping up a Websauna application.
We go through various subsystem inits.
"""
# TODO: Remove passing settings to methods as an argument
settings = self.settings
self.secrets = self.read_secrets()
self.configure_logging(settings)
# Serving
self.configure_templates()
self.configure_static()
# Forms
self.configure_forms()
self.configure_crud(settings)
# Email
self.configure_mailer(settings)
# Timed tasks
self.configure_scheduler(settings)
self.configure_tasks(settings)
# Core view and layout related
self.configure_root()
self.configure_error_views()
self.configure_views()
self.configure_panels(settings)
self.configure_sitemap(settings)
# Website administration
self.configure_admin(settings)
# Sessions and users
self.configure_sessions(settings, self.secrets)
self.configure_user(settings, self.secrets)
self.configure_model_admins()
self.configure_notebook()
# Configure addons before anything else, so we can override bits from addon, like template lookup paths, later easily
self.configure_addons()
# Database
# This must be run before configure_database() because SQLAlchemy will resolve @declared_attr and we must have config present by then
self.configure_instrumented_models()
self.configure_database()
# Tests can pass us some extra initialization work on ad hoc
extra_init = self.global_config.get("extra_init")
if extra_init:
resolver = DottedNameResolver()
extra_init = resolver.resolve(extra_init)
extra_init(self)
示例11: test_app_no_login_real_policy
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def test_app_no_login_real_policy(request, test_app_no_perm):
"""A configured Assembl fixture with permissions
and no user logged in"""
config = testing.setUp(
registry=test_app_no_perm.app.registry,
settings=get_config(),
)
from ...auth.util import authentication_callback
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.path import DottedNameResolver
resolver = DottedNameResolver(__package__)
auth_policy_name = "assembl.auth.util.UpgradingSessionAuthenticationPolicy"
auth_policy = resolver.resolve(auth_policy_name)(
callback=authentication_callback)
config.set_authorization_policy(ACLAuthorizationPolicy())
config.set_authentication_policy(auth_policy)
import transaction
# ensure default roles and permissions at startup
from ...models import get_session_maker
with transaction.manager:
session = get_session_maker()
from ...lib.migration import bootstrap_db_data
bootstrap_db_data(session, False)
return test_app_no_perm
示例12: command
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def command(self):
ini_file = self.args[-1] # pylint: disable=E1101
# TheLMA setup.
config = self.__setup_thelma(ini_file)
# Initialize the tool and run it.
rsv = DottedNameResolver(None)
tool_cls = rsv.resolve(self.__target_class.tool)
arg_names = [od[1] for od in self.__target_class.option_defs]
# Initializing lazy options. We pass the target class and the
# options so the callback has access to them.
opts = self.options # pylint: disable=E1101
for arg_name in arg_names:
arg_value = getattr(opts, arg_name)
if isinstance(arg_value, LazyOptionCallback):
arg_value = arg_value.initialize(self.__target_class, opts)
setattr(opts, arg_name, arg_value)
# We only now do a final loop over the options so that lazy option
# callbacks get a chance to set dependent option values.
kw = {}
for arg_name in arg_names:
kw[arg_name] = getattr(opts, arg_name)
# Remove options that are for command use only.
for opt in self.parser.option_list:
if opt.dest in kw and opt.pass_to_tool is False:
del kw[opt.dest]
tool = tool_cls(**kw)
try:
tool.run()
except:
transaction.abort()
raise
else:
if tool.has_errors():
err_msgs = tool.get_messages()
msg = 'Errors occurred during the tool run. Error messages:\n'
raise RuntimeError(msg + os.linesep.join(err_msgs))
warn_msgs = tool.get_messages(logging_level=logging.WARNING)
if warn_msgs \
and not self.options.ignore_warnings: # pylint: disable=E1101
msg = 'Warnings occurred during the tool run. You can ' \
'repeat the run with the --ignore-warnings switch ' \
'to force changes to be committed. Warning messages:\n'
raise RuntimeError(msg + os.linesep.join(warn_msgs))
try:
# This gives the tool command a chance to perform actions after
# the tool has run.
self.__target_class.finalize(tool, opts)
except:
transaction.abort()
raise
else:
# Create a report of the run.
self.__run_report(tool)
# All good - check if we should commit.
if not self.options.simulate: # pylint: disable=E1101
transaction.commit()
else:
transaction.abort()
config.end()
示例13: _load_module
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def _load_module(config, package, module):
try:
resolver = DottedNameResolver()
# log.debug('{0}.{1}'.format(package, module))
prefix = resolver.resolve('{0}.{1}:ROUTE_PREFIX'.format(package, module))
except ImportError, e:
prefix = None
示例14: includeme
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def includeme(config):
""" Set up and configure the pypicloud app """
config.set_root_factory(Root)
config.include('pyramid_tm')
config.include('pyramid_beaker')
config.include('pyramid_duh')
config.include('pyramid_duh.auth')
config.include('pypicloud.auth')
config.include('pypicloud.access')
settings = config.get_settings()
config.add_renderer('json', json_renderer)
# Jinja2 configuration
settings['jinja2.filters'] = {
'static_url': 'pyramid_jinja2.filters:static_url_filter',
'tojson': to_json,
}
settings['jinja2.directories'] = ['pypicloud:templates']
config.include('pyramid_jinja2')
# BEAKER CONFIGURATION
settings.setdefault('session.type', 'cookie')
settings.setdefault('session.httponly', 'true')
config.set_session_factory(session_factory_from_settings(settings))
# PYPICLOUD SETTINGS
config.registry.fallback_url = settings.get('pypi.fallback_url',
'http://pypi.python.org/simple')
config.registry.use_fallback = asbool(settings.get('pypi.use_fallback',
True))
realm = settings.get('pypi.realm', 'pypi')
config.registry.realm = realm
# CACHING DATABASE SETTINGS
resolver = DottedNameResolver(__name__)
dotted_cache = settings.get('pypi.db', 'sql')
if dotted_cache == 'sql':
dotted_cache = 'pypicloud.cache.SQLCache'
elif dotted_cache == 'redis':
dotted_cache = 'pypicloud.cache.RedisCache'
cache_impl = resolver.resolve(dotted_cache)
cache_impl.configure(config)
cache_impl.reload_if_needed()
config.add_request_method(cache_impl, name='db', reify=True)
# Special request methods
config.add_request_method(_app_url, name='app_url')
config.add_request_method(lambda x: __version__, name='pypicloud_version',
reify=True)
cache_max_age = int(settings.get('pyramid.cache_max_age', 3600))
config.add_static_view(name='static/%s' % __version__,
path='pypicloud:static',
cache_max_age=cache_max_age)
示例15: parse_asset_settings
# 需要导入模块: from pyramid.path import DottedNameResolver [as 别名]
# 或者: from pyramid.path.DottedNameResolver import resolve [as 别名]
def parse_asset_settings(settings):
config = configparser.SafeConfigParser()
asset_resolver = AssetResolver()
dotted_resolver = DottedNameResolver()
asset_config = settings.get('assets.config')
print asset_config
try:
s = asset_resolver.resolve(asset_config).abspath()
config.read(s)
except AttributeError:
raise
try:
store_locally = config.getboolean('assets', 'store_locally')
except configparser.NoSectionError:
try:
with open(asset_config) as fp:
config.readfp(fp)
except IOError:
raise
else:
store_locally = config.getboolean('assets', 'store_locally')
result = dict(
store_locally=store_locally,
tmp_path=asset_resolver.resolve(config.get('assets', 'tmp_path')).abspath(),
save_path=asset_resolver.resolve(config.get('assets', 'save_path')).abspath()
)
c = config.items('assets:local')
for key, value in c:
# Skip any urls since they don't need to be resolved
# TODO: Might produce bugs if module name starts with `http`
if value.startswith('http'):
result[key] = value
continue
try:
value = asset_resolver.resolve(value).abspath()
except ValueError:
# This gets raised if the name isn't in dotted notation
pass
except ImportError:
# This gets raised if there's ":" in the value but it's not a module
pass
finally:
result[key] = value
if not store_locally:
c = dict(config.items('assets:cloud'))
c['service'] = dotted_resolver.resolve(c.get('service'))
result.update(c)
return result