• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python path.DottedNameResolver类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid.path.DottedNameResolver的典型用法代码示例。如果您正苦于以下问题:Python DottedNameResolver类的具体用法?Python DottedNameResolver怎么用?Python DottedNameResolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: configure_task

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
开发者ID:jessedhillon,项目名称:bonanza,代码行数:33,代码来源:common.py


示例2: get_db_session

def get_db_session(request, settings=None):
    if settings is None:
        settings = request.registry.settings
    session_path = settings.get('bowab.db_session', DBSession)
    resolver = DottedNameResolver()
    db_session = resolver.maybe_resolve(session_path)
    return db_session
开发者ID:davidblewett,项目名称:sixfeetup.bowab,代码行数:7,代码来源:base.py


示例3: configure_mailer

    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)
开发者ID:rmoorman,项目名称:websauna,代码行数:26,代码来源:__init__.py


示例4: start_scheduler

def start_scheduler(config):
    reader = config.settings_reader()
    settings = reader.settings
    scheduler = reader.read_str('papaye.scheduler')
    scheduler_keys = (key[17:] for key in settings.keys()
                      if key.startswith('papaye.scheduler.'))
    if not reader.read_bool('papaye.cache') or scheduler is None:
        scheduler = DummyScheduler()
    else:
        resolver = DottedNameResolver()
        scheduler_kwargs = {key[17:]: val for key, val in settings.items()
                            if key in scheduler_keys}
        scheduler = resolver.maybe_resolve(scheduler)(**scheduler_kwargs)
    scheduler.start()
    TaskRegistry().register_scheduler(scheduler)

    def get_scheduler(request):

        return scheduler

    config.add_request_method(
        get_scheduler,
        'scheduler',
        property=True,
        reify=True
    )
开发者ID:rcommande,项目名称:papaye,代码行数:26,代码来源:startup.py


示例5: run

    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)
开发者ID:rmoorman,项目名称:websauna,代码行数:60,代码来源:__init__.py


示例6: debug

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
开发者ID:frispete,项目名称:websauna,代码行数:30,代码来源:vars.py


示例7: main

def main(argv=sys.argv, processor=None):
    logger = logging.getLogger(__name__)

    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    settings = setup_database({}, **settings)

    session = settings['session']
    subscription_model = SubscriptionModel(session)
    tx_model = TransactionModel(session)

    maximum_retry = int(settings.get(
        'billy.transaction.maximum_retry', 
        TransactionModel.DEFAULT_MAXIMUM_RETRY,
    ))

    resolver = DottedNameResolver()
    if processor is None:
        processor_factory = settings['billy.processor_factory']
        processor_factory = resolver.maybe_resolve(processor_factory)
        processor = processor_factory()

    # yield all transactions and commit before we process them, so that
    # we won't double process them. 
    with db_transaction.manager:
        logger.info('Yielding transaction ...')
        subscription_model.yield_transactions()

    with db_transaction.manager:
        logger.info('Processing transaction ...')
        tx_model.process_transactions(processor, maximum_retry=maximum_retry)
    logger.info('Done')
开发者ID:JeffersonK,项目名称:billy,代码行数:35,代码来源:process_transactions.py


示例8: configure_mailer

    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')
开发者ID:LukeSwart,项目名称:websauna,代码行数:32,代码来源:__init__.py


示例9: includeme

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})
开发者ID:dz0ny,项目名称:pyramid_basemodel,代码行数:60,代码来源:__init__.py


示例10: get_init

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
开发者ID:LukeSwart,项目名称:websauna,代码行数:31,代码来源:__init__.py


示例11: includeme

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)
开发者ID:jenner,项目名称:pyramid_extdirect,代码行数:28,代码来源:__init__.py


示例12: mailer_settings_factory

def mailer_settings_factory(settings, prefix='photoapp.mailer.'):
    """Returns the correctly configured specific implementation
    of an IMailer object based on settings.

    The specific implementation is determined by the `type`
    setting, currently:

    smtp:
        send mail from SMTP server
    console:
        print mail messages to stdout (does not send any mail)

    `console` is the default type.

    Args:
        settings: dict of settings
        prefix: specific prefix to find mailer-specific settings

    Returns:
        IMailer instance
    """

    classname = settings.get(prefix + 'class',
                             'photoapp.mail.SMTP_Mailer')

    mailer_cls = DottedNameResolver().resolve(classname)
    return mailer_cls.from_settings(settings, prefix)
开发者ID:danjac,项目名称:photoapp,代码行数:27,代码来源:mail.py


示例13: debug

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
开发者ID:LukeSwart,项目名称:websauna,代码行数:31,代码来源:vars.py


示例14: test_app_no_login_real_policy

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
开发者ID:assembl,项目名称:assembl,代码行数:28,代码来源:base.py


示例15: _parse_settings

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
开发者ID:claeyswo,项目名称:pyramid_rawes,代码行数:59,代码来源:__init__.py


示例16: command

 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()
开发者ID:helixyte,项目名称:TheLMA,代码行数:59,代码来源:shell.py


示例17: __new__

 def __new__(cls, namespace, base, *args, **kw):
     # Dotted name support makes it easy to configure with pyramid_multiauth
     name_resolver = DottedNameResolver(caller_package())
     base = name_resolver.maybe_resolve(base)
     # Dynamically create a subclass
     name = 'Namespaced_%s_%s' % (namespace, base.__name__)
     klass = type(name, (cls, base), {'_namespace_prefix': namespace + '.'})
     return super(NamespacedAuthenticationPolicy, klass).__new__(klass)
开发者ID:ClinGen,项目名称:clincoded,代码行数:8,代码来源:authentication.py


示例18: add_logging

def add_logging(config, log_key, log_func=None):
    resolver = DottedNameResolver()
    if log_func is None:
        log_func = operator.attrgetter(log_key)
    log_func = resolver.maybe_resolve(log_func)

    config.registry[get_key("registered_loggers")][log_key] = log_func
    config.registry[get_key("order")].append(log_key)
开发者ID:dobrite,项目名称:notaliens.com,代码行数:8,代码来源:log.py


示例19: get_processor_factory

def get_processor_factory(settings):
    """Get processor factory from settings and return

    """
    resolver = DottedNameResolver()
    processor_factory = settings['billy.processor_factory']
    processor_factory = resolver.maybe_resolve(processor_factory)
    return processor_factory
开发者ID:Imaxinacion,项目名称:billy,代码行数:8,代码来源:utils.py


示例20: _load_module

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
开发者ID:sakal,项目名称:pyramid-watchshop,代码行数:8,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python registry.Registry类代码示例发布时间:2022-05-27
下一篇:
Python path.AssetResolver类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap