Python pyramid.config.Configurator() Examples

The following are 30 code examples of pyramid.config.Configurator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyramid.config , or try the search function .
Example #1
Source File: app.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def main(global_config, **settings):
    """This function returns a Pyramid WSGI application."""

    settings['SOFTWARE_VERSION'] = __VERSION__

    config = Configurator(settings=settings)

    # Addons
    config.include('pyramid_jinja2')
    # http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/#adding-or-overriding-a-renderer
    config.add_jinja2_renderer('.html')
    config.include('cornice')

    # Views and routes
    config.add_static_view('static/app', 'static/app', cache_max_age=0)
    config.add_static_view('static/lib', 'static/lib', cache_max_age=60 * 24)
    config.add_route('index', '/')

    config.scan()

    return config.make_wsgi_app() 
Example #2
Source File: __init__.py    From pyramid_openapi3 with MIT License 6 votes vote down vote up
def includeme(config: Configurator) -> None:
    """Pyramid knob."""
    config.add_view_deriver(openapi_view)
    config.add_directive("pyramid_openapi3_add_formatter", add_formatter)
    config.add_directive("pyramid_openapi3_add_explorer", add_explorer_view)
    config.add_directive("pyramid_openapi3_spec", add_spec_view)
    config.add_tween("pyramid_openapi3.tween.response_tween_factory", over=EXCVIEW)

    if not config.registry.settings.get(  # pragma: no branch
        "pyramid_openapi3_extract_errors"
    ):
        config.registry.settings["pyramid_openapi3_extract_errors"] = extract_errors

    config.add_exception_view(
        view=openapi_validation_error, context=RequestValidationError, renderer="json"
    )

    config.add_exception_view(
        view=openapi_validation_error, context=ResponseValidationError, renderer="json"
    ) 
Example #3
Source File: __init__.py    From pyramid_zipkin with Apache License 2.0 6 votes vote down vote up
def main(global_config, **settings):
    """ Very basic pyramid app """
    settings['service_name'] = 'acceptance_service'
    settings['zipkin.transport_handler'] = lambda x, y: None
    settings['zipkin.encoding'] = Encoding.V2_JSON

    config = Configurator(settings=settings)

    config.add_route('sample_route', '/sample')
    config.add_route('sample_route_v2', '/sample_v2')
    config.add_route('sample_route_v2_client', '/sample_v2_client')
    config.add_route('sample_route_child_span', '/sample_child_span')
    config.add_route('span_context', '/span_context')
    config.add_route('decorator_context', '/decorator_context')
    config.add_route('pattern_route', '/pet/{petId}')

    config.add_route('server_error', '/server_error')
    config.add_route('client_error', '/client_error')

    config.scan()

    config.add_tween('pyramid_zipkin.tween.zipkin_tween', over=EXCVIEW)

    return config.make_wsgi_app() 
Example #4
Source File: test_integration.py    From pyramid_jwt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_pyramid_custom_json_encoder(app_config: Configurator):
    """Test we can still use user-defined custom adapter"""
    from pyramid.renderers import json_renderer_factory

    def serialize_anyclass(obj, request):
        assert False  # This asserts this method will not be called

    json_renderer_factory.add_adapter(NonSerializable, serialize_anyclass)

    def other_serializer(obj, request):
        return "other_serializer"

    my_renderer = JSON()
    my_renderer.add_adapter(NonSerializable, other_serializer)
    app_config.add_renderer("json", my_renderer)
    app = TestApp(app_config.make_wsgi_app())

    response = app.get("/extra_claims")
    token = str(response.json_body["token"])

    response = app.get("/dump_claims", headers={"X-Token": token})
    assert response.json_body["extra_claim"] == "other_serializer" 
Example #5
Source File: test_extract_errors.py    From pyramid_openapi3 with MIT License 6 votes vote down vote up
def _testapp(self) -> TestApp:
        """Start up the app so that tests can send requests to it."""
        from webtest import TestApp

        with tempfile.NamedTemporaryFile() as document:
            document.write(self.OPENAPI_YAML.encode())
            document.seek(0)

            with Configurator() as config:
                config.include("pyramid_openapi3")
                config.pyramid_openapi3_spec(document.name)
                config.pyramid_openapi3_add_formatter("unique-name", self.UniqueName())
                config.add_route("hello", "/hello")
                config.add_view(
                    openapi=True, renderer="json", view=self.hello, route_name="hello"
                )
                app = config.make_wsgi_app()

            return TestApp(app) 
