1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Server implementation using the sanic webserver framework.
10 from pathlib import Path
14 from nominatim.api import NominatimAPIAsync
15 from nominatim.apicmd.status import StatusResult
16 import nominatim.result_formatter.v1 as formatting
18 api = sanic.Blueprint('NominatimAPI')
21 'text': 'text/plain; charset=utf-8',
22 'xml': 'text/xml; charset=utf-8'
26 return sanic.response.text(msg, status=400)
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'))
36 async def extract_format(request):
37 request.ctx.formatter = request.app.ctx.formatters[request.route.ctx.result_type]
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()))
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())
50 def get_application(project_dir: Path) -> sanic.Sanic:
51 app = sanic.Sanic("NominatimInstance")
53 app.ctx.api = NominatimAPIAsync(project_dir)
54 app.ctx.formatters = {}
55 for rtype in (StatusResult, ):
56 app.ctx.formatters[rtype] = formatting.create(rtype)