def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ with Configurator(settings=settings) as config: config.include('.models') config.include('pyramid_mako') config.include('.routes') config.include('pyramid_ldap3') config.scan() config.add_subscriber(add_cors_headers_response_callback, NewRequest) # Add the "geojson" renderer config.add_renderer("geojson", GeoJSON()) config.set_authentication_policy( AuthTktAuthenticationPolicy( settings["authtkt_secret"], cookie_name=settings["authtkt_cookie_name"], callback=groupfinder, samesite=settings["authtk_samesite"], secure=settings["authtk_secure"] ) ) config.set_authorization_policy( ACLAuthorizationPolicy() ) config.ldap_setup( settings['ldap_url'], bind=settings['ldap_bind'], passwd=settings['ldap_passwd']) config.ldap_set_login_query( base_dn=settings['ldap_login_query_base_dn'], filter_tmpl=settings['ldap_login_query_filter_tmpl'], attributes=settings['ldap_login_query_attributes'].replace(', ', ',').replace(' , ', ',').replace(' ,', ',').split( ','), scope=settings['ldap_login_query_scope']) config.ldap_set_groups_query( base_dn=settings['ldap_group_query_base_dn'], filter_tmpl=settings['ldap_group_query_filter_tmpl'], scope=settings['ldap_group_query_scope'], cache_period=int(settings['ldap_group_query_cache_period']), attributes=settings['ldap_group_attributes'].replace(', ', ',').replace(' , ', ',').replace(' ,', ',').split(',')) return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ load_local_settings(settings) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.include('papyrus') config.add_static_view('static', 'static', cache_max_age=3600, cachebust=True) config.add_static_view('lib', settings.get('node_modules'), cache_max_age=86000, cachebust=True) config.add_route('index', '/') config.add_route('about', '/about') config.add_route('faq', '/faq') config.add_route('report', '/report/{divisioncode:\d+}/{hazardtype:([A-Z]{2})}') config.add_route( 'report_json', '/report/{divisioncode:\d+}/{hazardtype:([A-Z]{2})}.json') config.add_route('report_overview', '/report/{divisioncode:\d+}') config.add_route('report_overview_slash', '/report/{divisioncode:\d+}/') config.add_route('report_overview_json', '/report/{divisioncode:\d+}.json') config.add_route('administrativedivision', '/administrativedivision') config.add_renderer('geojson', GeoJSON()) config.scan(ignore=['thinkhazard.tests']) return config.make_wsgi_app()
def includeme(config): """ This function returns a Pyramid WSGI application. """ settings = config.get_settings() config.include("c2cgeoportal_commons") 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) # Initialise DBSessions init_dbsessions(settings, config, health_check) # Initialize the dbreflection module dbreflection.init() checker.init(config, health_check) check_collector.init(config, health_check) config.include("pyramid_closure") # dogpile.cache configuration if 'cache' in settings: caching.init_region(settings['cache']) from c2cgeoportal_commons.models.main import InvalidateCacheEvent @zope.event.classhandler.handler(InvalidateCacheEvent) def handle(event: InvalidateCacheEvent): del event caching.invalidate_region() # Register a tween to get back the cache buster path. config.add_tween( "c2cgeoportal_geoportal.lib.cacheversion.CachebusterTween") # 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 decimal json renderer config.add_renderer("decimaljson", DecimalJSON()) # Add the "xsd" renderer config.add_renderer( "xsd", XSD(sequence_callback=dbreflection.xsd_sequence_callback)) # 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) if settings.get("ogcproxy_enable", False): # pragma: no cover # Add an OGCProxy view config.add_route_predicate("ogc_server", OgcproxyRoutePredicate) config.add_route("ogcproxy", "/ogcproxy", ogc_server=True) config.add_view("papyrus_ogcproxy.views:ogcproxy", route_name="ogcproxy") # Add routes to the mapserver proxy config.add_route_predicate("mapserverproxy", MapserverproxyRoutePredicate) config.add_route( "mapserverproxy", "/mapserv_proxy", mapserverproxy=True, pregenerator=C2CPregenerator(role=True), ) # Add route to the tinyows proxy config.add_route( "tinyowsproxy", "/tinyows_proxy", pregenerator=C2CPregenerator(role=True), ) # Add routes to csv view config.add_route("csvecho", "/csv", request_method="POST") # Add route to the export GPX/KMLÂ view config.add_route("exportgpxkml", "/exportgpxkml") # Add routes to the echo service config.add_route("echo", "/echo", request_method="POST") # 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, "/loginchange", "login") config.add_route("loginchange", "/loginchange", 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_route("apijs", "/api.js", request_method="GET") config.add_route("xapijs", "/xapi.js", request_method="GET") config.add_route("apihelp", "/apihelp.html", request_method="GET") config.add_route("xapihelp", "/xapihelp.html", request_method="GET") 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") # For v2 config.add_route( "printproxy_info", "/printproxy/info.json", request_method="GET", pregenerator=C2CPregenerator(role=True), ) config.add_route( "printproxy_create", "/printproxy/create.json", request_method="POST", ) config.add_route( "printproxy_get", "/printproxy/{file}.printout", request_method="GET", ) # Full-text search routes add_cors_route(config, "/fulltextsearch", "fulltextsearch") config.add_route("fulltextsearch", "/fulltextsearch") # Access to raster data add_cors_route(config, "/raster", "raster") config.add_route("raster", "/raster", request_method="GET") add_cors_route(config, "/profile.{ext}", "profile") config.add_route("profile.csv", "/profile.csv", request_method="POST") 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", "/short/{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=JSON_CONTENT_TYPE) config.add_route("layers_update", "/layers/{layer_id:\\d+}/{feature_id}", request_method="PUT", header=JSON_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") # Scan view decorator for adding routes config.scan(ignore=[ "c2cgeoportal_geoportal.scripts", "c2cgeoportal_geoportal.wsgi_app" ]) if "subdomains" in settings: # pragma: no cover config.registry.registerUtility(MultiDomainStaticURLInfo(), IStaticURLInfo) # Add the static view (for static resources) _add_static_view(config, "static", "c2cgeoportal_geoportal:static") _add_static_view(config, "project", "c2cgeoportal_geoportal:project") add_admin_interface(config) add_static_view(config) # 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)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ app_version = settings.get('app_version') settings['app_version'] = app_version config = Configurator(settings=settings) # ogcproxy import papyrus_ogcproxy config.include(papyrus_ogcproxy) # configure 'locale' dir as the translation dir for geoadmin app config.add_translation_dirs('geoadmin:locale/') config.add_subscriber(add_localizer, NewRequest) config.add_subscriber(add_renderer_globals, BeforeRender) # renderers config.add_renderer('.html', mako_renderer_factory) config.add_renderer('.js', mako_renderer_factory) config.add_renderer('jsonp', JSONP(param_name='cb', indent=4)) config.add_renderer('geojson', GeoJSON(jsonp_param_name='cb')) config.add_renderer('esrijson', EsriJSON(jsonp_param_name='callback')) config.add_renderer('csv', CSVRenderer) # sql section config.registry.dbmaker = scoped_session(sessionmaker()) config.add_request_method(db, reify=True) initialize_sql(settings) # Static config config.add_route('home', '/') config.add_route('testi18n', '/testi18n') config.add_route('api', '/loader.js') config.add_view(route_name='home', renderer='geoadmin:templates/index.pt', http_cache=0) config.add_view(route_name='testi18n', renderer='geoadmin:templates/testi18n.mako', http_cache=0) config.add_view(route_name='api', renderer='geoadmin:templates/loader.js', http_cache=0) # Application specific config.add_route('mapservice', '/rest/services/{map}/MapServer') config.add_route('identify', '/rest/services/{map}/MapServer/identify') config.add_route('getlegend', '/rest/services/{map}/MapServer/{idlayer}/getlegend') config.add_route('getfeature', '/rest/services/{map}/MapServer/{idlayer}/{idfeature}') config.add_route( 'htmlpopup', '/rest/services/{map}/MapServer/{idlayer}/{idfeature}/htmlpopup') config.add_route('wmtscapabilities', '/rest/services/{map}/1.0.0/WMTSCapabilities.xml') config.add_route('profile_json', '/rest/services/profile.json') config.add_route('profile_csv', '/rest/services/profile.csv') config.add_route('height', '/rest/services/height') config.add_route('geocodeservice', '/rest/services/GeocodeServer') config.add_route('findaddresscandidates', '/rest/services/GeocodeServer/findaddresscandidates') # Checker section config.add_route('checker_home', '/checker_home') config.add_route('checker_api', '/checker_api') config.scan(ignore='geoadmin.tests' ) # required to find code decorated by view_config config.add_static_view('static', 'geoadmin:static', cache_max_age=3600) return config.make_wsgi_app()
def includeme(config): """ This function returns a Pyramid WSGI application. """ # update the settings object from the YAML application config file settings = config.get_settings() settings.update(c2c.template.get_config(settings.get("app.cfg"))) call_hook(settings, "after_settings", settings) config.add_request_method(_create_get_user_from_request(settings), name="user", property=True) # configure 'locale' dir as the translation dir for c2cgeoportal app config.add_translation_dirs("c2cgeoportal:locale/") # initialize database engine = sqlalchemy.engine_from_config(settings, "sqlalchemy.") sqlahelper.add_engine(engine) config.include(pyramid_tm.includeme) config.include("pyramid_closure") if "sqlalchemy_slave.url" in settings and \ settings["sqlalchemy.url"] != settings["sqlalchemy_slave.url"]: # pragma: nocover # Setup a slave DB connection and add a tween to switch between it and the default one. log.info("Using a slave DB for reading") engine_slave = sqlalchemy.engine_from_config(config.get_settings(), "sqlalchemy_slave.") sqlahelper.add_engine(engine_slave, name="slave") config.add_tween("c2cgeoportal.models.db_chooser_tween_factory", over="pyramid_tm.tm_tween_factory") # initialize the dbreflection module dbreflection.init(engine) # dogpile.cache configuration caching.init_region(settings["cache"]) caching.invalidate_region() # Register a tween to get back the cache buster path. config.add_tween("c2cgeoportal.lib.cacheversion.CachebusterTween") # bind the mako renderer to other file extensions add_mako_renderer(config, ".html") add_mako_renderer(config, ".js") config.include("pyramid_chameleon") # add the "geojson" renderer config.add_renderer("geojson", GeoJSON()) # add decimal json renderer config.add_renderer("decimaljson", DecimalJSON()) # add the "xsd" renderer config.add_renderer( "xsd", XSD(sequence_callback=dbreflection._xsd_sequence_callback)) # 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) if settings.get("ogcproxy_enable", False): # pragma: no cover # add an OGCProxy view config.add_route_predicate("ogc_server", OgcproxyRoutePredicate) config.add_route("ogcproxy", "/ogcproxy", ogc_server=True) config.add_view("papyrus_ogcproxy.views:ogcproxy", route_name="ogcproxy") # add routes to the mapserver proxy config.add_route_predicate("mapserverproxy", MapserverproxyRoutePredicate) config.add_route( "mapserverproxy", "/mapserv_proxy", mapserverproxy=True, pregenerator=C2CPregenerator(role=True), ) # add route to the tinyows proxy config.add_route( "tinyowsproxy", "/tinyows_proxy", pregenerator=C2CPregenerator(role=True), ) # add routes to csv view config.add_route("csvecho", "/csv", request_method="POST") # add route to the export GPX/KMLÂ view config.add_route("exportgpxkml", "/exportgpxkml") # add routes to the echo service config.add_route("echo", "/echo", request_method="POST") # 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, "/loginchange", "login") config.add_route("loginchange", "/loginchange", 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_route("apijs", "/api.js", request_method="GET") config.add_route("xapijs", "/xapi.js", request_method="GET") config.add_route("apihelp", "/apihelp.html", request_method="GET") config.add_route("xapihelp", "/xapihelp.html", request_method="GET") config.add_route( "themes", "/themes", request_method="GET", pregenerator=C2CPregenerator(role=True), ) config.add_route("invalidate", "/invalidate", request_method="GET") # checker routes, Checkers are web services to test and assess that # the application is correctly functioning. # These web services are used by tools like (nagios). config.add_route("checker_routes", "/checker_routes", request_method="GET") config.add_route("checker_lang_files", "/checker_lang_files", request_method="GET") config.add_route("checker_pdf3", "/checker_pdf3", request_method="GET") config.add_route("checker_fts", "/checker_fts", request_method="GET") config.add_route("checker_theme_errors", "/checker_theme_errors", request_method="GET") config.add_route("checker_phantomjs", "/checker_phantomjs", request_method="GET") # collector config.add_route("check_collector", "/check_collector", 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, "/fulltextsearch", "fulltextsearch") config.add_route("fulltextsearch", "/fulltextsearch") # Access to raster data add_cors_route(config, "/raster", "raster") config.add_route("raster", "/raster", request_method="GET") add_cors_route(config, "/profile.{ext}", "profile") config.add_route("profile.csv", "/profile.csv", request_method="POST") config.add_route("profile.json", "/profile.json", request_method="POST") # shortener add_cors_route(config, "/short/create", "shortner") config.add_route("shortener_create", "/short/create", request_method="POST") config.add_route("shortener_get", "/short/{ref}", request_method="GET") # Geometry processing config.add_route("difference", "/difference", request_method="POST") # PDF report tool config.add_route("pdfreport", "/pdfreport/{layername}/{id}", 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=JSON_CONTENT_TYPE) config.add_route("layers_update", "/layers/{layer_id:\\d+}/{feature_id}", request_method="PUT", header=JSON_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's 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") # pyramid_formalchemy's configuration config.include("pyramid_formalchemy") config.include("fa.jquery") # define the srid, schema and parentschema # as global variables to be usable in the model c2cgeoportal.srid = settings["srid"] c2cgeoportal.schema = settings["schema"] c2cgeoportal.parentschema = settings["parentschema"] c2cgeoportal.formalchemy_default_zoom = get_setting( settings, ("admin_interface", "map_zoom"), c2cgeoportal.formalchemy_default_zoom) c2cgeoportal.formalchemy_default_x = get_setting( settings, ("admin_interface", "map_x"), c2cgeoportal.formalchemy_default_x) c2cgeoportal.formalchemy_default_y = get_setting( settings, ("admin_interface", "map_y"), c2cgeoportal.formalchemy_default_y) c2cgeoportal.formalchemy_available_functionalities = get_setting( settings, ("admin_interface", "available_functionalities"), c2cgeoportal.formalchemy_available_functionalities) c2cgeoportal.formalchemy_available_metadata = get_setting( settings, ("admin_interface", "available_metadata"), c2cgeoportal.formalchemy_available_metadata) c2cgeoportal.formalchemy_available_metadata = [ e if isinstance(e, basestring) else e.get("name") for e in c2cgeoportal.formalchemy_available_metadata ] config.add_route("checker_all", "/checker_all", request_method="GET") config.add_route("version_json", "/version.json", request_method="GET") stats.init(config) # scan view decorator for adding routes config.scan(ignore=["c2cgeoportal.tests", "c2cgeoportal.scripts"]) if "subdomains" in settings: # pragma: no cover config.registry.registerUtility(MultiDomainStaticURLInfo(), IStaticURLInfo) # add the static view (for static resources) _add_static_view(config, "static", "c2cgeoportal:static") _add_static_view(config, "project", "c2cgeoportal:project") add_admin_interface(config) add_static_view(config) # 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) _log_versions(settings)
def __init__(self, jsonp_param_name='callback'): GeoJSON.__init__(self) self.jsonp_param_name = jsonp_param_name
def _callFUT(self, **kwargs): from papyrus.renderers import GeoJSON fake_info = {} return GeoJSON(**kwargs)(fake_info)
def includeme(config: pyramid.config.Configurator) -> None: """Get the Pyramid WSGI application.""" settings = config.get_settings() 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") # Be able for an organization to override the method to use alternate: # - Organization roles name for the standard roles 'anonymous', 'registered' and 'intranet'. config.add_request_method(lambda request, role_type: role_type, name="get_organization_role") # - Organization print URL config.add_request_method( lambda request: request.registry.settings["print_url"], name="get_organization_print_url") # - Organization interface name (in the config and in the admin interface) config.add_request_method(lambda request, interface: interface, name="get_organization_interface") # Configure 'locale' dir as the translation dir for c2cgeoportal app config.add_translation_dirs("c2cgeoportal_geoportal:locale/") config.include("pyramid_mako") 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_db_sessions(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 ) # type: ignore def handle(event: InvalidateCacheEvent) -> None: del event caching.invalidate_region() if caching.MEMORY_CACHE_DICT: caching.get_region("std").delete_multi( list(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", "static-geomapfish"] 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("oauth2token", "/oauth/token", request_method="POST") config.add_route("oauth2loginform", "/oauth/login", request_method="GET") config.add_route("notlogin", "/notlogin", request_method="GET") 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", ) # The tow next views are used to serve the application on the URL /mapserv_proxy/<ogc server name> # instead of /mapserv_proxy?ogcserver=<ogc server name>, required for QGIS server landing page config.add_route( "mapserverproxy_get_path", "/mapserv_proxy/{ogcserver}/*path", mapserverproxy=True, pregenerator=C2CPregenerator(role=True), request_method="GET", ) config.add_route( "mapserverproxy_post_path", "/mapserv_proxy/{ogcserver}/*path", 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") config.add_route("localepot", "/locale.pot", 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") config.add_route("apijs", "/api.js", request_method="GET") 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") # Access to vector tiles add_cors_route(config, "/vector_tiles", "vector_tiles") config.add_route("vector_tiles", "/vector_tiles/{layer_name}/{z}/{x}/{y}.pbf", request_method="GET") # There is no view corresponding to that route, it is to be used from # mako templates to get the root of the "vector_tiles" web service config.add_route("vector_tiles_root", "/vector_tiles", request_method="HEAD") # 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"]), ) # Add the c2cgeoportal static view with cache buster config.add_static_view( name="static-geomapfish", path="c2cgeoportal_geoportal:static", cache_max_age=int(config.get_settings()["default_max_age"]), ) config.add_cache_buster("c2cgeoportal_geoportal:static", version_cache_buster) # Add the project static view without cache buster config.add_static_view( name="static-ngeo-dist", path="/opt/c2cgeoportal/geoportal/node_modules/ngeo/dist", 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>")
def includeme(config: pyramid.config.Configurator): """ This function returns a Pyramid WSGI application. """ settings = config.get_settings() config.include("c2cgeoportal_commons") 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) # Initialise DBSessions init_dbsessions(settings, config, health_check) # Initialize the dbreflection module dbreflection.init() checker.init(config, health_check) check_collector.init(config, health_check) # dogpile.cache configuration if 'cache' in settings: caching.init_region(settings['cache']) from c2cgeoportal_commons.models.main import InvalidateCacheEvent @zope.event.classhandler.handler(InvalidateCacheEvent) def handle(event: InvalidateCacheEvent): # pylint: disable=unused-variable del event caching.invalidate_region() # 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 decimal json renderer config.add_renderer("decimaljson", DecimalJSON()) # 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, "/loginchange", "login") config.add_route("loginchange", "/loginchange", 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") # Cannot be at the header to do not load the model too early from c2cgeoportal_geoportal.views.entry import Entry def add_api_route(name: str, attr: str, path: str, renderer: str): config.add_route(name, path, request_method="GET") config.add_view(Entry, attr=attr, route_name=name, renderer=renderer) add_api_route('favicon', 'favicon', '/favicon.ico', '/etc/geomapfish/static/images/favicon.ico') add_api_route('apijs', 'apijs', '/api.js', "/etc/static-ngeo/api.js") add_api_route('apijsmap', 'apijsmap', '/api.js.map', "/etc/static-ngeo/api.js.map") add_api_route('apicss', 'apicss', '/api.css', "/etc/static-ngeo/api.css") add_api_route('apihelp', 'apihelp', '/apihelp/index.html', "/etc/geomapfish/static/apihelp/index.html") c2cgeoportal_geoportal.views.add_redirect(config, 'apihelp_redirect', '/apihelp.html', '/apihelp/index.html') 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 the project static view with cache buster from c2cgeoportal_geoportal.lib.cacheversion import version_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>')
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ load_processing_settings(settings) load_local_settings(settings, settings["appname"]) settings.update({"version": version}) config = Configurator(root_factory=Root, settings=settings) config.set_authorization_policy(ACLAuthorizationPolicy()) config.set_authentication_policy( BasicAuthAuthenticationPolicy(check=groupfinder, )) # set forbidden view to basic auth def forbidden_view(request): resp = HTTPUnauthorized() resp.www_authenticate = 'Basic realm="Thinkhazard"' return resp config.add_forbidden_view(forbidden_view) config.include("pyramid_jinja2") config.include("papyrus") config.include("thinkhazard.session") config.add_tween("thinkhazard.tweens.notmodified_tween_factory", over=MAIN) config.add_static_view("static", "static", cache_max_age=3600) config.add_static_view("lib", settings.get("node_modules"), cache_max_age=86000) config.add_translation_dirs("thinkhazard:locale") config.set_locale_negotiator("thinkhazard.i18n.custom_locale_negotiator") config.add_route("healthcheck", "/healthcheck") if settings["appname"] == "public": config.include(add_public_routes) config.add_route("sitemap", "/sitemap.xml") if settings["appname"] == "admin": # Celery from thinkhazard.celery import app as celery_app config.add_request_method(lambda x: celery_app, "celery_app", reify=True) config.set_default_permission("admin") config.include(add_public_routes, route_prefix="preview") config.add_route("admin_index", "/") config.add_route("admin_add_task", "/addtask") config.add_route("admin_technical_rec", "/technical_rec") config.add_route("admin_technical_rec_new", "/technical_rec/new") config.add_route("admin_technical_rec_edit", "/technical_rec/{id:\d+}") config.add_route("admin_technical_rec_delete", "/technical_rec/{id:\d+}/delete") config.add_route("admin_admindiv_hazardsets", "/admindiv_hazardsets") config.add_route("admin_admindiv_hazardsets_export", "/admindiv_hazardsets_export") config.add_route( "admin_admindiv_hazardsets_hazardtype", "/admindiv_hazardsets/{hazardtype:([A-Z]{2})}", ) config.add_route("admin_climate_rec", "/climate_rec") config.add_route("admin_climate_rec_hazardtype", "/climate_rec/{hazard_type:([A-Z]{2})}") config.add_route("admin_climate_rec_new", "/climate_rec/{hazard_type:([A-Z]{2})}/new") config.add_route("admin_climate_rec_edit", "/climate_rec/{id:\d+}") config.add_route("admin_climate_rec_delete", "/climate_rec/{id:\d+}/delete") config.add_route("admin_hazardcategories", "/hazardcategories") config.add_route( "admin_hazardcategory", "/hazardcategory/{hazard_type:([A-Z]{2})}" "/{hazard_level:([A-Z]{3})}", ) config.add_route("admin_hazardsets", "/hazardsets") config.add_route("admin_hazardset", "/hazardset/{hazardset}") config.add_route("admin_contacts", "/contacts") config.add_route("admin_contact_new", "/contact/new") config.add_route("admin_contact_edit", "/contact/{id:\d+}") config.add_route("admin_contact_delete", "/contact/{id:\d+}/delete") config.add_route("admin_contact_admindiv_hazardtype_association", "/contact/CAdHt_form") config.add_renderer("geojson", GeoJSON()) config.add_renderer("csv", "thinkhazard.renderers.CSVRenderer") config.add_request_method( lambda r: S3Helper(r.registry.settings), "s3_helper", property=True, reify=True, ) scan_ignore = [] if settings["appname"] != "public": scan_ignore.append("thinkhazard.views.sitemap") if settings["appname"] != "admin": scan_ignore.append("thinkhazard.views.admin") config.scan(ignore=scan_ignore) return config.make_wsgi_app()
def includeme(config): """ This function returns a Pyramid WSGI application. """ settings = config.get_settings() yaml_config = yaml.load(file(settings.get("app.cfg"))) settings.update(yaml_config) my_session_factory = SignedCookieSessionFactory( yaml_config['authtkt_secret'], cookie_name=yaml_config['authtkt_cookie_name'], timeout=8200 ) config.set_session_factory(my_session_factory) engine = engine_from_config(settings, 'sqlalchemy.') sqlahelper.add_engine(engine) global db_config db_config = yaml.load(file(settings.get('database.cfg')))['db_config'] settings.update(yaml.load(file(settings.get('pdf.cfg')))) config.include(papyrus.includeme) config.include('pyramid_mako') # bind the mako renderer to other file extensions add_mako_renderer(config, ".js") config.add_renderer('geojson', GeoJSON()) # add app configuration from db read_app_config(settings) specific_tmp_path = os.path.join(settings['specific_root_dir'], 'templates') specific_static_path = os.path.join(settings['specific_root_dir'], 'static') settings.setdefault('mako.directories',['crdppf:templates', specific_tmp_path]) settings.setdefault('reload_templates',True) # add the static view (for static resources) config.add_static_view('static', 'crdppf:static',cache_max_age=3600) config.add_static_view('proj', 'crdppfportal:static', cache_max_age=3600) # ROUTES config.add_route('home', '/') config.add_route('images', '/static/images/') config.add_route('create_extract', 'create_extract') config.add_route('get_features', 'get_features') config.add_route('get_property', 'property/get') config.add_route('set_language', 'set_language') config.add_route('get_language', 'get_language') config.add_route('get_translation_dictionary', 'get_translation_dictionary') config.add_route('get_translations_list', 'get_translations_list') config.add_route('get_interface_config', 'get_interface_config') config.add_route('get_baselayers_config', 'get_baselayers_config') config.add_route('test', 'test') config.add_route('formulaire_reglements', 'formulaire_reglements') config.add_route('getTownList', 'getTownList') config.add_route('getTopicsList', 'getTopicsList') config.add_route('createNewDocEntry', 'createNewDocEntry') config.add_route('document_ref', 'getDocumentReferences') config.add_route('legal_documents', 'getLegalDocuments') config.add_route('map', 'map') config.add_route('configpanel', 'configpanel') config.add_route('initjs', '/init.js') config.add_route('globalsjs', '/globals.js') config.add_route('ogcproxy', '/ogcproxy') # CLIENT VIEWS config.add_view('crdppf.views.entry.Entry', route_name = 'images') config.add_view('crdppf.views.entry.Entry', route_name='test') # Print proxy routes config.add_route('printproxy_report_get', '/printproxy/report/{ref}') config.add_route('printproxy_status', '/printproxy/status/{ref}.json') config.add_route('printproxy_report_create', '/printproxy/report/{type_}/{id}') #~ # ADMIN VIEWS #~ config.add_view('crdppf.views.administration.Config', route_name='configpanel') #~ config.add_view('crdppf.views.administration.Config', route_name='formulaire_reglements') config.add_route('catchall_static', '/*subpath') config.add_view('crdppf.static.static_view', route_name='catchall_static') config.scan()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ global scheduler scheduler = BackgroundScheduler() scheduler.start() load_processing_settings(settings) load_local_settings(settings, settings['appname']) settings.update({'version': version}) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.include('papyrus') config.add_tween('thinkhazard.tweens.notmodified_tween_factory') config.add_static_view('static', 'static', cache_max_age=3600, cachebust=True) config.add_static_view('lib', settings.get('node_modules'), cache_max_age=86000, cachebust=True) config.add_translation_dirs('thinkhazard:locale') config.set_locale_negotiator('thinkhazard.i18n.custom_locale_negotiator') if settings['appname'] == 'public': config.include(add_public_routes) config.add_route('sitemap', '/sitemap.xml') if settings['appname'] == 'admin': config.include(add_public_routes, route_prefix='preview') config.add_route('admin_index', '/') config.add_route('admin_technical_rec', '/technical_rec') config.add_route('admin_technical_rec_new', '/technical_rec/new') config.add_route('admin_technical_rec_edit', '/technical_rec/{id:\d+}') config.add_route('admin_technical_rec_delete', '/technical_rec/{id:\d+}/delete') config.add_route('admin_admindiv_hazardsets', '/admindiv_hazardsets') config.add_route('admin_admindiv_hazardsets_export', '/admindiv_hazardsets_export') config.add_route('admin_admindiv_hazardsets_hazardtype', '/admindiv_hazardsets/{hazardtype:([A-Z]{2})}') config.add_route('admin_climate_rec', '/climate_rec') config.add_route('admin_climate_rec_hazardtype', '/climate_rec/{hazard_type:([A-Z]{2})}') config.add_route('admin_climate_rec_new', '/climate_rec/{hazard_type:([A-Z]{2})}/new') config.add_route('admin_climate_rec_edit', '/climate_rec/{id:\d+}') config.add_route('admin_climate_rec_delete', '/climate_rec/{id:\d+}/delete') config.add_route('admin_hazardcategories', '/hazardcategories') config.add_route('admin_hazardcategory', '/hazardcategory/{hazard_type:([A-Z]{2})}' '/{hazard_level:([A-Z]{3})}') config.add_route('admin_hazardsets', '/hazardsets') config.add_route('admin_hazardset', '/hazardset/{hazardset}') config.add_route('admin_contacts', '/contacts') config.add_route('admin_contact_new', '/contact/new') config.add_route('admin_contact_edit', '/contact/{id:\d+}') config.add_route('admin_contact_delete', '/contact/{id:\d+}/delete') config.add_route('admin_contact_admindiv_hazardtype_association', '/contact/CAdHt_form') config.add_renderer('geojson', GeoJSON()) config.add_renderer('csv', 'thinkhazard.renderers.CSVRenderer') scan_ignore = ['thinkhazard.tests'] if settings['appname'] != 'public': scan_ignore.append('thinkhazard.views.sitemap') if settings['appname'] != 'admin': scan_ignore.append('thinkhazard.views.admin') config.scan(ignore=scan_ignore) return config.make_wsgi_app()
def includeme(config): """ This function returns a Pyramid WSGI application. """ # update the settings object from the YAML application config file settings = config.get_settings() settings.update(yaml.load(file(settings.get("app.cfg")))) global srid global schema global parentschema global formalchemy_language global formalchemy_default_zoom global formalchemy_default_x global formalchemy_default_y global formalchemy_available_functionalities global formalchemy_available_metadata config.add_request_method(_create_get_user_from_request(settings), name="user", property=True) # configure 'locale' dir as the translation dir for c2cgeoportal app config.add_translation_dirs("c2cgeoportal:locale/") # initialize database engine = sqlalchemy.engine_from_config(settings, "sqlalchemy.") sqlahelper.add_engine(engine) config.include(pyramid_tm.includeme) config.include("pyramid_closure") # initialize the dbreflection module dbreflection.init(engine) # dogpile.cache configuration caching.init_region(settings["cache"]) caching.invalidate_region() # bind the mako renderer to other file extensions add_mako_renderer(config, ".html") add_mako_renderer(config, ".js") config.include("pyramid_chameleon") # add the "geojson" renderer config.add_renderer("geojson", GeoJSON()) # add decimal json renderer config.add_renderer("decimaljson", DecimalJSON()) # add the "xsd" renderer config.add_renderer( "xsd", XSD(sequence_callback=dbreflection._xsd_sequence_callback)) # 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) if settings.get("ogcproxy_enable", True): # add an OGCProxy view config.add_route("ogcproxy", "/ogcproxy", custom_predicates=(ogcproxy_route_predicate, )) config.add_view("papyrus_ogcproxy.views:ogcproxy", route_name="ogcproxy") # add routes to the mapserver proxy config.add_route( "mapserverproxy", "/mapserv_proxy", custom_predicates=(mapserverproxy_route_predicate, ), pregenerator=C2CPregenerator(role=True), ) # add route to the tinyows proxy config.add_route( "tinyowsproxy", "/tinyows_proxy", pregenerator=C2CPregenerator(role=True), ) # add routes to csv view config.add_route("csvecho", "/csv", request_method="POST") # add route to the export GPX/KMLÂ view config.add_route("exportgpxkml", "/exportgpxkml") # add routes to the echo service config.add_route("echo", "/echo", request_method="POST") # add routes to the entry view class config.add_route("loginform", "/login.html", request_method="GET") add_cors_route(config, "/login", "login") config.add_route("login", "/login", request_method=("GET", "POST")) add_cors_route(config, "/logout", "login") config.add_route("logout", "/logout", request_method="GET") add_cors_route(config, "/loginchange", "login") config.add_route("loginchange", "/loginchange", request_method="POST") add_cors_route(config, "/loginresetpassword", "login") config.add_route("loginresetpassword", "/loginresetpassword", request_method="GET") config.add_route("testi18n", "/testi18n.html", request_method="GET") config.add_route("apijs", "/api.js", request_method="GET") config.add_route("xapijs", "/xapi.js", request_method="GET") config.add_route("apihelp", "/apihelp.html", request_method="GET") config.add_route("xapihelp", "/xapihelp.html", request_method="GET") config.add_route( "themes", "/themes", request_method="GET", pregenerator=C2CPregenerator(role=True), ) config.add_route("invalidate", "/invalidate", request_method="GET") # checker routes, Checkers are web services to test and assess that # the application is correctly functioning. # These web services are used by tools like (nagios). config.add_route("checker_main", "/checker_main", request_method="GET") config.add_route("checker_viewer", "/checker_viewer", request_method="GET") config.add_route("checker_edit", "/checker_edit", request_method="GET") config.add_route("checker_edit_js", "/checker_edit_js", request_method="GET") config.add_route("checker_api", "/checker_api", request_method="GET") config.add_route("checker_xapi", "/checker_xapi", request_method="GET") config.add_route("checker_lang_files", "/checker_lang_files", request_method="GET") config.add_route( "checker_printcapabilities", "/checker_printcapabilities", request_method="GET", ) config.add_route("checker_pdf", "/checker_pdf", request_method="GET") config.add_route( "checker_print3capabilities", "/checker_print3capabilities", request_method="GET", ) config.add_route("checker_pdf3", "/checker_pdf3", request_method="GET") config.add_route("checker_fts", "/checker_fts", request_method="GET") config.add_route("checker_wmscapabilities", "/checker_wmscapabilities", request_method="GET") config.add_route("checker_wfscapabilities", "/checker_wfscapabilities", request_method="GET") config.add_route("checker_theme_errors", "/checker_theme_errors", request_method="GET") # collector config.add_route("check_collector", "/check_collector", request_method="GET") # print proxy routes config.add_route("printproxy", "/printproxy", request_method="HEAD") config.add_route( "printproxy_info", "/printproxy/info.json", request_method="GET", pregenerator=C2CPregenerator(role=True), ) config.add_route( "printproxy_create", "/printproxy/create.json", request_method="POST", ) config.add_route( "printproxy_get", "/printproxy/{file}.printout", request_method="GET", ) # V3 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, "/fulltextsearch", "fulltextsearch") config.add_route("fulltextsearch", "/fulltextsearch") # Access to raster data add_cors_route(config, "/raster", "raster") config.add_route("raster", "/raster", request_method="GET") add_cors_route(config, "/profile.{ext}", "profile") config.add_route("profile.csv", "/profile.csv", request_method="POST") config.add_route("profile.json", "/profile.json", request_method="POST") # shortener config.add_route("shortener_create", "/short/create", request_method="POST") config.add_route("shortener_get", "/short/{ref}", request_method="GET") # Geometry processing config.add_route("difference", "/difference", request_method="POST") # PDF report tool config.add_route("pdfreport", "/pdfreport/{layername}/{id}", 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=JSON_CONTENT_TYPE) config.add_route("layers_update", "/layers/{layer_id:\\d+}/{feature_id}", request_method="PUT", header=JSON_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's 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") # pyramid_formalchemy's configuration config.include("pyramid_formalchemy") config.include("fa.jquery") # define the srid, schema and parentschema # as global variables to be usable in the model srid = settings["srid"] schema = settings["schema"] parentschema = settings["parentschema"] formalchemy_default_zoom = get_setting(settings, ("admin_interface", "map_zoom"), formalchemy_default_zoom) formalchemy_default_x = get_setting(settings, ("admin_interface", "map_x"), formalchemy_default_x) formalchemy_default_y = get_setting(settings, ("admin_interface", "map_y"), formalchemy_default_y) formalchemy_available_functionalities = get_setting( settings, ("admin_interface", "available_functionalities"), formalchemy_available_functionalities) formalchemy_available_metadata = get_setting( settings, ("admin_interface", "available_metadata"), formalchemy_available_metadata) config.add_route("checker_all", "/checker_all", request_method="GET") # scan view decorator for adding routes config.scan(ignore="c2cgeoportal.tests") config.registry.registerUtility(MultiDomainStaticURLInfo(), IStaticURLInfo) # add the static view (for static resources) _add_static_view(config, "static", "c2cgeoportal:static") _add_static_view(config, "project", "c2cgeoportal:project") add_admin_interface(config) add_static_view(config) # 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)
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine init_model() session_factory = session_factory_from_settings(settings) if 'localization' not in settings: settings['localization'] = 'id_ID.UTF-8' locale.setlocale(locale.LC_ALL, settings['localization']) if 'timezone' not in settings: settings['timezone'] = DefaultTimeZone config = Configurator(settings=settings, root_factory='opensipkd.models.RootFactory', session_factory=session_factory) modules = get_modules(settings) for module in modules: if module=='admin': continue module = module.replace('/','.') mfile = 'opensipkd.'+module m = __import__(mfile,globals(), locals(),'main',0) m.main(global_config, **settings) config.include('pyramid_beaker') config.include('pyramid_chameleon') authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=group_finder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_request_method(get_user, 'user', reify=True) config.add_request_method(get_title, 'title', reify=True) config.add_request_method(get_company, 'company', reify=True) config.add_request_method(get_departement, 'departement', reify=True) config.add_request_method(get_ibukota, 'ibukota', reify=True) config.add_request_method(get_address, 'address', reify=True) config.add_request_method(get_address2, 'address2', reify=True) config.add_request_method(get_app_name, 'app_name', reify=True) config.add_request_method(get_modules, 'modules', reify=True) #config.add_request_method(thousand, 'thousand', reify=True) config.add_notfound_view(RemoveSlashNotFoundViewFactory()) config.add_static_view('static', 'static', cache_max_age=3600) config.add_static_view('deform_static', 'deform:static') config.add_static_view('files', settings['static_files']) config.add_renderer('csv', '.tools.CSVRenderer') routes = DBSession.query(Route.kode, Route.path, Route.nama).\ filter(Route.type==0).all() #standar route for route in routes: config.add_route(route.kode, route.path) if route.nama: titles[route.kode] = route.nama ############################################################################ #Custom JSON json_renderer = JSON() json_renderer.add_adapter(datetime.datetime, lambda v, request: dmy(v)) json_renderer.add_adapter(datetime.date, lambda v, request: dmy(v)) json_renderer.add_adapter(decimal.Decimal, lambda v, request: str(v)) config.add_renderer('json', json_renderer) ############################################################################ # JSON RPC config.include('pyramid_rpc.jsonrpc') json_renderer = JSON() json_renderer.add_adapter(datetime.datetime, lambda v, request: v.isoformat()) json_renderer.add_adapter(datetime.date, lambda v, request: v.isoformat()) config.add_renderer('json_rpc', json_renderer) routes = DBSession.query(Route.kode, Route.path, Route.nama).\ filter(Route.type==1).all() # for route in routes: config.add_jsonrpc_endpoint(route.kode, route.path, default_renderer="json_rpc") ############################################################################ #config.add_jsonrpc_endpoint('ws_pbb', '/pbb/api', default_renderer="json_rpc") #config.add_jsonrpc_endpoint('ws_keuangan', '/ws/keuangan', default_renderer="json_rpc") #config.add_jsonrpc_endpoint('ws_user', '/ws/user', default_renderer="json_rpc") ############################################################################ ########################################### #MAP ########################################### if 'map' in modules: import papyrus from papyrus.renderers import GeoJSON, XSD config.add_request_method(get_gmap_key, 'gmap', reify=True) config.include(papyrus.includeme) config.add_renderer('geojson', GeoJSON()) config.add_renderer('xsd', XSD()) config.add_static_view('static_map', 'map/static', cache_max_age=3600) if 'map/aset' in modules: config.add_static_view('static_map_aset', 'map/aset/static', cache_max_age=3600) if 'map/pbb' in modules: config.add_static_view('static_map_pbb', 'map/pbb/static', cache_max_age=3600) config.scan() app = config.make_wsgi_app() from paste.translogger import TransLogger app = TransLogger(app, setup_console_handler=False) return app
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) try: #create the tables if they do not yet exist Base.metadata.create_all(engine) except: pass # drop the newly created tables and replace them by views (did not find how to do this otherwise, but works) s0a = text("""drop view v_bus_delays_concat""") s0b = text("""create or replace view v_bus_delays_concat as select *, '<tr><td> ' || line || '</td><td>' || destination || '</td><td>' || delay || 'min</td><td>' || to_char(departure,'HH24:MI') || '</td></tr>' as formatted from busdelays order by formatted asc;""") s1a = text("""drop table v_bus_average_delays_by_line;""") s1b = text("""drop view v_bus_average_delays_by_line;""") s1c = text("""create or replace view v_bus_average_delays_by_line as select id,time,geom,name,line,avg(delay) as mean_delay, string_agg(formatted ,'' order by line asc, destination asc, departure asc) as formatted_delay_info, avg(delay)/ 5 as weight from v_bus_delays_concat group by (id,time,geom,name,line);""") s2a = text("""drop table v_bus_average_delays;""") s2b = text("""drop view v_bus_average_delays;""") s2c = text("""create or replace view v_bus_average_delays as select id,time,geom,name,avg(delay) as mean_delay, string_agg(formatted ,'' order by line asc, destination asc, departure asc) as formatted_delay_info , avg(delay)/ 5 as weight from v_bus_delays_concat group by (id,time,geom,name);""") i1 = text("""CREATE INDEX bus_average_delays_idx ON busdelays (id,time,geom,name);""") i2 = text("""CREATE INDEX bus_average_delays_by_line_idx ON busdelays (id,time,geom,name,line);""") c = engine.connect() try: c.execute(s2b) except: pass try: c.execute(s1b) except: pass try: c.execute(s0a) except: pass try: c.execute(s0b) except: pass try: c.execute(s1a) except: pass try: c.execute(s1c) except: pass try: c.execute(s2a) except: pass try: c.execute(s2c) except: pass try: c.execute(i1) except: pass try: c.execute(i2) except: pass config.add_renderer('geojson', GeoJSON()) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('data', '/data') config.add_route('timestamps', '/timestamps') config.add_route('lines', '/lines') config.scan() return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ app_version = settings.get('app_version') settings['app_version'] = app_version config = Configurator(settings=settings) config.include('pyramid_mako') # configure 'locale' dir as the translation dir for chsdi app config.add_translation_dirs('chsdi:locale/') config.add_subscriber(add_localizer, NewRequest) config.add_subscriber(add_renderer_globals, BeforeRender) # renderers config.add_mako_renderer('.html') config.add_mako_renderer('.js') config.add_renderer( 'jsonp', JSONP(param_name='callback', indent=None, separators=(',', ':'))) config.add_renderer('geojson', GeoJSON(jsonp_param_name='callback')) config.add_renderer('esrijson', EsriJSON(jsonp_param_name='callback')) config.add_renderer('csv', CSVRenderer) # sql section config.registry.dbmaker = scoped_session(sessionmaker()) config.add_request_method(db, reify=True) initialize_sql(settings) # route definitions config.add_route('dev', '/dev') config.add_route('ga_api', '/loader.js') config.add_route('testi18n', '/testi18n') config.add_route('topics', '/rest/services') config.add_route('mapservice', '/rest/services/{map}/MapServer') config.add_route('layersConfig', '/rest/services/{map}/MapServer/layersConfig') config.add_route('catalog', '/rest/services/{map}/CatalogServer') config.add_route('identify', '/rest/services/{map}/MapServer/identify') config.add_route('find', '/rest/services/{map}/MapServer/find') config.add_route( 'attribute_values', '/rest/services/{map}/MapServer/{layerId}/attributes/{attribute}') config.add_route('legend', '/rest/services/{map}/MapServer/{layerId}/legend') config.add_route('releases', '/rest/services/{map}/MapServer/{layerId}/releases') config.add_route('cacheUpdate', '/rest/services/{map}/MapServer/{layerId}/cacheUpdate') config.add_route('featureAttributes', '/rest/services/{map}/MapServer/{layerId}') config.add_route('feature', '/rest/services/{map}/MapServer/{layerId}/{featureId}') config.add_route( 'htmlPopup', '/rest/services/{map}/MapServer/{layerId}/{featureId}/htmlPopup') config.add_route( 'iframeHtmlPopup', '/rest/services/{map}/MapServer/{layerId}/{featureId}/iframeHtmlPopup') config.add_route( 'extendedHtmlPopup', '/rest/services/{map}/MapServer/{layerId}/{featureId}/extendedHtmlPopup' ) config.add_route('search', '/rest/services/{map}/SearchServer') config.add_route('wmtscapabilities', '/rest/services/{map}/1.0.0/WMTSCapabilities.xml') config.add_route('feedback', '/feedback') config.add_route('qrcodegenerator', '/qrcodegenerator') config.add_route('sitemap', '/sitemap') config.add_route('luftbilder', '/luftbilder/viewer.html') config.add_route('historicalmaps', '/historicalmaps/viewer.html') config.add_route('checker', '/checker') config.add_route('checker_dev', '/checker_dev') config.add_route('backend_checker', '/backend_checker') config.add_route('downloadkml', '/downloadkml') config.add_route('translations', '/rest/services/translations') config.add_route('wmsconfig', '/rest/services/wmsconfig') # kml files config.add_route('files_collection', '/files', request_method=('GET', 'POST', 'DELETE')) add_cors_route(config, '/files', 'files_collection', headers={'Access-Control-Allow-Credentials': 'true'}, methods=['GET', 'POST', 'DELETE']) config.add_route('files', '/files/{id}', request_method=('GET', 'POST', 'DELETE')) add_cors_route(config, '/files/{id}', 'files', headers={'Access-Control-Allow-Credentials': 'true'}, methods=['GET', 'POST', 'DELETE']) # glstyles json files config.add_route('glstyles_collection', '/gl-styles', request_method=('GET', 'POST', 'DELETE')) add_cors_route(config, '/gl-styles', 'glstyles_collection', headers={'Access-Control-Allow-Credentials': 'true'}, methods=['GET', 'POST', 'DELETE']) config.add_route('glstyles', '/gl-styles/{id}', request_method=('GET', 'POST', 'DELETE')) add_cors_route(config, '/gl-styles/{id}', 'glstyles', headers={'Access-Control-Allow-Credentials': 'true'}, methods=['GET', 'POST', 'DELETE']) config.add_route('adminkml', '/admin/kml') config.add_route('stationboard', '/stationboard/stops/{id}') config.add_route('faqlist', '/rest/services/{map}/faqlist') config.add_route('cut', '/rest/services/{map}/GeometryServer/cut') config.add_route('color', '/color/{r},{g},{b}/{image}') # Some views for specific routes config.add_view(route_name='dev', renderer='chsdi:templates/index.mako') config.add_view(route_name='testi18n', renderer='chsdi:templates/testi18n.mako') # Shortener config.add_route('shorten', '/shorten.json') config.add_route('shorten_redirect', '/shorten/{id}') # static view definitions config.add_static_view('static', 'chsdi:static') config.add_static_view('images', 'chsdi:static/images') config.add_static_view('examples', 'chsdi:static/doc/examples') config.add_static_view('vectorStyles', 'chsdi:static/vectorStyles') # keep this the last one config.add_static_view('/', 'chsdi:static/doc/build') # required to find code decorated by view_config config.scan(ignore=['chsdi.tests', 'chsdi.models.bod']) return config.make_wsgi_app()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ app_version = settings.get('app_version') settings['app_version'] = app_version config = Configurator(settings=settings) # configure 'locale' dir as the translation dir for chsdi app config.add_translation_dirs('chsdi:locale/') config.add_subscriber(add_localizer, NewRequest) config.add_subscriber(add_renderer_globals, BeforeRender) # renderers config.add_renderer('.html', mako_renderer_factory) config.add_renderer('.js', mako_renderer_factory) config.add_renderer('jsonp', JSONP(param_name='callback', indent=4)) config.add_renderer('geojson', GeoJSON(jsonp_param_name='callback')) config.add_renderer('esrijson', EsriJSON(jsonp_param_name='callback')) config.add_renderer('csv', CSVRenderer) # sql section config.registry.dbmaker = scoped_session(sessionmaker()) config.add_request_method(db, reify=True) initialize_sql(settings) # route definitions config.add_route('ogcproxy', '/ogcproxy') config.add_route('dev', '/dev') config.add_route('ga_api', '/uncached_loader.js') config.add_route('testi18n', '/testi18n') config.add_route('topics', '/rest/services') config.add_route('mapservice', '/rest/services/{map}/MapServer') config.add_route('layersConfig', '/rest/services/{map}/MapServer/layersConfig') config.add_route('catalog', '/rest/services/{map}/CatalogServer') config.add_route('identify', '/rest/services/{map}/MapServer/identify') config.add_route('find', '/rest/services/{map}/MapServer/find') config.add_route('legend', '/rest/services/{map}/MapServer/{layerId}/legend') config.add_route('featureAttributes', '/rest/services/{map}/MapServer/{layerId}') config.add_route('feature', '/rest/services/{map}/MapServer/{layerId}/{featureId}') config.add_route( 'htmlPopup', '/rest/services/{map}/MapServer/{layerId}/{featureId}/htmlPopup') config.add_route( 'extendedHtmlPopup', '/rest/services/{map}/MapServer/{layerId}/{featureId}/extendedHtmlPopup' ) config.add_route('search', '/rest/services/{map}/SearchServer') config.add_route('wmtscapabilities', '/rest/services/{map}/1.0.0/WMTSCapabilities.xml') config.add_route('profile_json', '/rest/services/profile.json') config.add_route('profile_csv', '/rest/services/profile.csv') config.add_route('height', '/rest/services/height') config.add_route('feedback', '/feedback') config.add_route('owschecker_bykvp', '/owschecker/bykvp') config.add_route('owschecker_form', '/owschecker/form') config.add_route('qrcodegenerator', '/qrcodegenerator') config.add_route('sitemap', '/sitemap') config.add_route('luftbilder', '/luftbilder/viewer.html') config.add_route('checker', '/checker') config.add_route('checker_dev', '/checker_dev') # Some views for specific routes config.add_view(route_name='dev', renderer='chsdi:templates/index.pt') config.add_view(route_name='testi18n', renderer='chsdi:templates/testi18n.mako') # Shortener config.add_route('shorten', '/shorten.json') config.add_route('shorten_redirect', '/shorten/{id}') # static view definitions config.add_static_view('static', 'chsdi:static') config.add_static_view('images', 'chsdi:static/images') config.add_static_view('examples', 'chsdi:static/doc/examples') # keep this the last one config.add_static_view('/', 'chsdi:static/doc/build') # required to find code decorated by view_config config.scan( ignore=['chsdi.tests', 'chsdi.models.bod', 'chsdi.models.vector']) return config.make_wsgi_app()
def includeme(config): """ This function returns a Pyramid WSGI application. """ # update the settings object from the YAML application config file settings = config.get_settings() settings.update(yaml.load(file(settings.get('app.cfg')))) global srid global schema global parentschema global formalchemy_language global formalchemy_default_zoom global formalchemy_default_x global formalchemy_default_y global formalchemy_available_functionalities config.set_request_property( get_user_from_request, name='user', reify=True) # configure 'locale' dir as the translation dir for c2cgeoportal app config.add_translation_dirs('c2cgeoportal:locale/') # initialize database engine = sqlalchemy.engine_from_config( config.get_settings(), 'sqlalchemy.') sqlahelper.add_engine(engine) config.include(pyramid_tm.includeme) # initialize the dbreflection module dbreflection.init(engine) # dogpile.cache configuration caching.init_region(settings['cache']) caching.invalidate_region() # bind the mako renderer to other file extensions config.add_renderer('.html', mako_renderer_factory) config.add_renderer('.js', mako_renderer_factory) # add the "geojson" renderer config.add_renderer('geojson', GeoJSON()) # add decimal json renderer config.add_renderer('decimaljson', DecimalJSON()) # add the "xsd" renderer config.add_renderer('xsd', XSD( sequence_callback=dbreflection._xsd_sequence_callback)) # 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) # add an OGCProxy view config.add_route( 'ogcproxy', '/ogcproxy', custom_predicates=(ogcproxy_route_predicate,)) config.add_view('papyrus_ogcproxy.views:ogcproxy', route_name='ogcproxy') # add routes to the mapserver proxy config.add_route( 'mapserverproxy', '/mapserv_proxy', custom_predicates=(mapserverproxy_route_predicate,), pregenerator=MultiDomainPregenerator()) # add routes to csv view config.add_route('csvecho', '/csv') # add routes to the echo service config.add_route('echo', '/echo') # add routes to the entry view class config.add_route('home', '/') config.add_route('viewer', '/viewer.js') config.add_route('edit', '/edit') config.add_route('edit.js', '/edit.js') config.add_route('routing', '/routing') config.add_route('routing.js', '/routing.js') config.add_route('loginform', '/login.html') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('loginchange', '/loginchange') config.add_route('testi18n', '/testi18n.html') config.add_route('apijs', '/api.js') config.add_route('xapijs', '/xapi.js') config.add_route('apihelp', '/apihelp.html') config.add_route('xapihelp', '/xapihelp.html') config.add_route('themes', '/themes') # permalink theme: recover the theme for generating custom viewer.js url config.add_route('permalinktheme', '/theme/*themes') # checker routes, Checkers are web services to test and assess that # the application is correctly functioning. # These web services are used by tools like (nagios). config.add_route('checker_main', '/checker_main') config.add_route('checker_viewer', '/checker_viewer') config.add_route('checker_edit', '/checker_edit') config.add_route('checker_edit_js', '/checker_edit_js') config.add_route('checker_api', '/checker_api') config.add_route('checker_xapi', '/checker_xapi') config.add_route('checker_printcapabilities', '/checker_printcapabilities') config.add_route('checker_pdf', '/checker_pdf') config.add_route('checker_fts', '/checker_fts') config.add_route('checker_wmscapabilities', '/checker_wmscapabilities') config.add_route('checker_wfscapabilities', '/checker_wfscapabilities') # collector config.add_route('check_collector', '/check_collector') # print proxy routes config.add_route('printproxy', '/printproxy') config.add_route('printproxy_info', '/printproxy/info.json') config.add_route('printproxy_create', '/printproxy/create.json') config.add_route('printproxy_get', '/printproxy/{file}.printout') # full text search routes config.add_route('fulltextsearch', '/fulltextsearch') # Access to raster data config.add_route('raster', '/raster') config.add_route('profile.csv', '/profile.csv') config.add_route('profile.json', '/profile.json') # shortener config.add_route('shortener_create', '/short/create') config.add_route('shortener_get', '/short/{ref}') # add routes for the "layers" web service 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') 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') config.add_route( 'layers_update', '/layers/{layer_id:\\d+}/{feature_id}', request_method='PUT') 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') # there's 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/') # pyramid_formalchemy's configuration config.include('pyramid_formalchemy') config.include('fa.jquery') # define the srid, schema and parentschema # as global variables to be usable in the model srid = config.get_settings()['srid'] schema = config.get_settings()['schema'] parentschema = config.get_settings()['parentschema'] settings = config.get_settings() formalchemy_default_zoom = get_setting( settings, ('admin_interface', 'map_zoom'), formalchemy_default_zoom) formalchemy_default_x = get_setting( settings, ('admin_interface', 'map_x'), formalchemy_default_x) formalchemy_default_y = get_setting( settings, ('admin_interface', 'map_y'), formalchemy_default_y) formalchemy_available_functionalities = get_setting( settings, ('admin_interface', 'available_functionalities'), formalchemy_available_functionalities) # scan view decorator for adding routes config.scan(ignore='c2cgeoportal.tests') config.registry.registerUtility( MultiDomainStaticURLInfo(), IStaticURLInfo) # add the static view (for static resources) config.add_static_view( 'static', 'c2cgeoportal:static', cache_max_age=int(settings["default_max_age"]) )
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ settings['mako.directories'] = 'OSMTM:templates' engine = engine_from_config(settings, 'sqlalchemy.') admin_user = settings['admin_user'] initialize_sql(engine, admin_user) authn_policy = AuthTktAuthenticationPolicy(secret='super_secret', callback=group_membership) authz_policy = ACLAuthorizationPolicy() config = Configurator(settings=settings, root_factory='OSMTM.models.RootFactory', authentication_policy=authn_policy, authorization_policy=authz_policy) session_factory = session_factory_from_settings(settings) config.set_session_factory(session_factory) config.add_static_view('static', 'OSMTM:static', cache_max_age=3600) config.include('pyramid_fanstatic') config.add_view('OSMTM.views.crossdomain.crossdomain_view', name='crossdomain.xml') config.add_route('crossdomain', '/crossdomain.xml', view='OSMTM.views.crossdomain.crossdomain_view') config.add_route('home', '/') config.add_route('about', '/about') config.add_route('tour', '/tour') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('job_new', '/job/new') config.add_route('job_geom', '/job/{job}.json') config.add_route('job_tiles', '/job/{job}/tiles') config.add_route('job_tiles_status', '/job/{job}/tiles_status') config.add_route('job', '/job/{job}', factory='OSMTM.resources.JobFactory') config.add_route('job_edit', '/job/{job}/edit', factory='OSMTM.resources.JobFactory') config.add_route('job_feature', '/job/{job}/feature', factory='OSMTM.resources.JobFactory') config.add_route('job_archive', '/job/{job}/archive', factory='OSMTM.resources.JobFactory') config.add_route('job_publish', '/job/{job}/publish', factory='OSMTM.resources.JobFactory') config.add_route('job_delete', '/job/{job}/delete', factory='OSMTM.resources.JobFactory') config.add_route('job_users', '/job/{job}/users', factory='OSMTM.resources.JobFactory') config.add_route('job_tags', '/job/{job}/tags', factory='OSMTM.resources.JobFactory') config.add_route('job_export', '/job/{job}/export', factory='OSMTM.resources.JobFactory') config.add_route('job_preset', '/job/{job}/preset', factory='OSMTM.resources.JobFactory') config.add_route('task_take_random', '/job/{job}/task/take/{checkin}', factory='OSMTM.resources.JobFactory') config.add_route('task', '/job/{job}/task/{x}/{y}/{zoom}', factory='OSMTM.resources.JobFactory') config.add_route('task_unlock', '/job/{job}/task/{x}/{y}/{zoom}/unlock', factory='OSMTM.resources.JobFactory') config.add_route('task_done', '/job/{job}/task/{x}/{y}/{zoom}/done', factory='OSMTM.resources.JobFactory') config.add_route('task_take', '/job/{job}/task/{x}/{y}/{zoom}/take', factory='OSMTM.resources.JobFactory') config.add_route('task_export', '/job/{job}/task/{x}/{y}/{zoom}/export.osm', factory='OSMTM.resources.JobFactory') config.add_route('task_split', '/job/{job}/task/{x}/{y}/{zoom}/split', factory='OSMTM.resources.JobFactory') config.add_route('nextview', '/profile/nextview') config.add_route('user_add', '/user/add') config.add_route('user', '/user/{id}') config.add_route('user_update', '/user/{id}/update') config.add_route('users', '/users') config.add_route('osmproxy', '/osmproxy') config.add_route('oauth_callback', '/oauth_callback') config.add_view('OSMTM.views.security.login', renderer='forbidden.mako', context='pyramid.exceptions.Forbidden') config.add_renderer('geojson', GeoJSON()) config.scan() return config.make_wsgi_app()