当前位置: 首页>>代码示例>>Python>>正文


Python Configurator.hook_zca方法代码示例

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


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

示例1: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """ This function returns a WSGI application.
    """

    # TODO: make it safer. Remember it's unencrypted.
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseecreet')
    authn_policy = AuthTktAuthenticationPolicy(secret='sosecret',
                                               callback=groupfinder)
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(session_factory=my_session_factory,
                          root_factory=root_factory, settings=settings,
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy)
    config.add_translation_dirs('easyblog:locale/')
    config.set_locale_negotiator(my_locale_negotiator)
    config.add_settings(encoding="UTF-8")
    # config.add_settings(languages=['fi', 'en'])
    # config.add_settings({'default_locale_name': 'fi'})
    config.add_settings(default_encoding="UTF-8")
    config.hook_zca()

    config.include('pyramid_viewgroup')

    config.add_static_view('static', 'easyblog:static/', cache_max_age=3600)
    config.scan()

    config.add_route('lang', '/lang-{code}')
    return config.make_wsgi_app()
开发者ID:tojuhaka,项目名称:easyblog,代码行数:30,代码来源:__init__.py

示例2: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **local_config):
    """
    A paste.httpfactory to wrap a pyramid WSGI based application.
    """
    wconf = global_config.copy()
    wconf.update(**local_config)
    if global_config.get("debug", "False").lower() == "true":
        wconf["pyramid.debug_authorization"] = "true"
        wconf["pyramid.debug_notfound"] = "true"
        wconf["pyramid.reload_templates"] = "true"
        wconf["debugtoolbar.eval_exc"] = "true"
        wconf["debugtoolbar.enabled"] = "true"
    wconf["zcmls"] = utils.splitstrip(wconf["zcmls"])
    if not wconf["zcmls"]:
        wconf["zcmls"] = []
    wconf["zcmls"].insert(0, "configure.zcml")
    for i, zcml in enumerate(wconf["zcmls"]):
        if os.path.sep in zcml:
            zcml = os.path.abspath(zcml)
        else:
            zcml = pkg_resources.resource_filename(dn, zcml)
        wconf["zcmls"][i] = zcml
    globalreg = getGlobalSiteManager()
    config = Configurator(registry=globalreg)
    config.setup_registry(settings=wconf)
    config.include("pyramid_debugtoolbar")
    config.include("pyramid_chameleon")
    config.include("pyramid_zcml")
    config.add_static_view(name="resources", path=here + "/templates/static")
    config.hook_zca()
    for z in wconf["zcmls"]:
        config.load_zcml(z)
    return config.make_wsgi_app()
开发者ID:collective,项目名称:collective.generic.webbuilder,代码行数:35,代码来源:__init__.py

示例3: app_config

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def app_config():
    config = Configurator(settings=load(open(SETTINGS_FILE, 'r').read()))
    config.add_settings({'currentapp.basedir': APP_BASE_DIR})
    config.add_translation_dirs('example_app:locale/')
    config.hook_zca()
    config.include('example_app')
    # config.add_route('catchall', '{notfound:.*}')
    return config
开发者ID:jarederaj,项目名称:pyramid-gae-tutorial,代码行数:10,代码来源:main.py

示例4: base_configure

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def base_configure(global_config, **settings):
    # Resolve dotted names in settings, include plug-ins and create a
    # Configurator.

    from kotti.resources import get_root

    for key, value in conf_defaults.items():
        settings.setdefault(key, value)

    for key, value in settings.items():
        if key.startswith('kotti') and isinstance(value, basestring):
            settings[key] = unicode(value, 'utf8')

    # Allow extending packages to change 'settings' w/ Python:
    k = 'kotti.configurators'
    for func in _resolve_dotted(settings, keys=(k,))[k]:
        func(settings)

    settings = _resolve_dotted(settings)
    secret1 = settings['kotti.secret']
    settings.setdefault('kotti.secret2', secret1)

    # We'll process ``pyramid_includes`` later by hand, to allow
    # overrides of configuration from ``kotti.base_includes``:
    pyramid_includes = settings.pop('pyramid.includes', '')

    config = Configurator(
        request_factory=settings['kotti.request_factory'][0],
        settings=settings)
    config.begin()

    config.hook_zca()
    config.include('pyramid_zcml')

    # Chameleon bindings were removed from Pyramid core since pyramid>=1.5a2
    config.include('pyramid_chameleon')

    config.registry.settings['pyramid.includes'] = pyramid_includes

    # Include modules listed in 'kotti.base_includes':
    for module in settings['kotti.base_includes']:
        config.include(module)
    config.commit()

    # Modules in 'pyramid.includes' and 'kotti.zcml_includes' may
    # override 'kotti.base_includes':
    if pyramid_includes:
        for module in pyramid_includes.split():
            config.include(module)

    for name in settings['kotti.zcml_includes'].strip().split():
        config.load_zcml(name)

    config.commit()

    config._set_root_factory(get_root)

    return config
