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

Python config.Configurator类代码示例

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

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



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

示例1: test_it

 def test_it(self):
     from pyramid.config import Configurator
     from pyramid_handlers import add_handler
     from pyramid_handlers import includeme
     c = Configurator(autocommit=True)
     c.include(includeme)
     self.assertTrue(c.add_handler.__func__.__docobj__ is add_handler)
开发者ID:Pylons,项目名称:pyramid_handlers,代码行数:7,代码来源:tests.py


示例2: registerDummySecurityPolicy

def registerDummySecurityPolicy(userid=None, groupids=(), permissive=True):
    """ Registers a pair of faux :app:`Pyramid` security policies:
    a :term:`authentication policy` and a :term:`authorization
    policy`.

    The behavior of the registered :term:`authorization policy`
    depends on the ``permissive`` argument.  If ``permissive`` is
    true, a permissive :term:`authorization policy` is registered;
    this policy allows all access.  If ``permissive`` is false, a
    nonpermissive :term:`authorization policy` is registered; this
    policy denies all access.

    The behavior of the registered :term:`authentication policy`
    depends on the values provided for the ``userid`` and ``groupids``
    argument.  The authentication policy will return the userid
    identifier implied by the ``userid`` argument and the group ids
    implied by the ``groupids`` argument when the
    :func:`pyramid.security.authenticated_userid` or
    :func:`pyramid.security.effective_principals` APIs are used.

    This function is most useful when testing code that uses the APIs named
    :func:`pyramid.security.has_permission`,
    :func:`pyramid.security.authenticated_userid`,
    :func:`pyramid.security.unauthenticated_userid`,
    :func:`pyramid.security.effective_principals`, and
    :func:`pyramid.security.principals_allowed_by_permission`.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_securitypolicy(userid=userid, groupids=groupids,
                                           permissive=permissive)
    config.commit()
    return result
开发者ID:araymund,项目名称:karl,代码行数:33,代码来源:testing.py


示例3: test_pyramid_directive

    def test_pyramid_directive(self):
        from pyramid.config import Configurator

        config = Configurator()
        config.include('ptah')

        self.assertTrue(hasattr(config, 'ptah_migrate'))
开发者ID:webmaven,项目名称:ptah,代码行数:7,代码来源:test_migrate.py


示例4: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    load_project_settings()

    session_factory = UnencryptedCookieSessionFactoryConfig(settings.get('session.secret', 'hello'))

    engine = engine_from_config(settings, 'sqlalchemy.')
    db.configure(bind=engine)
    config = Configurator(session_factory=session_factory, settings=settings)
    config.add_tween('droneos_ui.auth.authenticator')
    config.include('pyramid_handlers')
    config.add_view('pyramid.view.append_slash_notfound_view',
                context='pyramid.httpexceptions.HTTPNotFound')

    add_admin_handler(config, db, get_models(droneos_ui), 'admin.', '/admin', AdminController)

    application_routes(config)
    configure_app_routes(config)

    all_apps = get_submodules(apps)

    ignored_apps = []
    for app in all_apps:
        if app['is_package'] and app['name'] not in enabled_apps:
            ignored_apps.append('.apps.' + app['name'])

    config.scan(ignore=ignored_apps)

    return config.make_wsgi_app()
开发者ID:kashifpk,项目名称:droneos,代码行数:31,代码来源:__init__.py


示例5: main

def main(argv=sys.argv):
    # Usage and configuration
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    config = Configurator(settings=settings)
    config.include('pyramid_sqlalchemy')

    # Make the database with schema and default data
    with transaction.manager:
        metadata.create_all()
        root = RootFolder(name='',
                      title='Moonbase Demo',
                      __acl__=[
                          ['Allow', ['paul'], 'view']
                      ]
                      )
        Session.add(root)
        f1 = root['f1'] = Folder(
            title='Folder 1',
            __acl__=[
                ['Allow', ['shane'], 'view']
            ]
        )
        f1['da'] = Document(title='Document 1A')
开发者ID:pauleveritt,项目名称:moonbase,代码行数:27,代码来源:initializedb.py


示例6: registerEventListener

def registerEventListener(event_iface=None):
    """ Registers an :term:`event` listener (aka :term:`subscriber`)
    listening for events of the type ``event_iface``.  This method
    returns a list object which is appended to by the subscriber
    whenever an event is captured.

    When an event is dispatched that matches ``event_iface``, that
    event will be appended to the list.  You can then compare the
    values in the list to expected event notifications.  This method
    is useful when testing code that wants to call
    :meth:`pyramid.registry.Registry.notify`,
    :func:`zope.component.event.dispatch` or
    :func:`zope.component.event.objectEventNotify`.

    The default value of ``event_iface`` (``None``) implies a
    subscriber registered for *any* kind of event.

    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_add_subscriber`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_add_subscriber(event_iface)
    config.commit()
    return result
开发者ID:jkrebs,项目名称:pyramid,代码行数:27,代码来源:testing.py


示例7: app

def app():
    config = Configurator()
    config.include('pyramid_wiring')

    graph = Graph()
    graph.register_scope(RequestScope, RequestScope())
    class Counter(object):
        def __init__(self):
            self.count = 1
    graph.register_provider('counter', FactoryProvider(Counter, scope=RequestScope))
    config.set_object_graph(graph)

    def count(request, counter=injected('counter')):
        # Increment the counter
        count = counter.count
        counter.count += 1

        # Get the counter from the graph again and make sure it's the same
        assert graph.get('counter') is counter

        return count
    config.add_route('count', '/count')
    config.add_view(count, route_name='count', renderer='string')

    return TestApp(config.make_wsgi_app())
开发者ID:veeti,项目名称:pyramid_wiring,代码行数:25,代码来源:test_scope.py


示例8: test_handle_submit_key_expired

    def test_handle_submit_key_expired(self):
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')
        request = self.request
        request.params['key'] = '0' * 40
        self._setupUsers()
        context = self.context
        context['profiles'] = testing.DummyModel()
        profile = context['profiles']['me'] = testing.DummyModel()
        profile.password_reset_key = '0' * 40
        controller = self._makeOne(context, request)
        converted = {'login': 'me'}
        # first w/ no profile reset time
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Key Expired')

        # now w/ expired key
        renderer = config.testing_add_template('templates/reset_failed.pt')
        from karl.views.resetpassword import max_reset_timedelta
        import datetime
        keytime = datetime.datetime.now() - max_reset_timedelta
        profile.password_reset_time = keytime
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Key Expired')
开发者ID:zagy,项目名称:karl,代码行数:29,代码来源:test_resetpassword.py


示例9: test_handle_submit_utf8_password

 def test_handle_submit_utf8_password(self):
     password = u'password\xe1'
     reg = get_current_registry()
     config = Configurator(reg)
     renderer = config.testing_add_template('templates/reset_complete.pt')
     request = self.request
     request.params['key'] = '0' * 40
     self._setupUsers()
     context = self.context
     context['profiles'] = testing.DummyModel()
     profile = context['profiles']['me'] = testing.DummyModel()
     profile.password_reset_key = '0' * 40
     controller = self._makeOne(context, request)
     converted = {'login': 'me', 'password': password}
     import datetime
     keytime = datetime.datetime.now()
     profile.password_reset_time = keytime
     response = controller.handle_submit(converted)
     self.failUnless(hasattr(renderer, 'api'))
     self.assertEqual(renderer.api.page_title,
                      'Password Reset Complete')
     renderer.assert_(login='me', password=password)
     self.failUnless(profile.password_reset_key is None)
     self.failUnless(profile.password_reset_time is None)
     user = self.context.users.get(login='me')
     from repoze.who.plugins.zodb.users import get_sha_password
     self.assertEqual(user['password'], get_sha_password(password.encode('utf8')))
开发者ID:zagy,项目名称:karl,代码行数:27,代码来源:test_resetpassword.py


示例10: test___call__bad_key

    def test___call__bad_key(self):
        # register dummy renderer for the email template
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')

        request = self.request
        request.layout_manager = mock.Mock()
        # no key
        controller = self._makeOne(self.context, request)
        response = controller()
        from pyramid.response import Response
        self.assertEqual(response.__class__, Response)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset URL Problem')

        # reset renderer.api value so we know the test is useful
        renderer = config.testing_add_template('templates/reset_failed.pt')
        # key of wrong length
        request.params['key'] = 'foofoofoo'
        controller = self._makeOne(self.context, request)
        response = controller()
        from pyramid.response import Response
        self.assertEqual(response.__class__, Response)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset URL Problem')
开发者ID:zagy,项目名称:karl,代码行数:28,代码来源:test_resetpassword.py


示例11: test_handle_submit_wrong_key

    def test_handle_submit_wrong_key(self):
        reg = get_current_registry()
        config = Configurator(reg)
        renderer = config.testing_add_template('templates/reset_failed.pt')
        request = self.request
        request.params['key'] = '0' * 40
        self._setupUsers()
        context = self.context
        context['profiles'] = testing.DummyModel()
        context['profiles']['me'] = testing.DummyModel()
        controller = self._makeOne(context, request)
        converted = {'login': 'me'}
        # first w/ no profile reset key
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Problem')

        # now w/ wrong profile reset key
        renderer = config.testing_add_template('templates/reset_failed.pt')
        context['profiles']['me'].password_reset_key = '1' * 40
        response = controller.handle_submit(converted)
        self.failUnless(hasattr(renderer, 'api'))
        self.assertEqual(renderer.api.page_title,
                         'Password Reset Confirmation Problem')
开发者ID:zagy,项目名称:karl,代码行数:25,代码来源:test_resetpassword.py


示例12: create_app

def create_app(settings):
    from horus import groupfinder
    from pyramid.config import Configurator
    from pyramid.authentication import AuthTktAuthenticationPolicy
    from pyramid.authorization import ACLAuthorizationPolicy

    settings.setdefault('horus.activation_class', 'h.models.Activation')
    settings.setdefault('horus.user_class', 'h.models.User')

    authn_policy = AuthTktAuthenticationPolicy(
        settings['auth.secret'],
        callback=groupfinder
    )

    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(
        settings=settings,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
        root_factory='h.resources.RootFactory'
    )

    config.include(includeme)
    return config.make_wsgi_app()
开发者ID:Laurian,项目名称:h,代码行数:25,代码来源:__init__.py


示例13: get_app

def get_app(
        tool_definition, data_folder, website_name=None, website_owner=None,
        website_url=None):
    settings = {
        'data.folder': data_folder,
        'website.name': website_name or WEBSITE['name'],
        'website.owner': website_owner or WEBSITE['owner'],
        'website.url': website_url or WEBSITE['url'],
        'website.root_assets': [
            'invisibleroads_posts:assets/favicon.ico',
            'invisibleroads_posts:assets/robots.txt',
        ],
        'uploads.upload.id.length': 32,
        'client_cache.http.expiration_time': 3600,
        'jinja2.directories': 'crosscompute:templates',
        'jinja2.lstrip_blocks': True,
        'jinja2.trim_blocks': True,
    }
    settings['tool_definition'] = tool_definition
    config = Configurator(settings=settings)
    config.include('invisibleroads_posts')
    includeme(config)
    add_routes(config)
    add_routes_for_fused_assets(config)
    return config.make_wsgi_app()
开发者ID:crosscompute,项目名称:crosscompute,代码行数:25,代码来源:serve.py


示例14: main

def main(argv=sys.argv):
	if len(argv) != 2:
		usage(argv)
	config_uri = argv[1]
	setup_logging(config_uri)
	settings = get_appsettings(config_uri)
	engine = engine_from_config(settings, 'sqlalchemy.')
	DBSession.configure(bind=engine)
	cache.cache = cache.configure_cache(settings)

	config = Configurator(
		settings=settings,
		root_factory=RootFactory,
		locale_negotiator=locale_neg
	)
	config.add_route_predicate('vhost', VHostPredicate)
	config.add_view_predicate('vhost', VHostPredicate)

	mmgr = config.registry.getUtility(IModuleManager)
	mmgr.load('core')
	mmgr.load_enabled()

	rts = rt.configure(mmgr, config.registry)
	app = rts.app()
	rt.run(rts, app)
开发者ID:baloon11,项目名称:npui,代码行数:25,代码来源:rtd.py


示例15: registerSettings

def registerSettings(dictarg=None, **kw):
    """Register one or more 'setting' key/value pairs.  A setting is
    a single key/value pair in the dictionary-ish object returned from
    the API :attr:`pyramid.registry.Registry.settings`.

    You may pass a dictionary::

       registerSettings({'external_uri':'http://example.com'})

    Or a set of key/value pairs::

       registerSettings(external_uri='http://example.com')

    Use of this function is required when you need to test code that calls
    the :attr:`pyramid.registry.Registry.settings` API and which uses return
    values from that API.

    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.add_settings`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    config.add_settings(dictarg, **kw)