Example #6
Source File: test_integration.py    From pyramid_jwt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def base_config() -> Configurator:
    config = Configurator()
    config.set_authorization_policy(ACLAuthorizationPolicy())

    config.include("pyramid_jwt")
    config.set_root_factory(Root)
    config.add_route("secure", "/secure")
    config.add_view(
        secure_view, route_name="secure", renderer="string", permission="read"
    )
    config.add_route("extra_claims", "/extra_claims")
    config.add_view(extra_claims, route_name="extra_claims", renderer="json")
    config.add_route("dump_claims", "/dump_claims")
    config.add_view(
        dump_claims, route_name="dump_claims", renderer="json", permission="read"
    )
    return config 
Example #7
Source File: webapp.py    From mycroft with MIT License 6 votes vote down vote up
def _create_application():
    """Create the WSGI application, post-fork."""
    mycroft.config.load_staticconf()
    # Initialize configs at the early stage to avoid repeated calculation at runtime.
    mycroft.config.init()

    # Create a basic pyramid Configurator.
    config = Configurator(settings={
        'service_name': 'mycroft',
    })

    # Add the service's custom configuration, routes, etc.
    config.include(mycroft.config.routes)
    config.include(mycroft.config.swagger_views)
    config.include(mycroft.config.renderers)

    config.add_route('status.healthcheck', '/status/healthcheck')

    # Display metrics on the '/status/metrics' endpoint
    # config.include(pyramid_uwsgi_metrics)

    # Scan the service package to attach any decorated views.
    config.scan('mycroft')

    return config.make_wsgi_app() 
Example #8
Source File: includeme_test.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_disable_api_doc_views(_1, _2, mock_register):
    settings = {
        'pyramid_swagger.enable_api_doc_views': False,
        'pyramid_swagger.enable_swagger_spec_validation': False,
    }

    mock_config = mock.Mock(
        spec=Configurator,
        registry=mock.Mock(spec=Registry, settings=settings))

    pyramid_swagger.includeme(mock_config)
    assert not mock_register.called 
