]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/server/sanic/server.py
9c75327e19b12d4f6221e5854cc7efbfc4bcccf4
[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) 2022 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 pathlib import Path
11
12 import sanic
13
14 from nominatim.api import NominatimAPIAsync
15 from nominatim.apicmd.status import StatusResult
16 import nominatim.result_formatter.v1 as formatting
17
18 api = sanic.Blueprint('NominatimAPI')
19
20 CONTENT_TYPE = {
21   'text': 'text/plain; charset=utf-8',
22   'xml': 'text/xml; charset=utf-8'
23 }
24
25 def usage_error(msg):
26     return sanic.response.text(msg, status=400)
27
28
29 def api_response(request, result):
30     body = request.ctx.formatter.format(result, request.ctx.format)
31     return sanic.response.text(body,
32                                content_type=CONTENT_TYPE.get(request.ctx.format, 'application/json'))
33
34
35 @api.on_request
36 async def extract_format(request):
37     request.ctx.formatter = request.app.ctx.formatters[request.route.ctx.result_type]
38
39     request.ctx.format = request.args.get('format', request.route.ctx.default_format)
40     if not request.ctx.formatter.supports_format(request.ctx.format):
41         return usage_error("Parameter 'format' must be one of: " +
42                            ', '.join(request.ctx.formatter.list_formats()))
43
44
45 @api.get('/status', ctx_result_type=StatusResult, ctx_default_format='text')
46 async def status(request):
47     return api_response(request,await request.app.ctx.api.status())
48
49
50 def get_application(project_dir: Path) -> sanic.Sanic:
51     app = sanic.Sanic("NominatimInstance")
52
53     app.ctx.api = NominatimAPIAsync(project_dir)
54     app.ctx.formatters = {}
55     for rtype in (StatusResult, ):
56         app.ctx.formatters[rtype] = formatting.create(rtype)
57
58     app.blueprint(api)
59
60     return app
61
62