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

    # Database
    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    birda.models.DBSession.configure(bind=engine)

    # Authentication / Authorization
    session_factory = pyramid.session.UnencryptedCookieSessionFactoryConfig(
        settings['session.secret'])

    authn_policy = pyramid.authentication.SessionAuthenticationPolicy()
    authz_policy = pyramid.authorization.ACLAuthorizationPolicy()

    # Config creation
    config = pyramid.config.Configurator(
        settings=settings,
        root_factory=birda.models.acl.RootFactory,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
        session_factory=session_factory)

    # Disabling exception logger in order to avoid conflicts with cornice
    # (exc_logger will be removed in .ini sometime in the future...)
    config.add_settings(handle_exceptions=False)

    # Tailorization of default pyramid json renderer
    config.add_renderer('json', define_json_renderer(settings))

    # Scan modules for cornice services
    #config.include("birda.services")
    config.include('cornice')
    config.scan("birda.services")

    # Add non JSON API routes
    birda.views.add_routes(config)
    config.scan()

    # Import all birda.models modules (necessary?)
    #config.scan('birda.models')

    config.add_subscriber(add_cors_headers_response_callback,
                          pyramid.events.NewRequest)

    # Activate and set application wide services (singletons)
    forms_factory = FormsFactory(settings)
    individuals_factory = IndividualsFactory(settings, forms_factory)

    config.include('pyramid_services')
    config.register_service(forms_factory,
                            iface=IFormsFactory,
                            name='FormsFactory')
    config.register_service(individuals_factory,
                            iface=IIndividualsFactory,
                            name='IndividualsFactory')

    # Make and run the application
    return config.make_wsgi_app()
Beispiel #2
0
def main(global_config, **settings):
    # Parse our couchdb secrets
    with open(settings['tractdb_couchdb_secrets']) as f:
        config = yaml.safe_load(f)
    settings['tractdb_couchdb_secrets'] = config

    # Parse our pyramid secrets
    with open(settings['tractdb_pyramid_secrets']) as f:
        config = yaml.safe_load(f)
    settings['tractdb_pyramid_secrets'] = config

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    pyramid_secret = settings['tractdb_pyramid_secrets']['pyramid_secret']

    # Authentication and Authorization
    pyramid_secret = settings['tractdb_pyramid_secrets']['authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512'
    )
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.include('cornice')
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
Beispiel #3
0
def main(global_config, **settings):
    """Return a Pyramid WSGI application."""

    settings.setdefault('mako.directories', 'porygo_nz:templates')

    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    porygo_nz.db.DBSession.configure(bind=engine)

    config = pyramid.config.Configurator(
        settings=settings, root_factory=porygo_nz.resources.get_root)

    config.include('pyramid_mako')

    config.add_static_view('static', 'porygo_nz:static')

    config.add_request_method(porygo_nz.db.request_session,
                              name='db',
                              reify=True)
    config.add_request_method(porygo_nz.request_methods.show_abilities,
                              reify=True)
    config.add_request_method(porygo_nz.request_methods.show_hidden_abilities,
                              reify=True)

    config.scan()

    return config.make_wsgi_app()
def main(global_config, **settings):
    # Keys that start with secrets need to be loaded from file
    settings['secrets'] = {}
    secrets = [key_original for key_original in settings.keys() if key_original.startswith('secrets.')]
    for key_original in secrets:
        path = settings[key_original]
        key = key_original[len('secrets.'):]

        with open(settings[key_original]) as f:
            config = yaml.safe_load(f)
        settings['secrets'][key] = config

        del settings[key_original]

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    # Authentication and Authorization
    pyramid_secret = settings['secrets']['pyramid']['authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512'
    )
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
Beispiel #5
0
def main(global_config, **settings):
	"""
	This function returns a Pyramid WSGI application.
	"""

	# Database
	engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
	birda.models.DBSession.configure(bind=engine)

	# Authentication / Authorization
	session_factory = pyramid.session.UnencryptedCookieSessionFactoryConfig(
		settings['session.secret']
	)

	authn_policy = pyramid.authentication.SessionAuthenticationPolicy()
	authz_policy = pyramid.authorization.ACLAuthorizationPolicy()

	# Config creation
	config = pyramid.config.Configurator(
		settings=settings,
		root_factory=birda.models.acl.RootFactory,
		authentication_policy=authn_policy,
		authorization_policy=authz_policy,
		session_factory=session_factory
	)

	# Disabling exception logger in order to avoid conflicts with cornice
	# (exc_logger will be removed in .ini sometime in the future...)
	config.add_settings(handle_exceptions=False)
	
	# Tailorization of default pyramid json renderer
	config.add_renderer('json', define_json_renderer(settings))	
	
	# Scan modules for cornice services
	#config.include("birda.services")
	config.include('cornice')
	config.scan("birda.services")

	# Add non JSON API routes
	birda.views.add_routes(config)
	config.scan()

	# Import all birda.models modules (necessary?)
	#config.scan('birda.models')

	config.add_subscriber(add_cors_headers_response_callback, pyramid.events.NewRequest)
	
	# Activate and set application wide services (singletons)
	forms_factory = FormsFactory(settings)
	individuals_factory = IndividualsFactory(settings, forms_factory)
	
	config.include('pyramid_services')
	config.register_service(forms_factory, iface=IFormsFactory, name='FormsFactory')
	config.register_service(individuals_factory, iface=IIndividualsFactory, name='IndividualsFactory')

	# Make and run the application
	return config.make_wsgi_app()
Beispiel #6
0
def main(global_config, **settings):
    config = pyramid.config.Configurator(settings=settings)
    config.add_static_view('static', os.path.join(here, 'static'))
    config.add_route('home', '/')
    config.add_route('away_mode', '/away_mode')
    config.add_route('status', '/status')
    config.scan()
    app = config.make_wsgi_app()
    return app
