1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Server implementation using the falcon webserver framework.
10 from typing import Optional, Mapping, cast
11 from pathlib import Path
14 from falcon.asgi import App, Request, Response
16 from nominatim.api import NominatimAPIAsync
17 import nominatim.api.v1 as api_impl
18 from nominatim.config import Configuration
21 class ParamWrapper(api_impl.ASGIAdaptor):
22 """ Adaptor class for server glue to Falcon framework.
25 def __init__(self, req: Request, resp: Response,
26 config: Configuration) -> None:
32 def get(self, name: str, default: Optional[str] = None) -> Optional[str]:
33 return cast(Optional[str], self.request.get_param(name, default=default))
36 def get_header(self, name: str, default: Optional[str] = None) -> Optional[str]:
37 return cast(Optional[str], self.request.get_header(name, default=default))
40 def error(self, msg: str, status: int = 400) -> falcon.HTTPError:
42 return falcon.HTTPBadRequest(description=msg)
44 return falcon.HTTPNotFound(description=msg)
46 return falcon.HTTPError(status, description=msg)
49 def create_response(self, status: int, output: str, content_type: str) -> None:
50 self.response.status = status
51 self.response.text = output
52 self.response.content_type = content_type
55 def config(self) -> Configuration:
59 class EndpointWrapper:
60 """ Converter for server glue endpoint functions to Falcon request handlers.
63 def __init__(self, func: api_impl.EndpointFunc, api: NominatimAPIAsync) -> None:
68 async def on_get(self, req: Request, resp: Response) -> None:
69 """ Implementation of the endpoint.
71 await self.func(self.api, ParamWrapper(req, resp, self.api.config))
74 def get_application(project_dir: Path,
75 environ: Optional[Mapping[str, str]] = None) -> App:
76 """ Create a Nominatim Falcon ASGI application.
78 api = NominatimAPIAsync(project_dir, environ)
80 app = App(cors_enable=api.config.get_bool('CORS_NOACCESSCONTROL'))
82 legacy_urls = api.config.get_bool('SERVE_LEGACY_URLS')
83 for name, func in api_impl.ROUTES:
84 endpoint = EndpointWrapper(func, api)
85 app.add_route(f"/{name}", endpoint)
87 app.add_route(f"/{name}.php", endpoint)