开发者ID:adamcheasley,项目名称:Kotti,代码行数:60,代码来源:__init__.py

示例5: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """Sets up the pyramid application.
    """
    config = Configurator(settings=settings)
    config.include(pyramid_zcml)
    config.hook_zca()
    config.load_zcml('configure.zcml')

    return config.make_wsgi_app()
开发者ID:4teamwork,项目名称:ftw.bridge.proxy,代码行数:11,代码来源:__init__.py

示例6: make_app

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def make_app(root_factory, package=None, filename='configure.zcml',
             settings=None, options=None, Configurator=Configurator):
    """ Return a Router object, representing a fully configured
    Pyramid WSGI application.

    .. warning:: Use of this function is deprecated as of
       Pyramid 1.0.  You should instead use a
       :class:`pyramid.config.Configurator` instance to
       perform startup configuration as shown in
       :ref:`configuration_narr`.

    ``root_factory`` must be a callable that accepts a :term:`request`
    object and which returns a traversal root object.  The traversal
    root returned by the root factory is the *default* traversal root;
    it can be overridden on a per-view basis.  ``root_factory`` may be
    ``None``, in which case a 'default default' traversal root is
    used.

    ``package`` is a Python :term:`package` or module representing the
    application's package.  It is optional, defaulting to ``None``.
    ``package`` may be ``None``.  If ``package`` is ``None``, the
    ``filename`` passed or the value in the ``options`` dictionary
    named ``configure_zcml`` must be a) absolute pathname to a
    :term:`ZCML` file that represents the application's configuration
    *or* b) a :term:`asset specification` to a :term:`ZCML` file in
    the form ``dotted.package.name:relative/file/path.zcml``.

    ``filename`` is the filesystem path to a ZCML file (optionally
    relative to the package path) that should be parsed to create the
    application registry.  It defaults to ``configure.zcml``.  It can
    also be a ;term:`asset specification` in the form
    ``dotted_package_name:relative/file/path.zcml``. Note that if any
    value for ``configure_zcml`` is passed within the ``settings``
    dictionary, the value passed as ``filename`` will be ignored,
    replaced with the ``configure_zcml`` value.

    ``settings``, if used, should be a dictionary containing runtime
    settings (e.g. the key/value pairs in an app section of a
    PasteDeploy file), with each key representing the option and the
    key's value representing the specific option value,
    e.g. ``{'reload_templates':True}``.  Note that the keyword
    parameter ``options`` is a backwards compatibility alias for the
    ``settings`` keyword parameter.
    """
    settings = settings or options or {}
    zcml_file = settings.get('configure_zcml', filename)
    config = Configurator(package=package, settings=settings,
                          root_factory=root_factory, autocommit=True)
    config.include(includeme)
    config.hook_zca()
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    return config.make_wsgi_app()
开发者ID:nak,项目名称:Penumbra,代码行数:56,代码来源:__init__.py

示例7: TestFixtureApp

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
class TestFixtureApp(unittest.TestCase):
    def setUp(self):
        from pyramid.config import Configurator
        from pyramid_viewgroup.tests import fixtureapp
        self.config = Configurator(package=fixtureapp, autocommit=True)
        self.config.include('pyramid_zcml')
        self.config.hook_zca()

    def tearDown(self):
        self.config.end()

    def test_it(self):
        self.config.load_zcml('configure.zcml')
开发者ID:lugensa,项目名称:pyramid_viewgroup,代码行数:15,代码来源:test_all.py

