X-Git-Url: https://git.openstreetmap.org./nominatim.git/blobdiff_plain/d22ca186e4d388c228e90e1e701452c041a34687..3acd7df5c44345ad85aa97a92d582c60a4eba240:/src/nominatim_api/v1/server_glue.py?ds=sidebyside diff --git a/src/nominatim_api/v1/server_glue.py b/src/nominatim_api/v1/server_glue.py index 0e954901..a6450bf2 100644 --- a/src/nominatim_api/v1/server_glue.py +++ b/src/nominatim_api/v1/server_glue.py @@ -8,175 +8,25 @@ Generic part of the server implementation of the v1 API. Combine with the scaffolding provided for the various Python ASGI frameworks. """ -from typing import Optional, Any, Type, Callable, NoReturn, Dict, cast +from typing import Optional, Any, Type, Dict, cast, Sequence, Tuple from functools import reduce -import abc import dataclasses -import math from urllib.parse import urlencode import sqlalchemy as sa from ..errors import UsageError -from ..config import Configuration from .. import logging as loglib from ..core import NominatimAPIAsync -from .format import dispatch as formatting from .format import RawDataList from ..types import DataLayer, GeometryFormat, PlaceRef, PlaceID, OsmID, Point from ..status import StatusResult from ..results import DetailedResult, ReverseResults, SearchResult, SearchResults from ..localization import Locales from . import helpers - -CONTENT_TEXT = 'text/plain; charset=utf-8' -CONTENT_XML = 'text/xml; charset=utf-8' -CONTENT_HTML = 'text/html; charset=utf-8' -CONTENT_JSON = 'application/json; charset=utf-8' - -CONTENT_TYPE = {'text': CONTENT_TEXT, 'xml': CONTENT_XML, 'debug': CONTENT_HTML} - -class ASGIAdaptor(abc.ABC): - """ Adapter class for the different ASGI frameworks. - Wraps functionality over concrete requests and responses. - """ - content_type: str = CONTENT_TEXT - - @abc.abstractmethod - def get(self, name: str, default: Optional[str] = None) -> Optional[str]: - """ Return an input parameter as a string. If the parameter was - not provided, return the 'default' value. - """ - - @abc.abstractmethod - def get_header(self, name: str, default: Optional[str] = None) -> Optional[str]: - """ Return a HTTP header parameter as a string. If the parameter was - not provided, return the 'default' value. - """ - - - @abc.abstractmethod - def error(self, msg: str, status: int = 400) -> Exception: - """ Construct an appropriate exception from the given error message. - The exception must result in a HTTP error with the given status. - """ - - - @abc.abstractmethod - def create_response(self, status: int, output: str, num_results: int) -> Any: - """ Create a response from the given parameters. The result will - be returned by the endpoint functions. The adaptor may also - return None when the response is created internally with some - different means. - - The response must return the HTTP given status code 'status', set - the HTTP content-type headers to the string provided and the - body of the response to 'output'. - """ - - @abc.abstractmethod - def base_uri(self) -> str: - """ Return the URI of the original request. - """ - - - @abc.abstractmethod - def config(self) -> Configuration: - """ Return the current configuration object. - """ - - - def get_int(self, name: str, default: Optional[int] = None) -> int: - """ Return an input parameter as an int. Raises an exception if - the parameter is given but not in an integer format. - - If 'default' is given, then it will be returned when the parameter - is missing completely. When 'default' is None, an error will be - raised on a missing parameter. - """ - value = self.get(name) - - if value is None: - if default is not None: - return default - - self.raise_error(f"Parameter '{name}' missing.") - - try: - intval = int(value) - except ValueError: - self.raise_error(f"Parameter '{name}' must be a number.") - - return intval - - - def get_float(self, name: str, default: Optional[float] = None) -> float: - """ Return an input parameter as a flaoting-point number. Raises an - exception if the parameter is given but not in an float format. - - If 'default' is given, then it will be returned when the parameter - is missing completely. When 'default' is None, an error will be - raised on a missing parameter. - """ - value = self.get(name) - - if value is None: - if default is not None: - return default - - self.raise_error(f"Parameter '{name}' missing.") - - try: - fval = float(value) - except ValueError: - self.raise_error(f"Parameter '{name}' must be a number.") - - if math.isnan(fval) or math.isinf(fval): - self.raise_error(f"Parameter '{name}' must be a number.") - - return fval - - - def get_bool(self, name: str, default: Optional[bool] = None) -> bool: - """ Return an input parameter as bool. Only '0' is accepted as - an input for 'false' all other inputs will be interpreted as 'true'. - - If 'default' is given, then it will be returned when the parameter - is missing completely. When 'default' is None, an error will be - raised on a missing parameter. - """ - value = self.get(name) - - if value is None: - if default is not None: - return default - - self.raise_error(f"Parameter '{name}' missing.") - - return value != '0' - - - def raise_error(self, msg: str, status: int = 400) -> NoReturn: - """ Raise an exception resulting in the given HTTP status and - message. The message will be formatted according to the - output format chosen by the request. - """ - if self.content_type == CONTENT_XML: - msg = f""" - - {status} - {msg} - - """ - elif self.content_type == CONTENT_JSON: - msg = f"""{{"error":{{"code":{status},"message":"{msg}"}}}}""" - elif self.content_type == CONTENT_HTML: - loglib.log().section('Execution error') - loglib.log().var_dump('Status', status) - loglib.log().var_dump('Message', msg) - msg = loglib.get_and_disable() - - raise self.error(msg, status) +from ..server import content_types as ct +from ..server.asgi_adaptor import ASGIAdaptor, EndpointFunc +from ..sql.async_core_library import PGCORE_ERROR def build_response(adaptor: ASGIAdaptor, output: str, status: int = 200, @@ -184,7 +34,7 @@ def build_response(adaptor: ASGIAdaptor, output: str, status: int = 200, """ Create a response from the given output. Wraps a JSONP function around the response, if necessary. """ - if adaptor.content_type == CONTENT_JSON and status == 200: + if adaptor.content_type == ct.CONTENT_JSON and status == 200: jsonp = adaptor.get('json_callback') if jsonp is not None: if any(not part.isidentifier() for part in jsonp.split('.')): @@ -199,8 +49,8 @@ def get_accepted_languages(adaptor: ASGIAdaptor) -> str: """ Return the accepted languages. """ return adaptor.get('accept-language')\ - or adaptor.get_header('accept-language')\ - or adaptor.config().DEFAULT_LANGUAGE + or adaptor.get_header('accept-language')\ + or adaptor.config().DEFAULT_LANGUAGE def setup_debugging(adaptor: ASGIAdaptor) -> bool: @@ -210,7 +60,7 @@ def setup_debugging(adaptor: ASGIAdaptor) -> bool: """ if adaptor.get_bool('debug', False): loglib.set_log_output('html') - adaptor.content_type = CONTENT_HTML + adaptor.content_type = ct.CONTENT_HTML return True return False @@ -236,11 +86,13 @@ def parse_format(adaptor: ASGIAdaptor, result_type: Type[Any], default: str) -> fmt = adaptor.get('format', default=default) assert fmt is not None + formatting = adaptor.formatting() + if not formatting.supports_format(result_type, fmt): adaptor.raise_error("Parameter 'format' must be one of: " + - ', '.join(formatting.list_formats(result_type))) + ', '.join(formatting.list_formats(result_type))) - adaptor.content_type = CONTENT_TYPE.get(fmt, CONTENT_JSON) + adaptor.content_type = formatting.get_content_type(fmt) return fmt @@ -269,7 +121,7 @@ def parse_geometry_details(adaptor: ASGIAdaptor, fmt: str) -> Dict[str, Any]: return {'address_details': True, 'geometry_simplification': adaptor.get_float('polygon_threshold', 0.0), 'geometry_output': output - } + } async def status_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: @@ -284,8 +136,8 @@ async def status_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: else: status_code = 200 - return build_response(params, formatting.format_result(result, fmt, {}), - status=status_code) + return build_response(params, params.formatting().format_result(result, fmt, {}), + status=status_code) async def details_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: @@ -311,11 +163,11 @@ async def details_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: linked_places=params.get_bool('linkedplaces', True), parented_places=params.get_bool('hierarchy', False), keywords=params.get_bool('keywords', False), - geometry_output = GeometryFormat.GEOJSON - if params.get_bool('polygon_geojson', False) - else GeometryFormat.NONE, + geometry_output=(GeometryFormat.GEOJSON + if params.get_bool('polygon_geojson', False) + else GeometryFormat.NONE), locales=locales - ) + ) if debug: return build_response(params, loglib.get_and_disable()) @@ -323,10 +175,11 @@ async def details_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: if result is None: params.raise_error('No place with that OSM ID found.', status=404) - output = formatting.format_result(result, fmt, - {'locales': locales, - 'group_hierarchy': params.get_bool('group_hierarchy', False), - 'icon_base_url': params.config().MAPICON_URL}) + output = params.formatting().format_result( + result, fmt, + {'locales': locales, + 'group_hierarchy': params.get_bool('group_hierarchy', False), + 'icon_base_url': params.config().MAPICON_URL}) return build_response(params, output, num_results=1) @@ -362,8 +215,8 @@ async def reverse_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: 'namedetails': params.get_bool('namedetails', False), 'addressdetails': params.get_bool('addressdetails', True)} - output = formatting.format_result(ReverseResults([result] if result else []), - fmt, fmt_options) + output = params.formatting().format_result(ReverseResults([result] if result else []), + fmt, fmt_options) return build_response(params, output, num_results=1 if result else 0) @@ -397,13 +250,13 @@ async def lookup_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: 'namedetails': params.get_bool('namedetails', False), 'addressdetails': params.get_bool('addressdetails', True)} - output = formatting.format_result(results, fmt, fmt_options) + output = params.formatting().format_result(results, fmt, fmt_options) return build_response(params, output, num_results=len(results)) async def _unstructured_search(query: str, api: NominatimAPIAsync, - details: Dict[str, Any]) -> SearchResults: + details: Dict[str, Any]) -> SearchResults: if not query: return SearchResults() @@ -440,15 +293,15 @@ async def search_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: debug = setup_debugging(params) details = parse_geometry_details(params, fmt) - details['countries'] = params.get('countrycodes', None) + details['countries'] = params.get('countrycodes', None) details['excluded'] = params.get('exclude_place_ids', None) details['viewbox'] = params.get('viewbox', None) or params.get('viewboxlbrt', None) details['bounded_viewbox'] = params.get_bool('bounded', False) details['dedupe'] = params.get_bool('dedupe', True) max_results = max(1, min(50, params.get_int('limit', 10))) - details['max_results'] = max_results + min(10, max_results) \ - if details['dedupe'] else max_results + details['max_results'] = (max_results + min(10, max_results) + if details['dedupe'] else max_results) details['min_rank'], details['max_rank'] = \ helpers.feature_type_to_rank(params.get('featureType', '')) @@ -508,7 +361,7 @@ async def search_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: 'namedetails': params.get_bool('namedetails', False), 'addressdetails': params.get_bool('addressdetails', False)} - output = formatting.format_result(results, fmt, fmt_options) + output = params.formatting().format_result(results, fmt, fmt_options) return build_response(params, output, num_results=len(results)) @@ -530,7 +383,7 @@ async def deletable_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any """) results = RawDataList(r._asdict() for r in await conn.execute(sql)) - return build_response(params, formatting.format_result(results, fmt, {})) + return build_response(params, params.formatting().format_result(results, fmt, {})) async def polygons_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: @@ -562,17 +415,28 @@ async def polygons_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any: results = RawDataList(r._asdict() for r in await conn.execute(sql, sql_params)) - return build_response(params, formatting.format_result(results, fmt, {})) + return build_response(params, params.formatting().format_result(results, fmt, {})) + +async def get_routes(api: NominatimAPIAsync) -> Sequence[Tuple[str, EndpointFunc]]: + routes = [ + ('status', status_endpoint), + ('details', details_endpoint), + ('reverse', reverse_endpoint), + ('lookup', lookup_endpoint), + ('deletable', deletable_endpoint), + ('polygons', polygons_endpoint), + ] -EndpointFunc = Callable[[NominatimAPIAsync, ASGIAdaptor], Any] + def has_search_name(conn: sa.engine.Connection) -> bool: + insp = sa.inspect(conn) + return insp.has_table('search_name') + + try: + async with api.begin() as conn: + if await conn.connection.run_sync(has_search_name): + routes.append(('search', search_endpoint)) + except (PGCORE_ERROR, sa.exc.OperationalError): + pass # ignored -ROUTES = [ - ('status', status_endpoint), - ('details', details_endpoint), - ('reverse', reverse_endpoint), - ('lookup', lookup_endpoint), - ('search', search_endpoint), - ('deletable', deletable_endpoint), - ('polygons', polygons_endpoint), -] + return routes