Beispiel #7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = pyramid.config.Configurator(settings=settings)
    # Add JSON as default renderer
    config.add_renderer(None, renderers.JSON())
    config.include('pyramid_jwt')
    config.include('.security')
    config.include('.models')
    config.include('.resources')
    config.scan()
    return config.make_wsgi_app()
Beispiel #8
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    model.setup()

    session_factory = session_factory_from_settings(settings)
    
    config = Configurator(
        settings=settings,
        root_factory=security.RootFactory,
        authentication_policy=AuthTktAuthenticationPolicy(
            settings["cookie_secret"],
            callback=security.group_finder),
        authorization_policy=ACLAuthorizationPolicy())

    config.set_request_factory(security.RequestWithUserAttribute)
    config.set_session_factory(session_factory)
    config.add_static_view("static", "scrobble:static")
    config.add_route("home", "/",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("new_account", "/new_account",
                     view="scrobble.login.new_account",
                     view_renderer="new_account.mako")
    config.add_route("login", "/login",
                     view="scrobble.login.login")
    config.add_route("logout", "/logout",
                     view="scrobble.login.logout",
                     view_renderer="logout.mako")
    config.add_route("list_users", "/users",
                     view="scrobble.views.list_users",
                     view_renderer="list_users.mako")
    config.add_route("user_home", "/user/{user}",
                     view="scrobble.views.user_home",
                     view_renderer="user_home.mako")

    
    config.add_route("simulate_listen", "/simulate_listen",
                     view="scrobble.views.simulate_listen",
                     view_renderer="simulate.mako")

    config.add_route("api_login", "api/login")
    config.add_route("api_whoami", "api/whoami")
    config.add_route("api_track_listen", "api/track_listen")
    config.add_route("api_follow_user", "api/follow_user")
    config.add_route("api_unfollow_user", "api/unfollow_user")
    config.scan()
    return config.make_wsgi_app()
Beispiel #9
0
    def test_scan_integration_dottedname_package(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response

        config = self._makeOne(autocommit=True)
        config.scan('tests.test_config.pkgs.scannable')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')
Beispiel #10
0
    def test_scan_integration_dottedname_package(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response

        config = self._makeOne(autocommit=True)
        config.scan('tests.test_config.pkgs.scannable')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')
def main(global_config, **settings):
    settings.setdefault("jinja2.filters", "")
    settings["jinja2.filters"] += "\n".join([
        "",
        "to_json = asp.app:to_json_filter",
    ])

    config = pyramid.config.Configurator(settings=settings)
    config.registry.games = {}
    config.registry.texts = json.loads(
        pkg_resources.resource_string(__name__, "texts.json")
    )
    config.include("asp.www.home")
    config.scan("asp.www")

    return config.make_wsgi_app()
Beispiel #12
0
    def configure(self):
        super(Portal, self).configure()
        self.configure_zca()

        mimetypes.add_type('application/font-woff', '.woff')
        mimetypes.add_type('application/x-font-ttf', '.ttf')

        registry = pyramid.registry.Registry(
            bases=(zope.component.getGlobalSiteManager(),))
        if self.settings.get('sentry.dsn', None):
            version = sw.allotmentclub.version.__version__
            sentry_sdk.init(
                release=f"sw-allotmentclub-backend@{version}",
                dsn=self.settings['sentry.dsn'],
                integrations=[PyramidIntegration(), SqlalchemyIntegration()])
        self.config = config = pyramid.config.Configurator(
            settings=self.settings,
            registry=registry)
        config.setup_registry(settings=self.settings)
        config.include('pyramid_beaker')
        config.include('pyramid_exclog')
        config.include('pyramid_tm')

        if self.testing:
            config.include('pyramid_mailer.testing')
        elif config.registry.settings.get('mail.enable') == 'false':
            config.include('sw.allotmentclub.printmailer')
        else:
            config.include('sw.allotmentclub.logmailer')

        # self.add_csrf_check()

        config.add_renderer(
            'json', risclog.sqlalchemy.serializer.json_renderer_factory(
                serializer=json_serializer))

        config.set_default_permission('view')
        config.set_authentication_policy(SessionAuthenticationPolicy())
        config.set_authorization_policy(ACLAuthorizationPolicy())
        config.set_root_factory(
            sw.allotmentclub.browser.auth.get_default_context)
        config.add_request_method(
            sw.allotmentclub.browser.auth.get_user, 'user', property=True)

        self.add_routes()
        config.scan(package=sw.allotmentclub.browser,
                    ignore=sw.allotmentclub.SCAN_IGNORE_TESTS)
Beispiel #13
0
def includeme(config):
    """Set up standard configurator registrations.  Use via:

    .. code-block:: python

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

    """
    config.set_request_property(request.add_stripe_event, "stripe", reify=True)
    config.set_request_property(request.add_stripe_event_raw,
                                "stripe_raw",
                                reify=True)
    config.include(add_routes)
    config.scan("pyramid_stripe.views")

    if not stripe.api_key:
        stripe.api_key = config.get_settings()["stripe.api_key"]
Beispiel #14
0
def includeme(config):
    """Set up standard configurator registrations.  Use via:

    .. code-block:: python

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

    """
    config.set_request_property(request.add_stripe_event, "stripe",
                                reify=True)
    config.set_request_property(request.add_stripe_event_raw, "stripe_raw",
                                reify=True)
    config.include(add_routes)
    config.scan("pyramid_stripe.views")

    if not stripe.api_key:
        stripe.api_key = config.get_settings()["stripe.api_key"]
Beispiel #15
0
    def test_scan_integration_with_ignore(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response
        import tests.test_config.pkgs.scannable as package

        config = self._makeOne(autocommit=True)
        config.scan(package, ignore='tests.test_config.pkgs.scannable.another')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')

        # ignored
        v = render_view_to_response(ctx, req, 'another_stacked_class2')
        self.assertEqual(v, None)
Beispiel #16
0
    def test_scan_integration_with_ignore(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response
        import tests.test_config.pkgs.scannable as package

        config = self._makeOne(autocommit=True)
        config.scan(package, ignore='tests.test_config.pkgs.scannable.another')

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')

        # ignored
        v = render_view_to_response(ctx, req, 'another_stacked_class2')
        self.assertEqual(v, None)
Beispiel #17
0
def server_start(arguments):
    try:
        __configure_logging(arguments)
        with pyramid.config.Configurator() as config:
            __discover_routes(config)
            # configure exception_view_config
            config.scan()
            app = config.make_wsgi_app()

        logger.info('Start server')
        server = wsgiref.simple_server.make_server(
            IP_ADDRESS,
            arguments.port,
            app,
            handler_class=LoggingWSGIRequestHandler,
        )
        State.get_instance().server = server
        logger.info('Accept requests')
        server.serve_forever()
    except Exception:
        logger.exception('Error starting server')
Beispiel #18
0
def getPyramidConfigurator(is_dev_server=False):
    """
    Get a pre-configurated Pyramid WSGI application.
    """
    # Configure and create the WSGI application.
    config = pyramid.config.Configurator(authentication_policy=CustomAuthPolicy())

    # Configuration settings.
    settings = dict()

    if is_dev_server:
        settings['pyramid.reload_templates'] = True

    config.add_settings(settings)

    # Include additional pyramid modules.
    config.include('pyramid_jinja2')

    # Scan the code for view declarations.
    config.scan(local)

    # Setup the views.
    config.add_route('index', '/')
    config.add_route('view.create_user', pattern='/users/create')
    config.add_route('view.search_users', pattern='/users/search')
    config.add_route('view.display_user', pattern='/users/{user_uid}')
    config.add_route('view.display_battles', pattern='/battles')

    # Setup the APIs.
    config.add_route('api.create_user', pattern='/api/users')
    config.add_route('api.modify_user', pattern='/api/users/{user_uid}')
    config.add_route('api.create_battle_log', pattern='/api/battles')
    config.add_route('api.list_users', pattern='/api/list_users')

    # Add static views
    config.add_static_view("styles", "local:site/styles/")

    return config
def main(global_config, **settings):
    # Keys that start with secrets need to be loaded from file
    settings['secrets'] = {}
    secrets = [
        key_original for key_original in settings.keys()
        if key_original.startswith('secrets.')
    ]
    for key_original in secrets:
        path = settings[key_original]
        key = key_original[len('secrets.'):]

        with open(settings[key_original]) as f:
            config = yaml.safe_load(f)
        settings['secrets'][key] = config

        del settings[key_original]

    # Configure our pyramid app
    config = pyramid.config.Configurator(settings=settings)

    # Authentication and Authorization
    pyramid_secret = settings['secrets']['pyramid'][
        'authtktauthenticationpolicy_secret']
    policy_authentication = pyramid.authentication.AuthTktAuthenticationPolicy(
        pyramid_secret, hashalg='sha512')
    policy_authorization = pyramid.authorization.ACLAuthorizationPolicy()

    config.set_authentication_policy(policy_authentication)
    config.set_authorization_policy(policy_authorization)

    # Application views
    config.scan('tractdb_pyramid.views')

    # Make the app
    app = config.make_wsgi_app()

    return app
Beispiel #20
0
def init_wsgi_app() -> pyramid.router.Router:
    config = pyramid.config.Configurator(
        settings={
            'pyramid.includes': [
                'pyramid_jinja2',
                'pyramid_tm',
            ],
            'pyramid.reload_templates': True,
        })
    init_json_renderer(config)

    for name, path, method in [
        ('index', "/", 'GET'),
        ('api_create_step', "/api/steps", 'POST'),
        ('api_get_step', "/api/steps/{step_id:\d+}", 'GET'),
        ('api_update_step', "/api/steps/{step_id:\d+}", 'PUT'),
    ]:
        config.add_route(name, path, request_method=method)
    config.scan()

    config.add_static_view('static', '../static', cache_max_age=1)
    config.commit()

    return config.make_wsgi_app()
Beispiel #21
0
def includeme(config: pyramid.config.Configurator) -> None:
    """
    This function returns a Pyramid WSGI application.
    """

    settings = config.get_settings()

    config.include("c2cgeoportal_commons")

    if "available_locale_names" not in settings:
        settings["available_locale_names"] = available_locale_names()

    call_hook(settings, "after_settings", settings)

    get_user_from_request = create_get_user_from_request(settings)
    config.add_request_method(get_user_from_request,
                              name="user",
                              property=True)
    config.add_request_method(get_user_from_request, name="get_user")

    # Configure 'locale' dir as the translation dir for c2cgeoportal app
    config.add_translation_dirs("c2cgeoportal_geoportal:locale/")

    config.include("c2cwsgiutils.pyramid.includeme")
    health_check = HealthCheck(config)
    config.registry["health_check"] = health_check

    metrics_config = config.registry.settings["metrics"]
    if metrics_config["memory_maps_rss"]:
        add_provider(MemoryMapProvider("rss"))
    if metrics_config["memory_maps_size"]:
        add_provider(MemoryMapProvider("size"))
    if metrics_config["memory_cache"]:
        add_provider(
            MemoryCacheSizeProvider(
                metrics_config.get("memory_cache_all", False)))
    if metrics_config["raster_data"]:
        add_provider(RasterDataSizeProvider())
    if metrics_config["total_python_object_memory"]:
        add_provider(TotalPythonObjectMemoryProvider())

    # Initialise DBSessions
    init_dbsessions(settings, config, health_check)

    checker.init(config, health_check)
    check_collector.init(config, health_check)

    # dogpile.cache configuration
    if "cache" in settings:
        register_backend("c2cgeoportal.hybrid",
                         "c2cgeoportal_geoportal.lib.caching",
                         "HybridRedisBackend")
        register_backend("c2cgeoportal.hybridsentinel",
                         "c2cgeoportal_geoportal.lib.caching",
                         "HybridRedisSentinelBackend")
        for name, cache_config in settings["cache"].items():
            caching.init_region(cache_config, name)

            @zope.event.classhandler.handler(InvalidateCacheEvent)
            def handle(event: InvalidateCacheEvent) -> None:  # pylint: disable=unused-variable
                del event
                caching.invalidate_region()
                if caching.MEMORY_CACHE_DICT:
                    caching.get_region("std").delete_multi(
                        caching.MEMORY_CACHE_DICT.keys())
                caching.MEMORY_CACHE_DICT.clear()

    # Register a tween to get back the cache buster path.
    if "cache_path" not in config.get_settings():
        config.get_settings()["cache_path"] = ["static"]
    config.add_tween(
        "c2cgeoportal_geoportal.lib.cacheversion.CachebusterTween")
    config.add_tween("c2cgeoportal_geoportal.lib.headers.HeadersTween")

    # Bind the mako renderer to other file extensions
    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")

    # Add the "geojson" renderer
    config.add_renderer("geojson", GeoJSON())

    # Add the "xsd" renderer
    config.add_renderer("xsd", XSD(include_foreign_keys=True))

    # Add the set_user_validator directive, and set a default user validator
    config.add_directive("set_user_validator", set_user_validator)
    config.set_user_validator(default_user_validator)

    config.add_route("dynamic", "/dynamic.json", request_method="GET")

    # Add routes to the mapserver proxy
    config.add_route_predicate("mapserverproxy", MapserverproxyRoutePredicate)
    config.add_route(
        "mapserverproxy",
        "/mapserv_proxy",
        mapserverproxy=True,
        pregenerator=C2CPregenerator(role=True),
        request_method="GET",
    )
    config.add_route(
        "mapserverproxy_post",
        "/mapserv_proxy",
        mapserverproxy=True,
        pregenerator=C2CPregenerator(role=True),
        request_method="POST",
    )
    add_cors_route(config, "/mapserv_proxy", "mapserver")

    # Add route to the tinyows proxy
    config.add_route("tinyowsproxy",
                     "/tinyows_proxy",
                     pregenerator=C2CPregenerator(role=True))

    # Add routes to the entry view class
    config.add_route("base", "/", static=True)
    config.add_route("loginform", "/login.html", request_method="GET")
    add_cors_route(config, "/login", "login")
    config.add_route("login", "/login", request_method="POST")
    add_cors_route(config, "/logout", "login")
    config.add_route("logout", "/logout", request_method="GET")
    add_cors_route(config, "/loginchangepassword", "login")
    config.add_route("change_password",
                     "/loginchangepassword",
                     request_method="POST")
    add_cors_route(config, "/loginresetpassword", "login")
    config.add_route("loginresetpassword",
                     "/loginresetpassword",
                     request_method="POST")
    add_cors_route(config, "/loginuser", "login")
    config.add_route("loginuser", "/loginuser", request_method="GET")
    config.add_route("testi18n", "/testi18n.html", request_method="GET")

    config.add_renderer(".map", AssetRendererFactory)
    config.add_renderer(".css", AssetRendererFactory)
    config.add_renderer(".ico", AssetRendererFactory)
    config.add_route("localejson", "/locale.json", request_method="GET")

    def add_static_route(name: str, attr: str, path: str,
                         renderer: str) -> None:
        config.add_route(name, path, request_method="GET")
        config.add_view(Entry, attr=attr, route_name=name, renderer=renderer)

    add_static_route("favicon", "favicon", "/favicon.ico",
                     "/etc/geomapfish/static/images/favicon.ico")
    add_static_route("robot.txt", "robot_txt", "/robot.txt",
                     "/etc/geomapfish/static/robot.txt")
    add_static_route("apijs", "apijs", "/api.js", "/etc/static-ngeo/api.js")
    add_static_route("apijsmap", "apijsmap", "/api.js.map",
                     "/etc/static-ngeo/api.js.map")
    add_static_route("apicss", "apicss", "/api.css",
                     "/etc/static-ngeo/api.css")
    add_static_route("apihelp", "apihelp", "/apihelp/index.html",
                     "/etc/geomapfish/static/apihelp/index.html")
    c2cgeoportal_geoportal.views.add_redirect(config, "apihelp_redirect",
                                              "/apihelp.html", "apihelp")

    config.add_route("themes",
                     "/themes",
                     request_method="GET",
                     pregenerator=C2CPregenerator(role=True))

    config.add_route("invalidate", "/invalidate", request_method="GET")

    # Print proxy routes
    config.add_route("printproxy", "/printproxy", request_method="HEAD")
    add_cors_route(config, "/printproxy/*all", "print")
    config.add_route(
        "printproxy_capabilities",
        "/printproxy/capabilities.json",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route(
        "printproxy_report_create",
        "/printproxy/report.{format}",
        request_method="POST",
        header=JSON_CONTENT_TYPE,
    )
    config.add_route("printproxy_status",
                     "/printproxy/status/{ref}.json",
                     request_method="GET")
    config.add_route("printproxy_cancel",
                     "/printproxy/cancel/{ref}",
                     request_method="DELETE")
    config.add_route("printproxy_report_get",
                     "/printproxy/report/{ref}",
                     request_method="GET")

    # Full-text search routes
    add_cors_route(config, "/search", "fulltextsearch")
    config.add_route("fulltextsearch", "/search", request_method="GET")

    # Access to raster data
    add_cors_route(config, "/raster", "raster")
    config.add_route("raster", "/raster", request_method="GET")

    add_cors_route(config, "/profile.json", "profile")
    config.add_route("profile.json", "/profile.json", request_method="POST")

    # Shortener
    add_cors_route(config, "/short/create", "shortener")
    config.add_route("shortener_create",
                     "/short/create",
                     request_method="POST")
    config.add_route("shortener_get", "/s/{ref}", request_method="GET")

    # Geometry processing
    config.add_route("difference", "/difference", request_method="POST")

    # PDF report tool
    config.add_route("pdfreport",
                     "/pdfreport/{layername}/{ids}",
                     request_method="GET")

    # Add routes for the "layers" web service
    add_cors_route(config, "/layers/*all", "layers")
    config.add_route("layers_count",
                     "/layers/{layer_id:\\d+}/count",
                     request_method="GET")
    config.add_route(
        "layers_metadata",
        "/layers/{layer_id:\\d+}/md.xsd",
        request_method="GET",
        pregenerator=C2CPregenerator(role=True),
    )
    config.add_route("layers_read_many",
                     "/layers/{layer_id:\\d+,?(\\d+,)*\\d*$}",
                     request_method="GET")  # supports URLs like /layers/1,2,3
    config.add_route("layers_read_one",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="GET")
    config.add_route("layers_create",
                     "/layers/{layer_id:\\d+}",
                     request_method="POST",
                     header=GEOJSON_CONTENT_TYPE)
    config.add_route(
        "layers_update",
        "/layers/{layer_id:\\d+}/{feature_id}",
        request_method="PUT",
        header=GEOJSON_CONTENT_TYPE,
    )
    config.add_route("layers_delete",
                     "/layers/{layer_id:\\d+}/{feature_id}",
                     request_method="DELETE")
    config.add_route(
        "layers_enumerate_attribute_values",
        "/layers/{layer_name}/values/{field_name}",
        request_method="GET",
        pregenerator=C2CPregenerator(),
    )
    # There is no view corresponding to that route, it is to be used from
    # mako templates to get the root of the "layers" web service
    config.add_route("layers_root", "/layers", request_method="HEAD")

    # Resource proxy (load external url, useful when loading non https content)
    config.add_route("resourceproxy", "/resourceproxy", request_method="GET")

    # Dev
    config.add_route("dev", "/dev/*path", request_method="GET")

    # Used memory in caches
    config.add_route("memory", "/memory", request_method="GET")

    # Scan view decorator for adding routes
    config.scan(ignore=[
        "c2cgeoportal_geoportal.lib",
        "c2cgeoportal_geoportal.scaffolds",
        "c2cgeoportal_geoportal.scripts",
    ])

    add_admin_interface(config)
    add_getitfixed(config)

    # Add the project static view with cache buster
    config.add_static_view(
        name="static",
        path="/etc/geomapfish/static",
        cache_max_age=int(config.get_settings()["default_max_age"]),
    )
    config.add_cache_buster("/etc/geomapfish/static", version_cache_buster)

    # Add the project static view without cache buster
    config.add_static_view(
        name="static-ngeo",
        path="/etc/static-ngeo",
        cache_max_age=int(config.get_settings()["default_max_age"]),
    )

    # Handles the other HTTP errors raised by the views. Without that,
    # the client receives a status=200 without content.
    config.add_view(error_handler, context=HTTPException)

    c2cwsgiutils.index.additional_title = (
        '<div class="row"><div class="col-lg-3"><h2>GeoMapFish</h2></div><div class="col-lg">'
    )

    c2cwsgiutils.index.additional_auth.extend([
        '<a href="../tiles/admin/">TileCloud chain admin</a><br>',
        '<a href="../tiles/c2c/">TileCloud chain c2c tools</a><br>',
        '<a href="../invalidate">Invalidate the cache</a><br>',
        '<a href="../memory">Memory status</a><br>',
    ])
    if config.get_settings().get("enable_admin_interface", False):
        c2cwsgiutils.index.additional_noauth.append(
            '<a href="../admin/">Admin</a><br>')

    c2cwsgiutils.index.additional_noauth.append(
        '</div></div><div class="row"><div class="col-lg-3"><h3>Interfaces</h3></div><div class="col-lg">'
    )
    c2cwsgiutils.index.additional_noauth.append(
        '<a href="../">Default</a><br>')
    for interface in config.get_settings().get("interfaces", []):
        if not interface.get("default", False):
            c2cwsgiutils.index.additional_noauth.append(
                '<a href="../{interface}">{interface}</a><br>'.format(
                    interface=interface["name"]))
    c2cwsgiutils.index.additional_noauth.append(
        '<a href="../apihelp/index.html">API help</a><br>')
    c2cwsgiutils.index.additional_noauth.append("</div></div><hr>")
Beispiel #22
0
 def test_scan_integration_with_extra_kw(self):
     config = self._makeOne(autocommit=True)
     config.scan('tests.test_config.pkgs.scanextrakw', a=1)
     self.assertEqual(config.a, 1)
Beispiel #23
0
    def test_scan_integration(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response
        import tests.test_config.pkgs.scannable as package

        config = self._makeOne(autocommit=True)
        config.scan(package)

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')

        req.method = 'POST'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked_post')

        result = render_view_to_response(ctx, req, 'grokked_class')
        self.assertEqual(result, 'grokked_class')

        result = render_view_to_response(ctx, req, 'grokked_instance')
        self.assertEqual(result, 'grokked_instance')

        result = render_view_to_response(ctx, req, 'oldstyle_grokked_class')
        self.assertEqual(result, 'oldstyle_grokked_class')

        req.method = 'GET'
        result = render_view_to_response(ctx, req, 'another')
        self.assertEqual(result, 'another_grokked')

        req.method = 'POST'
        result = render_view_to_response(ctx, req, 'another')
        self.assertEqual(result, 'another_grokked_post')

        result = render_view_to_response(ctx, req, 'another_grokked_class')
        self.assertEqual(result, 'another_grokked_class')

        result = render_view_to_response(ctx, req, 'another_grokked_instance')
        self.assertEqual(result, 'another_grokked_instance')

        result = render_view_to_response(
            ctx, req, 'another_oldstyle_grokked_class'
        )
        self.assertEqual(result, 'another_oldstyle_grokked_class')

        result = render_view_to_response(ctx, req, 'stacked1')
        self.assertEqual(result, 'stacked')

        result = render_view_to_response(ctx, req, 'stacked2')
        self.assertEqual(result, 'stacked')

        result = render_view_to_response(ctx, req, 'another_stacked1')
        self.assertEqual(result, 'another_stacked')

        result = render_view_to_response(ctx, req, 'another_stacked2')
        self.assertEqual(result, 'another_stacked')

        result = render_view_to_response(ctx, req, 'stacked_class1')
        self.assertEqual(result, 'stacked_class')

        result = render_view_to_response(ctx, req, 'stacked_class2')
        self.assertEqual(result, 'stacked_class')

        result = render_view_to_response(ctx, req, 'another_stacked_class1')
        self.assertEqual(result, 'another_stacked_class')

        result = render_view_to_response(ctx, req, 'another_stacked_class2')
        self.assertEqual(result, 'another_stacked_class')

        # NB: on Jython, a class without an __init__ apparently accepts
        # any number of arguments without raising a TypeError, so the next
        # assertion may fail there.  We don't support Jython at the moment,
        # this is just a note to a future self.

        self.assertRaises(
            TypeError, render_view_to_response, ctx, req, 'basemethod'
        )

        result = render_view_to_response(ctx, req, 'method1')
        self.assertEqual(result, 'method1')

        result = render_view_to_response(ctx, req, 'method2')
        self.assertEqual(result, 'method2')

        result = render_view_to_response(ctx, req, 'stacked_method1')
        self.assertEqual(result, 'stacked_method')

        result = render_view_to_response(ctx, req, 'stacked_method2')
        self.assertEqual(result, 'stacked_method')

        result = render_view_to_response(ctx, req, 'subpackage_init')
        self.assertEqual(result, 'subpackage_init')

        result = render_view_to_response(ctx, req, 'subpackage_notinit')
        self.assertEqual(result, 'subpackage_notinit')

        result = render_view_to_response(ctx, req, 'subsubpackage_init')
        self.assertEqual(result, 'subsubpackage_init')

        result = render_view_to_response(ctx, req, 'pod_notinit')
        self.assertEqual(result, None)
Beispiel #24
0
    def test_scan_integration(self):
        from zope.interface import alsoProvides
        from pyramid.view import render_view_to_response
        import tests.test_config.pkgs.scannable as package

        config = self._makeOne(autocommit=True)
        config.scan(package)

        ctx = DummyContext()
        req = DummyRequest()
        alsoProvides(req, IRequest)
        req.registry = config.registry

        req.method = 'GET'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked')

        req.method = 'POST'
        result = render_view_to_response(ctx, req, '')
        self.assertEqual(result, 'grokked_post')

        result = render_view_to_response(ctx, req, 'grokked_class')
        self.assertEqual(result, 'grokked_class')

        result = render_view_to_response(ctx, req, 'grokked_instance')
        self.assertEqual(result, 'grokked_instance')

        result = render_view_to_response(ctx, req, 'oldstyle_grokked_class')
        self.assertEqual(result, 'oldstyle_grokked_class')

        req.method = 'GET'
        result = render_view_to_response(ctx, req, 'another')
        self.assertEqual(result, 'another_grokked')

        req.method = 'POST'
        result = render_view_to_response(ctx, req, 'another')
        self.assertEqual(result, 'another_grokked_post')

        result = render_view_to_response(ctx, req, 'another_grokked_class')
        self.assertEqual(result, 'another_grokked_class')

        result = render_view_to_response(ctx, req, 'another_grokked_instance')
        self.assertEqual(result, 'another_grokked_instance')

        result = render_view_to_response(ctx, req,
                                         'another_oldstyle_grokked_class')
        self.assertEqual(result, 'another_oldstyle_grokked_class')

        result = render_view_to_response(ctx, req, 'stacked1')
        self.assertEqual(result, 'stacked')

        result = render_view_to_response(ctx, req, 'stacked2')
        self.assertEqual(result, 'stacked')

        result = render_view_to_response(ctx, req, 'another_stacked1')
        self.assertEqual(result, 'another_stacked')

        result = render_view_to_response(ctx, req, 'another_stacked2')
        self.assertEqual(result, 'another_stacked')

        result = render_view_to_response(ctx, req, 'stacked_class1')
        self.assertEqual(result, 'stacked_class')

        result = render_view_to_response(ctx, req, 'stacked_class2')
        self.assertEqual(result, 'stacked_class')

        result = render_view_to_response(ctx, req, 'another_stacked_class1')
        self.assertEqual(result, 'another_stacked_class')

        result = render_view_to_response(ctx, req, 'another_stacked_class2')
        self.assertEqual(result, 'another_stacked_class')

        # NB: on Jython, a class without an __init__ apparently accepts
        # any number of arguments without raising a TypeError, so the next
        # assertion may fail there.  We don't support Jython at the moment,
        # this is just a note to a future self.

        self.assertRaises(TypeError, render_view_to_response, ctx, req,
                          'basemethod')

        result = render_view_to_response(ctx, req, 'method1')
        self.assertEqual(result, 'method1')

        result = render_view_to_response(ctx, req, 'method2')
        self.assertEqual(result, 'method2')

        result = render_view_to_response(ctx, req, 'stacked_method1')
        self.assertEqual(result, 'stacked_method')

        result = render_view_to_response(ctx, req, 'stacked_method2')
        self.assertEqual(result, 'stacked_method')

        result = render_view_to_response(ctx, req, 'subpackage_init')
        self.assertEqual(result, 'subpackage_init')

        result = render_view_to_response(ctx, req, 'subpackage_notinit')
        self.assertEqual(result, 'subpackage_notinit')

        result = render_view_to_response(ctx, req, 'subsubpackage_init')
        self.assertEqual(result, 'subsubpackage_init')

        result = render_view_to_response(ctx, req, 'pod_notinit')
        self.assertEqual(result, None)
Beispiel #25
0
 def test_scan_integration_with_extra_kw(self):
     config = self._makeOne(autocommit=True)
     config.scan('tests.test_config.pkgs.scanextrakw', a=1, categories=None)
     self.assertEqual(config.a, 1)
Beispiel #26
0
def main(global_config, **settings):
    """
        This function returns a Pyramid WSGI application.
    """
    # Setup --------------------------------------------------------------------

    # Db
    init_DBSession(settings)

    # Pyramid Global Settings
    config = pyramid.config.Configurator(
        settings=settings,
        root_factory=TraversalGlobalRootFactory)  # , autocommit=True

    def assert_settings_keys(keys):
        for settings_key in key:
            assert config.registry.settings.get(settings_key)

    # Register Additional Includes ---------------------------------------------
    config.include(
        'pyramid_mako'
    )  # The mako.directories value is updated in the scan for addons. We trigger the import here to include the correct folders.

    # Reload on template change - Dedicated from pserve
    #template_filenames = map(operator.attrgetter('absolute'), file_scan(config.registry.settings['mako.directories']))
    #from pyramid.scripts.pserve import add_file_callback
    #add_file_callback(lambda: template_filenames)

    # Parse/Convert setting keys that have specified datatypes
    # Environment variables; capitalized and separated by underscores can override a settings key.
    # e.g.
    #   export KARAKARA_TEMPLATE_TITLE=Test
    #   can override 'karakara.template.title'
    for key in config.registry.settings.keys():
        value = os.getenv(
            key.replace('.', '_').upper(), ''
        ) if config.registry.settings['karakara.server.mode'] != 'test' else ''
        value = value or config.registry.settings[key]
        config.registry.settings[key] = convert_str_with_type(value)

    # Session identity
    config.add_request_method(partial(
        session_identity, session_keys={'id', 'admin', 'faves', 'user'}),
                              'session_identity',
                              reify=True)

    # Setup Cache Manager config in view
    setup_pyramid_cache_manager(config)
    # Setup Autoformat view processor
    setup_pyramid_autoformater(config)

    @post_view_dict_augmentation.register_pre_render_decorator()
    def add_paths_to_response_dict(request, response):
        response['paths'] = {
            'context': pyramid.traversal.resource_path(request.context),
            'queue': '',
        }
        try:
            queue_context = request.context.queue_context
            if queue_context:
                response['paths'].update(
                    template_helpers.paths_for_queue(queue_context.id))
        except AttributeError:
            pass

    # i18n
    config.add_translation_dirs(
        config.registry.settings['i18n.translation_dirs'])

    # Session Manager
    session_settings = extract_subkeys(config.registry.settings, 'session.')
    session_factory = SignedCookieSessionFactory(serializer=json_serializer,
                                                 **session_settings)
    config.set_session_factory(session_factory)

    from .model.actions import last_track_db_update

    def _last_track_db_update(request):
        return last_track_db_update()

    # Track DB Version ---------------------------------------------------------
    config.add_request_method(_last_track_db_update,
                              'last_track_db_update',
                              property=True,
                              reify=True)

    # Cachebust etags ----------------------------------------------------------
    #  crude implementation; count the number of tags in db, if thats changed, the etags will invalidate
    if not config.registry.settings['server.etag.cache_buster']:
        config.registry.settings[
            'server.etag.cache_buster'] = 'last_update:{0}'.format(
                str(last_track_db_update()))
        # TODO: Where is this used? How is this related to karakara.tracks.version?

    # Global State -------------------------------------------------------------
    config.registry.settings['karakara.tracks.version'] = random.randint(
        0, 20000000)

    # Search Config ------------------------------------------------------------
    import karakara.views.queue_search
    karakara.views.queue_search.search_config = read_json(
        config.registry.settings['karakara.search.view.config'])
    assert karakara.views.queue_search.search_config, 'search_config data required'

    # LogEvent -----------------------------------------------------------------

    log_event_logger = logging.getLogger('json_log_event')

    def log_event(request, **data):
        """
        It is expected that python's logging framework is used to output these
        events to the correct destination.
        Logstash can then read/process this log output for overview/stats
        """
        event = data.get('event')
        try:
            event = request.matched_route.name
        except Exception:
            pass
        try:
            event = request.context.__name__
        except Exception:
            pass
        data.update({
            'event': event,
            'session_id': request.session.get('id'),
            'ip': request.environ.get('REMOTE_ADDR'),
            'timestamp': now(),
        })
        log_event_logger.info(json_string(data))

    config.add_request_method(log_event)

    # WebSocket ----------------------------------------------------------------

    class NullAuthEchoServerManager(object):
        def recv(self, *args, **kwargs):
            pass

    socket_manager = NullAuthEchoServerManager()

    if config.registry.settings.get('karakara.websocket.port'):

        def authenticator(key):
            """Only admin authenticated keys can connect to the websocket"""
            cookie_name = config.registry.settings['session.cookie_name']
            if cookie_name in key:
                cookie = key
            else:
                cookie = '{0}={1}'.format(cookie_name, key)
            request = pyramid.request.Request({'HTTP_COOKIE': cookie})
            session_data = session_factory(request)
            return session_data and session_data.get('admin')

        def _int_or_none(setting_key):
            return int(config.registry.settings.get(setting_key)
                       ) if config.registry.settings.get(setting_key) else None

        try:
            _socket_manager = AuthEchoServerManager(
                authenticator=authenticator,
                websocket_port=_int_or_none('karakara.websocket.port'),
                tcp_port=_int_or_none('karakara.tcp.port'),
            )
            _socket_manager.start()
            socket_manager = _socket_manager
        except OSError:
            log.warn('Unable to setup websocket')

    def send_websocket_message(request, message):
        # TODO: This will have to be augmented with json and queue_id in future
        socket_manager.recv(
            message.encode('utf-8'))  # TODO: ?um? new_line needed?

    config.add_request_method(send_websocket_message)
    #config.registry['socket_manager'] = socket_manager

    # Login Providers ----------------------------------------------------------

    from .views.comunity_login import social_login
    social_login.user_store = ComunityUserStore()
    login_providers = config.registry.settings.get('login.provider.enabled')
    # Facebook
    if 'facebook' in login_providers:
        assert_settings_keys(
            ('login.facebook.appid', 'login.facebook.secret'),
            message=
            'To use facebook as a login provider appid and secret must be provided'
        )
        social_login.add_login_provider(
            FacebookLogin(
                appid=config.registry.settings.get('login.facebook.appid'),
                secret=config.registry.settings.get('login.facebook.secret'),
                permissions=config.registry.settings.get(
                    'login.facebook.permissions'),
            ))
    # Google
    if 'google' in login_providers:
        social_login.add_login_provider(
            GoogleLogin(client_secret_file=config.registry.settings.get(
                'login.google.client_secret_file'), ))
    # Firefox Persona (Deprecated technology but a useful reference)
    #if 'persona' in login_providers:
    #    social_login.add_login_provider(PersonaLogin(
    #        site_url=config.registry.settings.get('server.url')
    #    ))
    # No login provider
    if not login_providers and config.registry.settings.get(
            'karakara.server.mode') != 'test':
        # Auto login if no service keys are provided
        social_login.add_login_provider(NullLoginProvider())
        social_login.user_store = NullComunityUserStore()
    template_helpers.javascript_inline['comunity'] = social_login.html_includes

    # KaraKara request additions -----------------------------------------------

    from unittest.mock import patch

    def call_sub_view(request, view_callable, acquire_cache_bucket_func):
        """
        A wrapper for called view_callable's to allow subrequests to use correct cache_buckets
        """
        if not hasattr(request, 'cache_bucket'):
            # FFS - don't ask questions ... just ... (sigh) ... patch can ONLY patch existing attributes
            setattr(request, 'cache_bucket', 'some placeholder s***e')
        _cache_bucket = acquire_cache_bucket_func(request)
        with patch.object(request, 'cache_bucket', _cache_bucket):
            assert request.cache_bucket == _cache_bucket
            return view_callable(request)['data']

    config.add_request_method(call_sub_view)

    from .model_logic.queue_logic import QueueLogic
    config.add_request_method(QueueLogic, 'queue', reify=True)

    # Routes -------------------------------------------------------------------

    def settings_path(key):
        path = os.path.join(os.getcwd(), config.registry.settings[key])
        if not os.path.isdir(path):
            log.error('Unable to add_static_view {key}:{path}'.format(
                key=key, path=path))  #TODO: reaplce with formatstring
        return path

    # Static Routes
    config.add_static_view(
        name='ext',
        path=settings_path('static.externals'))  # cache_max_age=3600
    config.add_static_view(
        name='static',
        path=settings_path('static.assets'))  # cache_max_age=3600
    config.add_static_view(name='player', path=settings_path('static.player'))
    config.add_static_view(name='player2',
                           path=settings_path('static.player2'))

    # AllanC - it's official ... static route setup and generation is a mess in pyramid
    #config.add_static_view(name=settings["static.media" ], path="karakara:media" )
    config.add_static_view(
        name='files',
        path=config.registry.settings['static.processmedia2.config']
        ['path_processed'])

    # View Routes
    config.add_route('inject_testdata', '/inject_testdata')
    # Upload extras -----
    #config.add_static_view(name=settings['upload.route.uploaded'], path=settings['upload.path'])  # the 'upload' route above always matchs first
    config.add_route('upload', '/upload{sep:/?}{name:.*}')

    # Events -------------------------------------------------------------------
    config.add_subscriber(add_localizer_to_request, pyramid.events.NewRequest)
    config.add_subscriber(add_render_globals_to_template,
                          pyramid.events.BeforeRender)

    # Tweens -------------------------------------------------------------------
    if config.registry.settings.get(
            'karakara.server.mode'
    ) == 'development' and config.registry.settings.get(
            'karakara.server.postmortem'):
        config.add_tween('karakara.postmortem_tween_factory')

    # Return -------------------------------------------------------------------
    config.scan(ignore='.tests')
    config.scan('calaldees.pyramid_helpers.views')
    return config.make_wsgi_app()