]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/server/sanic/server.py
cf1ef4ce2859ab352bec841fe591c8a2969d5af1
[nominatim.git] / nominatim / server / sanic / server.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Server implementation using the sanic webserver framework.
9 """
10 from typing import Any, Optional, Mapping, Callable, cast, Coroutine
11 from pathlib import Path
12
13 from sanic import Request, HTTPResponse, Sanic
14 from sanic.exceptions import SanicException
15 from sanic.response import text as TextResponse
16
17 from nominatim.api import NominatimAPIAsync
18 import nominatim.api.v1 as api_impl
19 from nominatim.config import Configuration
20
21 class ParamWrapper(api_impl.ASGIAdaptor):
22     """ Adaptor class for server glue to Sanic framework.
23     """
24
25     def __init__(self, request: Request) -> None:
26         self.request = request
27
28
29     def get(self, name: str, default: Optional[str] = None) -> Optional[str]:
30         return cast(Optional[str], self.request.args.get(name, default))
31
32
33     def get_header(self, name: str, default: Optional[str] = None) -> Optional[str]:
34         return cast(Optional[str], self.request.headers.get(name, default))
35
36
37     def error(self, msg: str, status: int = 400) -> SanicException:
38         exception = SanicException(msg, status_code=status)
39         exception.headers = {'content-type': self.content_type}
40
41         return exception
42
43
44     def create_response(self, status: int, output: str) -> HTTPResponse:
45         return TextResponse(output, status=status, content_type=self.content_type)
46
47
48     def config(self) -> Configuration:
49         return cast(Configuration, self.request.app.ctx.api.config)
50
51
52 def _wrap_endpoint(func: api_impl.EndpointFunc)\
53        -> Callable[[Request], Coroutine[Any, Any, HTTPResponse]]:
54     async def _callback(request: Request) -> HTTPResponse:
55         return cast(HTTPResponse, await func(request.app.ctx.api, ParamWrapper(request)))
56
57     return _callback
58
59
60 def get_application(project_dir: Path,
61                     environ: Optional[Mapping[str, str]] = None) -> Sanic:
62     """ Create a Nominatim sanic ASGI application.
63     """
64     app = Sanic("NominatimInstance")
65
66     app.ctx.api = NominatimAPIAsync(project_dir, environ)
67
68     if app.ctx.api.config.get_bool('CORS_NOACCESSCONTROL'):
69         from sanic_cors import CORS # pylint: disable=import-outside-toplevel
70         CORS(app)
71
72     legacy_urls = app.ctx.api.config.get_bool('SERVE_LEGACY_URLS')
73     for name, func in api_impl.ROUTES:
74         endpoint = _wrap_endpoint(func)
75         app.add_route(endpoint, f"/{name}", name=f"v1_{name}_simple")
76         if legacy_urls:
77             app.add_route(endpoint, f"/{name}.php", name=f"v1_{name}_legacy")
78
79     return app