示例8: wsgi_app_factory

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def wsgi_app_factory(global_config, **local_config):
    """
    A paste.httpfactory to wrap a django WSGI based application.
    """
    dn = 'collective.generic.webbuilder'
    wconf = global_config.copy()
    wconf.update(**local_config)
    debug = False
    if global_config.get('debug', 'False').lower() == 'true':
        debug = True
        wconf['pyramid.debug_authorization'] = 'true'
        wconf['pyramid.debug_notfound'] = 'true'
        wconf['pyramid.reload_templates'] = 'true'
    wconf['zcmls' ] = utils.splitstrip(wconf['zcmls'])
    if not wconf['zcmls']:
        wconf['zcmls'] = []
    wconf['zcmls'].insert(0, 'configure.zcml')
    for i, zcml in enumerate(wconf['zcmls']):
        if os.path.sep in zcml:
            zcml = os.path.abspath(zcml)
        else:
            zcml = pkg_resources.resource_filename(dn, zcml)
        wconf['zcmls'][i] = zcml 

    globalreg = getGlobalSiteManager() 
    config = Configurator(registry=globalreg)
    config.setup_registry(settings=wconf)
    config.include('pyramid_zcml')
    config.hook_zca()
    for z in wconf['zcmls']:
        config.load_zcml(z)  
    app = config.make_wsgi_app()
    def webbuilder_app(environ, start_response):
        req = Request(environ)
        try:
            resp = req.get_response(app)
            return resp(environ, start_response)
        except Exception, e:
            if not debug:
                return exc.HTTPServerError(str(e))(environ, start_response)
            else:
                raise
开发者ID:numahell,项目名称:collective.generic.webbuilder,代码行数:44,代码来源:webserver.py

