2 Nominatim configuration accessor.
6 from pathlib import Path
8 from dotenv import dotenv_values
10 from .errors import UsageError
12 LOG = logging.getLogger()
15 """ Load and manage the project configuration.
17 Nominatim uses dotenv to configure the software. Configuration options
18 are resolved in the following order:
20 * from the OS environment
21 * from the .env file in the project directory of the installation
22 * from the default installation in the configuration directory
24 All Nominatim configuration options are prefixed with 'NOMINATIM_' to
25 avoid conflicts with other environment variables.
28 def __init__(self, project_dir, config_dir):
29 self.project_dir = project_dir
30 self.config_dir = config_dir
31 self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
32 if project_dir is not None:
33 self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
35 # Add defaults for variables that are left empty to set the default.
36 # They may still be overwritten by environment variables.
37 if not self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG']:
38 self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG'] = \
39 str(config_dir / 'address-levels.json')
42 def __getattr__(self, name):
43 name = 'NOMINATIM_' + name
45 return os.environ.get(name) or self._config[name]
47 def get_bool(self, name):
48 """ Return the given configuration parameter as a boolean.
49 Values of '1', 'yes' and 'true' are accepted as truthy values,
50 everything else is interpreted as false.
52 return self.__getattr__(name).lower() in ('1', 'yes', 'true')
55 def get_int(self, name):
56 """ Return the given configuration parameter as an int.
59 return int(self.__getattr__(name))
61 LOG.fatal("Invalid setting NOMINATIM_%s. Needs to be a number.", name)
62 raise UsageError("Configuration error.")
65 def get_libpq_dsn(self):
66 """ Get configured database DSN converted into the key/value format
67 understood by libpq and psycopg.
69 dsn = self.DATABASE_DSN
71 def quote_param(param):
72 key, val = param.split('=')
73 val = val.replace('\\', '\\\\').replace("'", "\\'")
76 return key + '=' + val
78 if dsn.startswith('pgsql:'):
79 # Old PHP DSN format. Convert before returning.
80 return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
85 def get_import_style_file(self):
86 """ Return the import style file as a path object. Translates the
87 name of the standard styles automatically into a file in the
90 style = self.__getattr__('IMPORT_STYLE')
92 if style in ('admin', 'street', 'address', 'full', 'extratags'):
93 return self.config_dir / 'import-{}.style'.format(style)
99 """ Return a copy of the OS environment with the Nominatim configuration
102 env = dict(self._config)
103 env.update(os.environ)