Exemplo n.º 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()
Exemplo n.º 2
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()
Exemplo n.º 3
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()
Exemplo n.º 4
0
def includeme(config: pyramid.config.Configurator) -> None:
    """Initialize json and fast_json renderer."""
    config.add_renderer("json", JSON(indent=2, sort_keys=True))
    config.add_renderer("fast_json", JSON(serializer=fast_dumps))
    config.add_renderer("cornice_json",
                        CorniceRenderer(indent=2, sort_keys=True))
    config.add_renderer("cornice_fast_json",
                        CorniceRenderer(serializer=fast_dumps))
Exemplo n.º 5
0
def init_json_renderer(config: pyramid.config.Configurator) -> None:
    renderer = pyramid.renderers.JSON()

    def step_adapter(step: tokaido.models.Step,
                     request: pyramid.request.Request) -> Dict[str, Any]:
        return {
            'id':
            step.id,
            'title':
            step.title,
            'next_step_ids':
            [next_step.next_step_id for next_step in step.next_steps]
        }

    renderer.add_adapter(tokaido.models.Step, step_adapter)
    config.add_renderer('json', renderer)
Exemplo n.º 6
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)
Exemplo n.º 7
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>")
Exemplo n.º 8
0
def init(config: pyramid.config.Configurator) -> None:
    config.add_renderer('json', JSON(indent=2, sort_keys=True))
    config.add_renderer('fast_json', JSON(serializer=fast_dumps))
Exemplo n.º 9
0
    Dashboard.set_connection(connection)

    Dashboard.add_dashboard([User, Group, SuperGroup],config,'/test')

    renderer = mf.renderer.TextChoiceRenderer(User,'email','')
    renderer.limit([ 'nomail', '*****@*****.**', 'sample@nomail' ])
    renderer.add_extra_control('<button class="btn btn-info">Fake button</button>')

    renderer = User.get_renderer('groupRef')
    renderer.set_reference(Group)

    groupid_renderer = mf.renderer.SimpleReferenceRenderer(User,'groupid',Group)

    # automatically serialize bson ObjectId to Mongo extended JSON
    json_renderer = JSON()

    def objectId_adapter(obj, request):
        return json_util.default(obj)
    def datetime_adapter(obj, request):
        return json_util.default(obj)
    json_renderer.add_adapter(ObjectId, objectId_adapter)
    json_renderer.add_adapter(datetime, datetime_adapter)
    config.add_renderer('json', json_renderer)

    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6789, app)
    server.serve_forever()