Example #9
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.include('pyramid_mako')
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app() 
Example #10
Source File: __init__.py    From consuming_services_python_demos with MIT License 5 votes vote down vote up
def main(_, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    register_includes(config)
    register_json_renderer(config)
    register_routes(config)

    config.scan()
    return config.make_wsgi_app() 
Example #11
Source File: macauth_demo.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    """Construct and return a WSGI app for the luckynumber service."""

    settings = {
      # The pyramid_persona plugin needs a master secret to use for
      # signing login cookies, and the expected hostname of your website
      # to prevent fradulent login attempts.
      "persona.secret": "TED KOPPEL IS A ROBOT",
      "persona.audiences": "localhost:8080",

      # The pyramid_macauth plugin needs a master secret to use for signing
      # its access tokens.  We could use the same secret as above, but it's
      # generally a good idea to use different secrets for different things.
      "macauth.master_secret": "V8 JUICE IS 1/8TH GASOLINE",

      # The pyramid_multiauth plugin needs to be told what sub-policies to
      # load, and the order in which they should be tried.
      "multiauth.policies": "pyramid_persona pyramid_macauth",
    }

    config = Configurator(settings=settings)
    config.add_route("number", "/")
    config.add_view(lucky_number, route_name="number")

    # Including pyramid_multiauth magically enables authentication, loading
    # both of the policies we specified in the settings.
    config.include("pyramid_multiauth")

    # Both of our chosen policies configure a "forbidden view" to handle
    # unauthenticated access.  We have to resolve this conflict by explicitly
    # picking which one we want to use.
    config.add_forbidden_view("pyramid_persona.views.forbidden")

    config.add_route("provision", "/provision")
    config.add_view(provision_creds, route_name="provision", renderer="json")

    return config.make_wsgi_app() 
Example #12
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

    authn_policy = AuthTktAuthenticationPolicy(
        'secret', callback=groupfinder, hashalg='sha512'
    )
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(settings=settings, root_factory='myshop.RootFactory')
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    config.set_request_property(get_user, 'user', reify=True)
    config.set_request_property(lambda request: DBSession, 'db', reify=True)

    config.include('pyramid_chameleon')

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('category', '/category/{id}')
    config.add_route('item', '/item/{id}')
    config.add_route('search', '/search')
    config.add_route('annoncement', '/annoncement/{id}')

    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('register', '/register')

    config.add_route('order', '/order')
    config.add_route('cart', '/cart')
    config.add_route('comment', '/comment')

    config.add_route('add_item', '/category/{id}/add')

    config.scan()
    return config.make_wsgi_app() 
Example #13
Source File: includeme_test.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bad_schema_not_validated_if_spec_validation_is_disabled(_):
    settings = {
        'pyramid_swagger.schema_directory': 'tests/sample_schemas/bad_app/',
        'pyramid_swagger.enable_swagger_spec_validation': False,
        'pyramid_swagger.enable_api_doc_views': False,
    }
    mock_config = mock.Mock(
        spec=Configurator, registry=mock.Mock(settings=settings))
    pyramid_swagger.includeme(mock_config) 
Example #14
Source File: response_test.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_registry(settings):
    registry = Registry('testing')
    config = Configurator(registry=registry)
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    registry.registerUtility(RoutesMapper(), IRoutesMapper)
    config.commit()
    return registry 
Example #15
Source File: __init__.py    From pyramid_swagger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(global_config, **settings):
    """ Very basic pyramid app """
    config = Configurator(settings=settings)

    config.include('pyramid_swagger')

    config.add_route(
        'sample_nonstring',
        '/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}',
    )
    config.add_route('standard', '/sample/{path_arg}/resource')
    config.add_route('get_with_non_string_query_args', '/get_with_non_string_query_args')
    config.add_route('post_with_primitive_body', '/post_with_primitive_body')
    config.add_route('post_with_form_params', '/post_with_form_params')
    config.add_route('post_with_file_upload', '/post_with_file_upload')
    config.add_route('sample_post', '/sample')
    config.include(include_samples, route_prefix='/sample')
    config.add_route('throw_400', '/throw_400')
    config.add_route('swagger_undefined', '/undefined/path')

    config.add_route('echo_date', '/echo_date')
    config.add_route('echo_date_json_renderer', '/echo_date_json_renderer')
    config.add_route('post_endpoint_with_optional_body', '/post_endpoint_with_optional_body')

    config.scan()
    return config.make_wsgi_app() 
Example #16
Source File: __init__.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def quick_serve(sql_session_factory=None, port=8080):
    """Start a HTTP server for your REST service.

    This function provides quick way to run a webserver for your REST service.
    The webserver will listen on port 8080 on all IP addresses of the local
    machine.

    If you need to configure the underlying Pyramid system, or you want to use
    a different HTTP server you will need to create the WSGI application
    yourself. Instead of using `quick_serve` you will need to do something like
    this:

    .. code-block:: python
       :linenos:

       from pyramid.config import Configurator
       from wsgiref.simple_server import make_server

       config = Configurator()
       config.include('rest_toolkit')
       config.scan()
       app = config.make_wsgi_app()
       make_server('0.0.0.0', 8080, app).serve_forever()

    :param sql_session_factory: A factory function to return a SQLAlchemy
        session. This is generally a :py:class:`scoped_session
        <sqlalchemy:sqlalchemy.orm.session.scoped_session>` instance, and
        commonly called ``Session`` or ``DBSession``.
    :param int port: TCP port to use for HTTP server.
    """
    config = Configurator()
    config.include('rest_toolkit')
    if sql_session_factory is not None:
        config.include('rest_toolkit.ext.sql')
        config.set_sqlalchemy_session_factory(sql_session_factory)
    pkg = caller_package()
    config.add_static_view('static', package_path(pkg))
    config.scan(pkg)
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', port, app)
    server.serve_forever() 
Example #17
Source File: test_error.py    From rest_toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_resource_constructor_exception():
    config = Configurator()
    config.include('rest_toolkit')
    config.scan('resource_error')
    app = make_app(config)
    r = app.get('/keyerror', status=500)
    assert r.content_type == 'application/json'
    assert set(r.json) == {'message'}
    assert r.json['message'] == 'BOOM!'
    assert 'traceback' not in r.json 
Example #18
Source File: wsgi_app.py    From channelstream with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_app(server_config):
    config = Configurator(
        settings=server_config, root_factory=APIFactory, default_permission="access"
    )
    config.include("pyramid_jinja2")
    module_, class_ = server_config["signature_checker"].rsplit(".", maxsplit=1)
    signature_checker_cls = getattr(importlib.import_module(module_), class_)
    config.registry.signature_checker = signature_checker_cls(server_config["secret"])
    authn_policy = AuthTktAuthenticationPolicy(
        server_config["cookie_secret"], max_age=2592000
    )
    authz_policy = ACLAuthorizationPolicy()

    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    json_renderer = JSON(serializer=json.dumps, indent=4)
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(uuid.UUID, uuid_adapter)
    config.add_renderer("json", json_renderer)

    config.add_subscriber(
        "channelstream.subscribers.handle_new_request", "pyramid.events.NewRequest"
    )
    config.add_request_method("channelstream.utils.handle_cors", "handle_cors")
    config.include("channelstream.wsgi_views")
    config.scan("channelstream.wsgi_views.server")
    config.scan("channelstream.wsgi_views.error_handlers")
    config.scan("channelstream.events")

    config.include("pyramid_apispec.views")
    config.pyramid_apispec_add_explorer(
        spec_route_name="openapi_spec",
        script_generator="channelstream.utils:swagger_ui_script_template",
        permission="admin",
        route_args={
            "factory": "channelstream.wsgi_views.wsgi_security:AdminAuthFactory"
        },
    )
    app = config.make_wsgi_app()
    return app 
Example #19
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app() 
Example #20
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app() 
Example #21
Source File: app.py    From pyramid_openapi3 with MIT License 5 votes vote down vote up
def app(spec):
    """Prepare a Pyramid app."""
    with Configurator() as config:
        config.include("pyramid_openapi3")
        config.pyramid_openapi3_spec(spec)
        config.pyramid_openapi3_add_explorer()
        config.add_route("hello", "/hello")
        config.scan(".")
        return config.make_wsgi_app() 
Example #22
Source File: test_integration.py    From pyramid_jwt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def app_config(base_config) -> Configurator:
    base_config.add_route("login", "/login")
    base_config.add_view(login_view, route_name="login", renderer="json")

    # Enable JWT authentication.
    base_config.set_jwt_authentication_policy("secret", http_header="X-Token")
    return base_config 
Example #23
Source File: webapp.py    From google-cloud-python-expenses-demo with Apache License 2.0 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    initialize_gcloud()
    config = Configurator(settings=settings)
    config.add_request_method(_get_create_bucket, 'bucket', reify=True)
    config.include('pyramid_chameleon')
    config.include('.views')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('employees', '/employees/')
    config.add_route('employee', '/employees/{employee_id}')
    config.add_route('report', '/employees/{employee_id}/{report_id}')
    config.scan()
    return config.make_wsgi_app() 
Example #24
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    init_includes(config)
    init_db(config)
    init_routing(config)

    return config.make_wsgi_app() 
Example #25
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    init_includes(config)
    init_db(config)
    init_routing(config)

    return config.make_wsgi_app() 
Example #26
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('about', '/about')
    config.scan()
    return config.make_wsgi_app() 
Example #27
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app() 
Example #28
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    init_includes(config)
    init_db(config)
    init_routing(config)

    return config.make_wsgi_app() 
Example #29
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    init_includes(config)
    init_db(config)
    init_routing(config)

    return config.make_wsgi_app() 
Example #30
Source File: __init__.py    From data-driven-web-apps-with-pyramid-and-sqlalchemy with MIT License 5 votes vote down vote up
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    init_includes(config)
    init_db(config)
    init_routing(config)

    return config.make_wsgi_app()