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

Python util.DottedNameResolver类代码示例

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

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



在下文中一共展示了DottedNameResolver类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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,
    }
开发者ID:nightmarebadger,项目名称:kotti_disqus,代码行数:26,代码来源:views.py


示例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
开发者ID:akirisolutions-zz,项目名称:apex,代码行数:32,代码来源:models.py


示例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
开发者ID:eevee,项目名称:floof,代码行数:35,代码来源:__init__.py


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


示例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)
开发者ID:akirisolutions-zz,项目名称:apex,代码行数:25,代码来源:models.py


示例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
开发者ID:nicfit,项目名称:apex,代码行数:25,代码来源:models.py


示例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,)
开发者ID:ArcheProject,项目名称:Arche,代码行数:10,代码来源:__init__.py


示例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)
开发者ID:HorizonXP,项目名称:pyramid,代码行数:55,代码来源:mako_templating.py


示例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)
开发者ID:ncouture,项目名称:pyramid_sms,代码行数:12,代码来源:__init__.py


示例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
开发者ID:duffyd,项目名称:myreturnvisits,代码行数:13,代码来源:paster.py


示例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)
开发者ID:Affirm,项目名称:pyrollbar,代码行数:49,代码来源:__init__.py


示例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)
开发者ID:tobsan,项目名称:voteit.core,代码行数:16,代码来源:crontick.py


示例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
开发者ID:invisibleroads,项目名称:pyramid,代码行数:16,代码来源:pshell.py


示例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()
开发者ID:Janaba,项目名称:adhocracy3,代码行数:34,代码来源:testing.py


示例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
开发者ID:rfk,项目名称:pyramid,代码行数:18,代码来源:pshell.py


示例16: __init__

 def __init__(self, app, rest_url: str = "http://localhost", base_path: str = "/", header: dict = None):
     """Initialize self."""
     self.app = TestApp(app)
     """: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."""
     self._resolver = DottedNameResolver()
开发者ID:fhartwig,项目名称:adhocracy3.mercator,代码行数:11,代码来源:testing.py


示例17: pshell_file_config

    def pshell_file_config(self, filename):
        config = self.ConfigParser()
        config.optionxform = str
        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
            elif k == 'default_shell':
                self.preferred_shells = [x.lower() for x in aslist(v)]
            else:
                self.loaded_objects[k] = resolver.maybe_resolve(v)
                self.object_help[k] = v
开发者ID:MatthewWilkes,项目名称:pyramid,代码行数:21,代码来源:pshell.py


示例18: 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"])

        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
开发者ID:ZonarSystems,项目名称:apex,代码行数:22,代码来源:models.py


示例19: __call__

    def __call__(self, info):
        p = re.compile(r"(?P<asset>[\w_.:/]+)" r"(?:\#(?P<defname>[\w_]+))?" r"(\.(?P<ext>.*))")
        asset, defname, ext = p.match(info.name).group("asset", "defname", "ext")
        path = "%s.%s" % (asset, ext)
        registry = info.registry
        settings = info.settings
        settings_prefix = self.settings_prefix

        if settings_prefix is None:
            settings_prefix = info.type + "."

        lookup = registry.queryUtility(IMakoLookup, name=settings_prefix)

        def sget(name, default=None):
            return settings.get(settings_prefix + name, default)

        if lookup is None:
            reload_templates = settings.get("pyramid.reload_templates", None)
            if reload_templates is None:
                reload_templates = settings.get("reload_templates", False)
            reload_templates = asbool(reload_templates)
            directories = sget("directories", [])
            module_directory = sget("module_directory", None)
            input_encoding = sget("input_encoding", "utf-8")
            error_handler = sget("error_handler", None)
            default_filters = sget("default_filters", "h")
            imports = sget("imports", None)
            strict_undefined = asbool(sget("strict_undefined", False))
            preprocessor = sget("preprocessor", None)
            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()))
            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, name=settings_prefix)
            finally:
                registry_lock.release()

        return MakoLookupTemplateRenderer(path, defname, lookup)
开发者ID:Javex,项目名称:pyramid,代码行数:66,代码来源:mako_templating.py


示例20: run

    def run(self, shell=None):
        if self.args.list:
            return self.show_shells()
        if not self.args.config_uri:
            self.out('Requires a config file argument')
            return 2
        config_uri = self.args.config_uri
        config_vars = parse_vars(self.args.config_vars)
        loader = self.get_config_loader(config_uri)
        loader.setup_logging(config_vars)
        self.pshell_file_config(loader, config_vars)

        env = self.bootstrap(config_uri, options=config_vars)

        # remove the closer from the env
        self.closer = env.pop('closer')

        # setup help text for default environment
        env_help = dict(env)
        env_help['app'] = 'The WSGI application.'
        env_help['root'] = 'Root of the default resource tree.'
        env_help['registry'] = 'Active Pyramid registry.'
        env_help['request'] = 'Active request object.'
        env_help['root_factory'] = (
            'Default root factory used to create `root`.')

        # override use_script with command-line options
        if self.args.setup:
            self.setup = self.args.setup

        if self.setup:
            # store the env before muddling it with the script
            orig_env = env.copy()

            # call the setup callable
            resolver = DottedNameResolver(None)
            setup = resolver.maybe_resolve(self.setup)
            setup(env)

            # remove any objects from default help that were overidden
            for k, v in env.items():
                if k not in orig_env or env[k] != orig_env[k]:
                    if getattr(v, '__doc__', False):
                        env_help[k] = v.__doc__.replace("\n", " ")
                    else:
                        env_help[k] = v

        # load the pshell section of the ini file
        env.update(self.loaded_objects)

        # eliminate duplicates from env, allowing custom vars to override
        for k in self.loaded_objects:
            if k in env_help:
                del env_help[k]

        # generate help text
        help = ''
        if env_help:
            help += 'Environment:'
            for var in sorted(env_help.keys()):
                help += '\n  %-12s %s' % (var, env_help[var])

        if self.object_help:
            help += '\n\nCustom Variables:'
            for var in sorted(self.object_help.keys()):
                help += '\n  %-12s %s' % (var, self.object_help[var])

        if shell is None:
            try:
                shell = self.make_shell()
            except ValueError as e:
                self.out(str(e))
                self.closer()
                return 1

        if self.pystartup and os.path.isfile(self.pystartup):
            with open(self.pystartup, 'rb') as fp:
                exec_(fp.read().decode('utf-8'), env)
            if '__builtins__' in env:
                del env['__builtins__']

        try:
            shell(env, help)
        finally:
            self.closer()
开发者ID:invisibleroads,项目名称:pyramid,代码行数:85,代码来源:pshell.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python view.render_view函数代码示例发布时间:2022-05-27
下一篇:
Python util.text_函数代码示例发布时间: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