Exemplo n.º 1
0
def add_interface_ngeo(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    renderer: str = None,
    permission: str = None,
) -> None:

    config.add_route(route_name, route, request_method="GET")
    config.add_view(Entry,
                    attr="get_ngeo_index_vars",
                    route_name=route_name,
                    renderer=renderer,
                    permission=permission)
    # Permalink theme: recover the theme for generating custom viewer.js url
    config.add_route(
        "{}theme".format(route_name),
        "{}{}theme/{{themes}}".format(route, "" if route[-1] == "/" else "/"),
        request_method="GET",
    )
    config.add_view(
        Entry,
        attr="get_ngeo_index_vars",
        route_name="{}theme".format(route_name),
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 2
0
def add_interface_ngeo(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    renderer: Optional[str] = None,
    permission: Optional[str] = None,
) -> None:
    """Add the ngeo interfaces views and routes."""

    config.add_route(route_name, route, request_method="GET")
    # Permalink theme: recover the theme for generating custom viewer.js url
    config.add_route(
        f"{route_name}theme",
        f"{route}{'' if route[-1] == '/' else '/'}theme/{{themes}}",
        request_method="GET",
    )
    config.add_view(Entry,
                    attr="get_ngeo_index_vars",
                    route_name=route_name,
                    renderer=renderer,
                    permission=permission)
    config.add_view(
        Entry,
        attr="get_ngeo_index_vars",
        route_name=f"{route_name}theme",
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 3
0
def init(config: pyramid.config.Configurator) -> None:
    base_path = _utils.get_base_path(config)
    if base_path != '':
        config.add_route("c2c_index", base_path, request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index", http_cache=0)
        config.add_route("c2c_index_slash", base_path + "/", request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index_slash", http_cache=0)
Exemplo n.º 4
0
def add_interface_canvas(
    config: pyramid.config.Configurator,
    route_name: str,
    route: str,
    interface_config: Dict[str, Any],
    permission: Optional[str] = None,
) -> None:
    """Add the ngeo interfaces views and routes."""

    renderer = f"/etc/geomapfish/interfaces/{route_name}.html.mako"
    config.add_route(route_name, route, request_method="GET")
    # Permalink theme: recover the theme for generating custom viewer.js URL
    config.add_route(
        f"{route_name}theme",
        f"{route}{'' if route[-1] == '/' else '/'}theme/{{themes}}",
        request_method="GET",
    )
    view = partial(canvas_view, interface_config=interface_config)
    view.__module__ = canvas_view.__module__
    config.add_view(
        view,
        route_name=route_name,
        renderer=renderer,
        permission=permission,
    )
    config.add_view(
        view,
        route_name=f"{route_name}theme",
        renderer=renderer,
        permission=permission,
    )
Exemplo n.º 5
0
def init(config: pyramid.config.Configurator) -> None:
    if os.path.isfile(VERSIONS_PATH):
        versions = _read_versions()
        config.add_route("c2c_versions",
                         _utils.get_base_path(config) + r"/versions.json",
                         request_method="GET")
        config.add_view(lambda request: versions,
                        route_name="c2c_versions",
                        renderer="fast_json",
                        http_cache=0)
        LOG.info("Installed the /versions.json service")
        git_hash = versions['main']['git_hash']

        if 'git_tag' in versions['main']:
            LOG.warning("Starting version %s (%s)",
                        versions['main']['git_tag'], git_hash)
        else:
            LOG.warning("Starting version %s", git_hash)

        if stats.USE_TAGS:
            stats.increment_counter(['version'],
                                    1,
                                    tags=dict(version=git_hash))
        else:
            stats.increment_counter(['version', git_hash], 1)
Exemplo n.º 6
0
def add_redirect(config: pyramid.config.Configurator, name: str, from_: str,
                 to: str) -> None:
    def redirect_view(request: pyramid.request.Request) -> HTTPFound:
        return HTTPFound(location=request.route_url(to))

    config.add_route(name, from_, request_method="GET")
    config.add_view(redirect_view, route_name=name)
Exemplo n.º 7
0
def add_cors_route(config: pyramid.config.Configurator, pattern: str,
                   service: str) -> None:
    """Add the OPTIONS route and view need for services supporting CORS."""
    def view(request: pyramid.request.Request) -> pyramid.response.Response:
        return set_common_headers(request, service, Cache.PRIVATE_NO)

    name = pattern + "_options"
    config.add_route(name, pattern, request_method="OPTIONS")
    config.add_view(view, route_name=name)
Exemplo n.º 8
0
def _add_view(config: pyramid.config.Configurator, name: str, path: str,
              view: Callable[[pyramid.request.Request], Any]) -> None:
    config.add_route("c2c_debug_" + name,
                     config_utils.get_base_path(config) + r"/debug/" + path,
                     request_method="GET")
    config.add_view(view,
                    route_name="c2c_debug_" + name,
                    renderer="fast_json",
                    http_cache=0)
Exemplo n.º 9
0
def init(config: pyramid.config.Configurator) -> None:
    config.add_route("c2c_read_stats_json",
                     _utils.get_base_path(config) + r"/stats.json",
                     request_method="GET")
    memory_backend = cast(stats.MemoryBackend, stats.BACKENDS['memory'])
    config.add_view(memory_backend.get_stats,
                    route_name="c2c_read_stats_json",
                    renderer="fast_json",
                    http_cache=0)
Exemplo n.º 10
0
def _static(config: pyramid.config.Configurator):
    config.add_route(name='index', path='/*subpath')
    config.add_view(
        request_method='GET',
        route_name='index',
        view=pyramid.static.static_view(
            root_dir='megadloader:static/',
            package_name='megadloader:static',
        ),
    )
Exemplo n.º 11
0
def _make_application(*, geoip, socket):
    """Construct a Pyramid WSGI application.

    This creates a central Pyramid configurator then adds all routes, views
    and Jinja2 configuration to it.

    :mod:`pyramid_jinja2` is included into the configuration. The search path
    for Jinja2 is set to the ``templates/`` directory. The Jinja2 syntax is
    modified so that it uses square brackets instead of curly ones. E.g.
    ``{{foo}}`` becomes ``[[foo]]``. This applies to Jinja2 statements as
    well as comments.

    A route and view is added for ``/`` which serves the Angular application.
    A default 'not found' view is also added which also serves the Angular
    application. This is so that the Angular ``$location`` service can use
    *HTML5 mode* routing. Because of this there is no guarantee that a matched
    route will be set for the current request inside the entry point template.
    E.g. you can't use ``request.current_route_url``.

    Static views are added for the ``external``, ``scripts``, ``styles``,
    ``images``, ``templates`` and ``data`` directories. These are all served
    directly from the route. E.g. templates are served from ``/templates/``.

    The configuration for Steam OpenID authentication and the location
    service is added.

    :param pathlib.Path geoip: the path to the GeoIP database to use for
        the location service.
    :param str socket: the websocket URL the UI should connect to.

    :return: a WSGI application.
    """
    config = pyramid.config.Configurator(settings={
        "pyramid.reload_templates": True,
    })
    config.include("pyramid_jinja2")
    config.add_jinja2_search_path(__name__ + ":templates/")
    config.add_route("main", "/")
    config.add_view(route_name="main", renderer="main.jinja2")
    config.add_notfound_view(_404, renderer="main.jinja2")
    for static in ["external", "scripts",
                   "styles", "images", "templates", "data"]:
        config.add_static_view(static, "{}:{}/".format(__name__, static))
    _configure_authentication(config)
    _configure_location(config, geoip)
    config.commit()
    jinja2_env = config.get_jinja2_environment()
    jinja2_env.block_start_string = "[%"
    jinja2_env.block_end_string = "%]"
    jinja2_env.variable_start_string = "[["
    jinja2_env.variable_end_string = "]]"
    jinja2_env.comment_start_string = "[#"
    jinja2_env.comment_end_string = "#]"
    jinja2_env.globals["socket"] = socket
    return config.make_wsgi_app()
def includeme(config: pyramid.config.Configurator) -> None:
    for pattern, view, request_method in [
        ('/api/sign_in', api.sign_in, 'POST'),
        ('/api/sign_up', api.sign_up, 'POST'),
    ]:
        config.add_route(pattern, pattern, request_method=request_method)
        config.add_view(view,
                        route_name=pattern,
                        request_method=request_method)

    config.add_view(api.error, context=Exception)
Exemplo n.º 13
0
def add_admin_interface(config: pyramid.config.Configurator) -> None:
    if config.get_settings().get("enable_admin_interface", False):
        config.add_request_method(
            lambda request: c2cgeoportal_commons.models.DBSession(),
            "dbsession",
            reify=True,
        )
        config.add_view(c2cgeoportal_geoportal.views.add_ending_slash,
                        route_name="admin_add_ending_slash")
        config.add_route("admin_add_ending_slash",
                         "/admin",
                         request_method="GET")
        config.include("c2cgeoportal_admin")
Exemplo n.º 14
0
def add_getitfixed(config: pyramid.config.Configurator) -> None:
    if config.get_settings()["getitfixed"].get("enabled", False):
        for route_name, pattern in (
            ("getitfixed_add_ending_slash", "/getitfixed"),
            ("getitfixed_admin_add_ending_slash", "/getitfixed_admin"),
        ):
            config.add_view(c2cgeoportal_geoportal.views.add_ending_slash,
                            route_name=route_name)
            config.add_route(route_name, pattern, request_method="GET")
        config.include("getitfixed")
        # Register admin and getitfixed search paths together
        Form.set_zpt_renderer(c2cgeoform.default_search_paths,
                              translator=translator)
Exemplo n.º 15
0
def _configure_location(config, geoip):
    """Configure the location server.

    This adds the ``service-location`` route and corresponding view to the
    given configurator. A reified request method ``geoip`` is added which
    returns a database reader for the given GeoIP database.

    :param pathlib.Path geoip: the path to the GeoIP database to use for
        the location service.
    """
    config.add_request_method(
        lambda r: geoip2.database.Reader(str(geoip)), "geoip", reify=True)
    config.add_route("service-location", "/services/location")
    config.add_view(_location, route_name="service-location", renderer="json")
Exemplo n.º 16
0
 def __init__(self, config: pyramid.config.Configurator) -> None:
     config.add_route("c2c_health_check",
                      _utils.get_base_path(config) + r"/health_check",
                      request_method="GET")
     config.add_view(self._view,
                     route_name="c2c_health_check",
                     renderer="fast_json",
                     http_cache=0)
     self._checks: List[Tuple[str, Callable[[pyramid.request.Request], Any],
                              int]] = []
     redis_url = _utils.env_or_config(config, broadcast.REDIS_ENV_KEY,
                                      broadcast.REDIS_CONFIG_KEY)
     if redis_url is not None:
         self.add_redis_check(redis_url, level=2)
         if version.get_version() is not None:
             self.add_version_check(level=2)
Exemplo n.º 17
0
 def test_deprecated_ranges_in_route_predicate(self):
     config = self._makeConfig()
     config.add_route('foo', '/foo', accept='text/*')
     config.add_view(lambda r: 'OK', route_name='foo', renderer='string')
     app = self._makeTestApp(config)
     res = app.get(
         '/foo',
         headers={'Accept': 'application/json; q=1.0, text/plain; q=0.9'},
         status=200,
     )
     self.assertEqual(res.content_type, 'text/plain')
     self.assertEqual(res.body, b'OK')
     res = app.get('/foo',
                   headers={'Accept': 'application/json'},
                   status=404)
     self.assertEqual(res.content_type, 'application/json')
Exemplo n.º 18
0
 def on_class_load(cls, config: pyramid.config.Configurator):
     super(cls, cls).on_class_load(config)
     # config.add_route('test_payment_form', cls.route_payment_form)
     config.add_route('yandex_money_result_redirect',
                      cls.route_result_redirect)
     settings = config.registry.settings
     # ViewsPaymentTestServer.notify_url = settings.get(ViewsPaymentTestServer.__name__+'.notify_url')
     # config.add_view(
     #     ViewsPaymentTestServer,
     #     attr='view_payment_form',
     #     route_name='test_payment_form',
     #     renderer='payment_systems/test_payment_form.jinja2'
     # )
     config.add_view(ViewsPaymentClientYandexMoney,
                     attr='view_result_redirect',
                     route_name='test_payment_notify',
                     renderer='string')
Exemplo n.º 19
0
    def __init__(self, config: pyramid.config.Configurator) -> None:
        config.add_route(
            "c2c_health_check", config_utils.get_base_path(config) + r"/health_check", request_method="GET"
        )
        config.add_view(self._view, route_name="c2c_health_check", renderer="fast_json", http_cache=0)
        self._checks: List[Tuple[str, Callable[[pyramid.request.Request], Any], int]] = []

        self.name = config_utils.env_or_config(
            config,
            redis_utils.REDIS_SENTINELS_KEY,
            redis_utils.REDIS_SENTINELS_KEY_PROP,
            config_utils.env_or_config(config, redis_utils.REDIS_URL_KEY, redis_utils.REDIS_URL_KEY_PROP),
        )
        if self.name:
            self.add_redis_check(level=2)
            if version.get_version() is not None:
                self.add_version_check(level=2)
Exemplo n.º 20
0
 def on_class_load(cls, config: pyramid.config.Configurator):
     super(cls, cls).on_class_load(config)
     config.add_route('test_payment_form', cls.route_payment_form)
     config.add_route('test_payment_notify', cls.route_payment_notify)
     settings = config.registry.settings
     ViewsPaymentTestServer.notify_url = settings.get(ViewsPaymentTestServer.__name__+'.notify_url')
     config.add_view(
         ViewsPaymentTestServer,
         attr='view_payment_form',
         route_name='test_payment_form',
         renderer='payment_systems/test_payment_form.jinja2'
     )
     config.add_view(
         ViewsPaymentTestClient,
         attr='view_payment_client_notify',
         route_name='test_payment_notify',
         renderer='string'
     )
Exemplo n.º 21
0
def includeme(config: pyramid.config.Configurator) -> None:
    """Initialize the index page."""
    base_path = config_utils.get_base_path(config)
    if base_path != "":
        config.add_route("c2c_index",
                         base_path,
                         request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index", http_cache=0)
        config.add_route("c2c_index_slash",
                         base_path + "/",
                         request_method=("GET", "POST"))
        config.add_view(_index, route_name="c2c_index_slash", http_cache=0)

        settings = config.get_settings()
        auth_type_ = auth_type(settings)
        if auth_type_ == AuthenticationType.SECRET:
            LOG.warning(
                "It is recommended to use OAuth2 with GitHub login instead of the `C2C_SECRET` because it "
                "protects from brute force attacks and the access grant is personal and can be revoked."
            )

        if auth_type_ == AuthenticationType.GITHUB:
            config.add_route("c2c_github_login",
                             base_path + "/github-login",
                             request_method=("GET", ))
            config.add_view(_github_login,
                            route_name="c2c_github_login",
                            http_cache=0)
            config.add_route("c2c_github_callback",
                             base_path + "/github-callback",
                             request_method=("GET", ))
            config.add_view(_github_login_callback,
                            route_name="c2c_github_callback",
                            http_cache=0,
                            renderer="fast_json")
            config.add_route("c2c_github_logout",
                             base_path + "/github-logout",
                             request_method=("GET", ))
            config.add_view(_github_logout,
                            route_name="c2c_github_logout",
                            http_cache=0)
Exemplo n.º 22
0
def _configure_authentication(config):
    """Configure authentication policies, routes and view.

    This adds a authentication and authorisation policy to the given
    configurator. In addition to this it adds a reified request method
    called ``openid_consumer`` -- see :func:`_get_openid_consumer`.

    For authentication two routes are added: ``authenticate-begin`` and
    ``authentication-complete``. These routes are bound to the views
    :func:`_begin_authentication` and :func:`_complete_authentication`
    respectively.

    The authentication completion view will have it's renderer set to the
    ``authentication-complete.jinja2`` Jinja template.

    Authentication it self is done through Steam's OpenID provision. The
    two views added by this function implement the OpenID flow.

    An additional route ``service-profile`` and corresponding view is added
    that returns a JSON object that identifies the current user.
    """
    # TODO: DO NOT use this factory in production!
    config.set_session_factory(
        pyramid.session.SignedCookieSessionFactory("coffeedenshul"))
    authn_policy = pyramid.authentication.AuthTktAuthenticationPolicy(
        "coffeedenshul",
        hashalg="sha512",
    )
    authz_policy = pyramid.authorization.ACLAuthorizationPolicy()
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.add_request_method(
        _get_openid_consumer,
        "openid_consumer",
        reify=True,
    )
    config.add_route("authenticate-begin", "/authenticate/begin")
    config.add_route("authenticate-complete", "/authenticate/complete")
    config.add_view(_begin_authentication, route_name="authenticate-begin")
    config.add_view(
        _complete_authentication,
        route_name="authenticate-complete",
        renderer="authentication-complete.jinja2",
    )
    config.add_route("service-profile", "/services/profile")
    config.add_view(_profile, route_name="service-profile", renderer="json")
Exemplo n.º 23
0
def main():
    with pyramid.config.Configurator() as config:
        config.add_route("hello", "/")
        config.add_view(handle_edit_request, route_name="hello")
        app = config.make_wsgi_app()
        return app
Exemplo n.º 24
0
import pyramid.config
import pyramid.response

from config import PING_MESSAGE


# noinspection PyUnusedLocal
def ping(request):
    return pyramid.response.Response(PING_MESSAGE.format(app='pyramid'))


with pyramid.config.Configurator() as config:
    config.add_route('ping', '/')
    config.add_view(ping, route_name='ping')
    app = config.make_wsgi_app()
Exemplo n.º 25
0
#Use pymongo
from pymongo import MongoClient
from mongokit import Document, Connection

from bson import json_util
from pyramid.renderers import JSON

if __name__ == '__main__':
    my_session_factory = UnencryptedCookieSessionFactoryConfig('itsaseekreet')
    config = Configurator(session_factory = my_session_factory)
    config.include('pyramid_debugtoolbar')
    config.add_settings({'mako.directories':'templates/'})
    config.add_static_view(name='static', path='static')
    config.add_route('home', '/')
    config.add_route('about', '/about')
    config.add_view(home, route_name='home')
    mgconnection = MongoClient()
    db = mgconnection.test

    # Clear database
    db.drop_collection('users')
    db.drop_collection('groups')

    connection = Connection()
    connection.register([User,Group,SuperGroup])

    group = connection.Group()
    group["name"] = "sampleGroup"
    group["creation_date"] = datetime.utcnow()
    group.save()
Exemplo n.º 26
0
def _api(config: pyramid.config.Configurator):
    config.add_route('api: status', '/api/status')
    config.add_view(
        request_method='GET',
        route_name='api: status',
        view=handle_status,
        renderer='json',
    )

    config.add_route('api: categories', '/api/categories/')
    config.add_view(
        request_method='GET',
        route_name='api: categories',
        view=handle_list_categories,
        renderer='json',
    )
    config.add_view(
        request_method='POST',
        route_name='api: categories',
        view=handle_create_category,
        renderer='json',
    )

    config.add_route('api: urls', '/api/urls/')
    config.add_view(
        request_method='GET',
        route_name='api: urls',
        view=handle_get_urls,
        renderer='json',
    )
    config.add_view(
        request_method='POST',
        route_name='api: urls',
        view=handle_add_url,
        renderer='json',
    )

    config.add_route('api: queue items', '/api/queue/{queue_id}')
    config.add_view(
        request_method='DELETE',
        route_name='api: queue items',
        view=handle_delete_url,
        renderer='json',
    )

    config.add_route('api: files', '/api/files/')
    config.add_view(
        request_method='GET',
        route_name='api: files',
        view=handle_list_files,
        renderer='json',
    )

    config.add_route('api: file', '/api/files/{file_id}')
    config.add_view(
        request_method='GET',
        route_name='api: file',
        view=handle_get_file,
        renderer='json',
    )
Exemplo n.º 27
0
 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)
Exemplo n.º 28
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.º 29
0
def _configure_routes(config):
    config.add_static_view(name='static', path='nerffinder:static')
    config.add_route('root', '/')
    config.add_view(nerffinder.views.map.map_view, route_name='root', renderer='nerffinder:templates/splash.mak')
    config.add_route('map', '/map')
    config.add_view(nerffinder.views.map.map_view, route_name='map', renderer='nerffinder:templates/map.mak')
    config.add_route('chart', '/chart')
    config.add_view(nerffinder.views.chart.chart_view, route_name='chart', renderer='nerffinder:templates/chart.mak')
    config.add_route('precache', '/precache')
    config.add_view(nerffinder.views.precache.precache_view, route_name='precache', renderer='nerffinder:templates/precache.mak')
    
    config.add_route('api_gear_categories', '/api/v1/gear/categories/')
    config.add_view(nerffinder.api.v1.gear.categories_view, route_name='api_gear_categories', renderer='json')
    config.add_route('api_gear_locations', '/api/v1/gear/locations/')
    config.add_view(nerffinder.api.v1.gear.locations_view, route_name='api_gear_locations', renderer='json')
    config.add_route('api_gear_details', '/api/v1/gear/details/{id}/')
    config.add_view(nerffinder.api.v1.gear.details_view, route_name='api_gear_details', renderer='json')
Exemplo n.º 30
0
Arquivo: imsa.py Projeto: sblask/imsa
def __discover_routes(config):
    for name, object_ in inspect.getmembers(sys.modules[__name__]):
        if inspect.isfunction(object_) and hasattr(object_, 'route'):
            config.add_route(name, object_.route)
            config.add_view(object_, route_name=name)