]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/server/falcon/server.py
fix liniting issues and add type annotations
[nominatim.git] / nominatim / server / falcon / 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) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Server implementation using the falcon webserver framework.
9 """
10 from typing import Type, Any
11 from pathlib import Path
12
13 import falcon
14 import falcon.asgi
15
16 from nominatim.api import NominatimAPIAsync
17 from nominatim.apicmd.status import StatusResult
18 import nominatim.result_formatter.v1 as formatting
19
20 CONTENT_TYPE = {
21   'text': falcon.MEDIA_TEXT,
22   'xml': falcon.MEDIA_XML
23 }
24
25 class NominatimV1:
26     """ Implementation of V1 version of the Nominatim API.
27     """
28
29     def __init__(self, project_dir: Path) -> None:
30         self.api = NominatimAPIAsync(project_dir)
31         self.formatters = {}
32
33         for rtype in (StatusResult, ):
34             self.formatters[rtype] = formatting.create(rtype)
35
36
37     def parse_format(self, req: falcon.asgi.Request, rtype: Type[Any], default: str) -> None:
38         """ Get and check the 'format' parameter and prepare the formatter.
39             `rtype` describes the expected return type and `default` the
40             format value to assume when no parameter is present.
41         """
42         req.context.format = req.get_param('format', default=default)
43         req.context.formatter = self.formatters[rtype]
44
45         if not req.context.formatter.supports_format(req.context.format):
46             raise falcon.HTTPBadRequest(
47                 description="Parameter 'format' must be one of: " +
48                             ', '.join(req.context.formatter.list_formats()))
49
50
51     def format_response(self, req: falcon.asgi.Request, resp: falcon.asgi.Response,
52                         result: Any) -> None:
53         """ Render response into a string according to the formatter
54             set in `parse_format()`.
55         """
56         resp.text = req.context.formatter.format(result, req.context.format)
57         resp.content_type = CONTENT_TYPE.get(req.context.format, falcon.MEDIA_JSON)
58
59
60     async def on_get_status(self, req: falcon.asgi.Request, resp: falcon.asgi.Response) -> None:
61         """ Implementation of status endpoint.
62         """
63         self.parse_format(req, StatusResult, 'text')
64
65         result = await self.api.status()
66
67         self.format_response(req, resp, result)
68
69
70 def get_application(project_dir: Path) -> falcon.asgi.App:
71     """ Create a Nominatim falcon ASGI application.
72     """
73     app = falcon.asgi.App()
74
75     api = NominatimV1(project_dir)
76
77     app.add_route('/status', api, suffix='status')
78
79     return app