开发者ID:jkrebs,项目名称:pyramid,代码行数:25,代码来源:testing.py


示例16: _makeOne

 def _makeOne(self, autocommit=True):
     from pyramid.config import Configurator
     import pyramid_handlers
     from papyrus import add_papyrus_routes
     config = Configurator(autocommit=autocommit)
     config.add_directive('add_papyrus_routes', add_papyrus_routes)
     return config
开发者ID:almet,项目名称:papyrus,代码行数:7,代码来源:test_init.py


示例17: registerResources

def registerResources(resources):
    """ Registers a dictionary of :term:`resource` objects that can be
    resolved via the :func:`pyramid.traversal.find_resource` API.

    The :func:`pyramid.traversal.find_resource` API is called with a
    path as one of its arguments.  If the dictionary you register when
    calling this method contains that path as a string key
    (e.g. ``/foo/bar`` or ``foo/bar``), the corresponding value will
    be returned to ``find_resource`` (and thus to your code) when
    :func:`pyramid.traversal.find_resource` is called with an
    equivalent path string or tuple.

    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_resources`
       method in your unit and integration tests.

    .. note:: For ancient backward compatibility purposes, this API can also
       be accessed as :func:`pyramid.testing.registerModels`.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_resources(resources)
    config.commit()
    return result
开发者ID:jkrebs,项目名称:pyramid,代码行数:25,代码来源:testing.py


示例18: main

def main(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    settings = dict(settings)
    settings.setdefault('jinja2.i18n.domain', 'hello_world')

    # Start Sphinx Include 2
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config = Configurator(root_factory=get_root, settings=settings,
                          session_factory=my_session_factory)
    # End Sphinx Include 2
    config.add_translation_dirs('locale/')
    # Start Include
    config.include('pyramid_jinja2')
    # End Include


    config.add_static_view('static', 'static')
    config.add_view('hello_world.views.my_view',
                    context='hello_world.models.MyModel', 
                    renderer="mytemplate.jinja2")

    return config.make_wsgi_app()
开发者ID:AdamG,项目名称:pyramid,代码行数:26,代码来源:__init__.py


示例19: TestServiceDefinition

class TestServiceDefinition(unittest2.TestCase):

    def setUp(self):
        if not metlog:
            raise(unittest2.SkipTest('no metlog'))
        mozconfig = Config(StringIO(dedent("""
        [test1]
        backend = mozsvc.metrics.MetlogPlugin
        sender_class=metlog.senders.DebugCaptureSender
        """)))
        settings = {"config": mozconfig}
        self.plugin = load_from_config("test1", mozconfig)
        self.config = Configurator(settings=settings)
        self.config.include("cornice")
        self.config.scan("mozsvc.tests.test_service_definition")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_decorated_view_fn(self):
        # passing a decorator in to the service api call should result in a
        # decorated view callable
        resp = self.app.get("/service3")
        self.assertEquals(resp.json, {'test': 'succeeded', 'wrapped0': 'yes'})

    def test_stacked_decorated_view(self):
        # passing a decorator in to the service api call should result in a
        # decorated view callable, ordering of the particular decorators
        # shouldn't break things
        resp = self.app.get("/service4")
        self.assertEquals(resp.json, {'test': 'succeeded', 'wrapped0': 'yes'})

        resp = self.app.get("/service5")
        self.assertEquals(resp.json, {'test': 'succeeded', 'wrapped0': 'yes'})
开发者ID:ncalexan,项目名称:mozservices,代码行数:35,代码来源:test_service_definition.py


示例20: _apply_parent_actions

def _apply_parent_actions(parent_registry):
    toolbar_app = parent_registry.queryUtility(IToolbarWSGIApp)
    if toolbar_app is None:
        # this registry does not have a debugtoolbar attached
        return

    toolbar_registry = toolbar_app.registry

    # inject the BeforeRender subscriber after the application is created
    # and all other subscribers are registered in hopes that this will be
    # the last subscriber in the chain and will be able to see the effects
    # of all previous subscribers on the event
    parent_config = Configurator(registry=parent_registry, introspection=False)

    parent_config.add_subscriber(
        'pyramid_debugtoolbar.toolbar.beforerender_subscriber',
        'pyramid.events.BeforeRender',
    )

    actions = toolbar_registry.queryUtility(IParentActions, default=[])
    for action in actions:
        action(parent_config)

    # overwrite actions after they have been applied to avoid applying them
    # twice - but leave it as a new list incase someone adds more actions later
    # and calls config.make_wsgi_app() again... this would mainly be necessary
    # for tests that call config.make_wsgi_app() multiple times.
    toolbar_registry.registerUtility([], IParentActions)

    parent_config.commit()
开发者ID:Pylons,项目名称:pyramid_debugtoolbar,代码行数:30,代码来源:__init__.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python configuration.Configurator类代码示例发布时间:2022-05-27
下一篇:
Python json.dumps函数代码示例发布时间: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