示例9: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """    
    from progress.models.app import appmaker
    from progress.security import authn_policy
    from progress.security import authz_policy
    
    zodb_uri = settings.get('zodb_uri', False)
    if zodb_uri is False:
        raise ValueError("No 'zodb_uri' in application configuration.")

    finder = PersistentApplicationFinder(zodb_uri, appmaker)
    def get_root(request):
        return finder(request.environ)

    sessionfact = UnencryptedCookieSessionFactoryConfig('messages')
    
    config = Configurator(settings=settings,
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy,
                          root_factory=get_root,
                          session_factory = sessionfact,)
    
    config.add_static_view('static', 'progress:static')
    config.add_static_view('deform', 'deform:static')

    #Set which mailer to use
    #config.include(settings['mailer'])
    
    config.add_translation_dirs('deform:locale/',
                                'colander:locale/',
                                #'progress:locale/',
                                )


    config.hook_zca()
    config.scan('progress')
    config.scan('betahaus.pyracont.fields.versioning')
    return config.make_wsgi_app()
开发者ID:robinharms,项目名称:Progress,代码行数:41,代码来源:__init__.py

示例10: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """ This function returns a WSGI application.
    """

    # TODO: make it safer. Remember it's unencrypted.
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    authn_policy = AuthTktAuthenticationPolicy(secret='sosecret',
                                               callback=groupfinder)
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(session_factory=my_session_factory,
                          root_factory=root_factory, settings=settings,
                          authentication_policy=authn_policy,
                          authorization_policy=authz_policy)
    config.add_settings(encoding="utf8")
    config.add_settings(default_encoding="utf8")
    config.hook_zca()
    config.include(pyramid_zcml)
    config.load_zcml('configure.zcml')

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.scan()
    return config.make_wsgi_app()
开发者ID:tojuhaka,项目名称:tojuhaka_scaffolds,代码行数:24,代码来源:__init__.py

示例11: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    # paster app config callback
    zodb_uri = settings.get('zodb_uri', None)
    if zodb_uri is None:
        raise ValueError('zodb_uri must not be None')        

    roots = {}

    for k in settings:
        if k.startswith('sphinx.'):
            prefix, rest = k.split('sphinx.', 1)
            name, setting = rest.split('.', 1)
            tmp = roots.setdefault(name, {})
            tmp[setting] = settings[k]

    settings['sphinx_roots'] = roots

    for rootname, tmp in roots.items():
        if not 'url_prefix' in tmp:
            raise ValueError('sphinx.%s.url_prefix missing' % rootname)
        if not 'package_dir' in tmp:
            raise ValueError('sphinx.%s.package_dir missing' % rootname)
        if not 'docs_subpath' in tmp:
            raise ValueError('sphinx.%s.docs_subpath missing' % rootname)
        if not 'title' in tmp:
            raise ValueError('sphinx.%s.title missing' % rootname)
        if not 'description' in tmp:
            tmp['description'] = rootname

    finder = PersistentApplicationFinder(zodb_uri, appmaker)
    config = Configurator(settings=settings, root_factory=finder)
    config.hook_zca()
    config.begin()
    config.load_zcml('configure.zcml')
    config.scan()
    config.end()
    app = config.make_wsgi_app()
    return app
开发者ID:mcdonc,项目名称:marlton,代码行数:40,代码来源:__init__.py

示例12: setUp

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def setUp(registry=None, request=None, hook_zca=True, autocommit=True,
          settings=None, package=None):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``get_current_*`` functions (or call :app:`Pyramid` code
    that uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a *global*
    :term:`application registry`, which may cause unit tests to not be
    isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_registry` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    If ``settings`` is not ``None``, it must be a dictionary representing the
    values passed to a Configurator as its ``settings=`` argument.

    If ``package`` is ``None`` it will be set to the caller's package. The
    ``package`` setting in the :class:`pyramid.config.Configurator` will
    affect any relative imports made via
    :meth:`pyramid.config.Configurator.include` or
    :meth:`pyramid.config.Configurator.maybe_dotted`.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    if package is None:
        package = caller_package()
    config = Configurator(registry=registry, autocommit=autocommit,
                          package=package)
    if settings is None:
        settings = {}
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        config.add_default_renderers()
        config.add_default_view_predicates()
        config.add_default_route_predicates()
    config.commit()
    global have_zca
    try:
        have_zca and hook_zca and config.hook_zca()
    except ImportError: # pragma: no cover
        # (dont choke on not being able to import z.component)
        have_zca = False
    config.begin(request=request)
    return config
开发者ID:AdrianTeng,项目名称:pyramid,代码行数:94,代码来源:testing.py

示例13: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """Returns WSGI application.
    """
    # set authentication related application properties
    import cone.app.security as security
    security.ADMIN_USER = settings.get('cone.admin_user', 'admin')
    security.ADMIN_PASSWORD = settings.get('cone.admin_password', 'admin')
    
    auth_secret = settings.get('cone.auth_secret', 'secret')
    auth_cookie_name = settings.get('cone.auth_cookie_name', 'auth_tkt')
    auth_secure = settings.get('cone.auth_secure', False)
    auth_include_ip = settings.get('cone.auth_include_ip', False)
    auth_timeout = settings.get('cone.auth_timeout', None)
    auth_reissue_time = settings.get('cone.auth_reissue_time', None)
    if auth_reissue_time is not None:
        auth_reissue_time = int(auth_reissue_time)
    auth_max_age = settings.get('cone.auth_max_age', None)
    if auth_max_age is not None:
        auth_max_age = int(auth_max_age)
    auth_http_only = settings.get('cone.auth_http_only', False)
    auth_path = settings.get('cone.auth_path', "/")
    auth_wild_domain = settings.get('cone.auth_wild_domain', True)
    
    auth_policy = auth_tkt_factory(
        secret=auth_secret,
        cookie_name=auth_cookie_name,
        secure=auth_secure,
        include_ip=auth_include_ip,
        timeout=auth_timeout,
        reissue_time=auth_reissue_time,
        max_age=auth_max_age,
        http_only=auth_http_only,
        path=auth_path,
        wild_domain=auth_wild_domain,
    )
    
    configure_root(settings)
    
    if settings.get('testing.hook_global_registry'):
        globalreg = getGlobalSiteManager()
        config = Configurator(registry=globalreg)
        config.setup_registry(
            root_factory=get_root,
            settings=settings,
            authentication_policy=auth_policy,
            authorization_policy=acl_factory())
        config.hook_zca()
    else:
        config = Configurator(
            root_factory=get_root,
            settings=settings,
            authentication_policy=auth_policy,
            authorization_policy=acl_factory())
    
    config.include(pyramid_zcml)
    config.begin()
    
    config.load_zcml('configure.zcml')
    
    # read plugin configurator
    plugins = settings.get('cone.plugins', '')
    plugins = plugins.split('\n')
    plugins = [pl for pl in plugins if pl]
    for plugin in plugins:
        config.load_zcml('%s:configure.zcml' % plugin) #pragma NO COVERAGE
    
    # end config
    config.end()
    
    # execute main hooks
    for hook in main_hooks:
        hook(config, global_config, settings)
    
    # return wsgi app
    return config.make_wsgi_app()
开发者ID:AnneGilles,项目名称:cone.app,代码行数:77,代码来源:__init__.py

示例14: setUp

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def setUp(registry=None, request=None, hook_zca=True, autocommit=True):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any of the ``register*`` functions in :mod:`pyramid.testing`
      (such as :func:`pyramid.testing.registerResources`)

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``testing.register*`` APIs, or the
    ``get_current_*`` functions (or call :app:`Pyramid` code that
    uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a
    *global* :term:`application registry`, which may cause unit tests
    to not be isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_request` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.

    .. warning:: Although this method of setting up a test registry
                 will never disappear, after :app:`Pyramid` 1.0,
                 using the ``begin`` and ``end`` methods of a
                 ``Configurator`` are preferred to using
                 ``pyramid.testing.setUp`` and
                 ``pyramid.testing.tearDown``.  See
                 :ref:`testing_chapter` for more information.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    config = Configurator(registry=registry, autocommit=autocommit)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        from pyramid.config import DEFAULT_RENDERERS
        for name, renderer in DEFAULT_RENDERERS:
            # Cause the default renderers to be registered because
            # in-the-wild test code relies on being able to call
            # e.g. ``pyramid.chameleon_zpt.render_template``
            # without registering a .pt renderer, expecting the "real"
            # template to be rendered.  This is a holdover from when
            # individual template system renderers weren't indirected
            # by the ``pyramid.renderers`` machinery, and
            # ``render_template`` and friends went behind the back of
            # any existing renderer factory lookup system.
            config.add_renderer(name, renderer)
    config.commit()
    hook_zca and config.hook_zca()
    config.begin(request=request)
    return config
开发者ID:jkrebs,项目名称:pyramid,代码行数:93,代码来源:testing.py

示例15: main

# 需要导入模块: from pyramid.config import Configurator [as 别名]
# 或者: from pyramid.config.Configurator import hook_zca [as 别名]
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.hook_zca()
    config.include('pyramid_zcml')
    config.load_zcml('pysiphae:configure.zcml')
    config.include('pyramid_chameleon')
    config.include('pyramid_viewgroup')

    sessionfactory = SignedCookieSessionFactory(uuid.uuid4().hex)

    config.set_session_factory(sessionfactory)

    pconfig = yaml.load(
            open(settings.get('pysiphae.config')).read())
    config.registry.settings['pysiphae'] = pconfig
    default_permission = pconfig.get('default_permission', None)
    if default_permission:
        config.set_default_permission(default_permission)
    config.set_root_factory(root_factory)

    # register process managers
    processmgrs = pconfig.get('processmanagers', [])
    if not processmgrs:
        processmgrs.append({'name': 'defaut', 
                            'address': 'http://localhost:8888'})

    for pm in processmgrs:
        name = pm['name']
        address = pm['address']
        if name == 'default':
            config.registry.registerUtility(ProcessManager(address))
        else:
            config.registry.registerUtility(ProcessManager(address), name=name)

    # viewgroups
    for vg in pconfig.get('viewgroups', []):
        vg['context'] = vg.get('context', 'pysiphae.interfaces.ISiteRoot')
        config.add_viewgroup(**vg)

    config.add_static_view('++static++', 'static', cache_max_age=3600)
    config.add_request_method(requestmethods.main_template, 'main_template', reify=True)
    config.add_request_method(requestmethods.vars, 'template_vars', property=True)
    config.add_request_method(requestmethods.main_navigation, 'main_navigation',
            property=True)
    config.add_request_method(requestmethods.viewgroup_provider, 'provider',
            property=True)
    config.add_request_method(requestmethods.pconfig, 'pconfig', property=True)
    config.add_route('home','/')
    config.add_route('login','/login')
    config.add_route('logout','/logout')
    config.scan()

    plugins = pconfig.get('plugins', [])
    for plugin in plugins:
        package = config.maybe_dotted(plugin)
        if getattr(package, 'configure', None):
            package.configure(config, settings)
        config.load_zcml(plugin + ':configure.zcml')
        config.scan(plugin)

    return config.make_wsgi_app()
开发者ID:koslab,项目名称:pysiphae,代码行数:65,代码来源:wsgi.py


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