]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/config.py
d4ba0d7a1eb59c3a2aaa6cbfb90c22ae641876db
[nominatim.git] / nominatim / config.py
1 """
2 Nominatim configuration accessor.
3 """
4 import os
5
6 from dotenv import dotenv_values
7
8 class Configuration:
9     """ Load and manage the project configuration.
10
11         Nominatim uses dotenv to configure the software. Configuration options
12         are resolved in the following order:
13
14          * from the OS environment
15          * from the .env file in the project directory of the installation
16          * from the default installation in the configuration directory
17
18         All Nominatim configuration options are prefixed with 'NOMINATIM_' to
19         avoid conflicts with other environment variables.
20     """
21
22     def __init__(self, project_dir, config_dir):
23         self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
24         if project_dir is not None:
25             self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
26
27         # Add defaults for variables that are left empty to set the default.
28         # They may still be overwritten by environment variables.
29         if not self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG']:
30             self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG'] = \
31                 str(config_dir / 'address-levels.json')
32
33
34     def __getattr__(self, name):
35         name = 'NOMINATIM_' + name
36
37         return os.environ.get(name) or self._config[name]
38
39     def get_libpq_dsn(self):
40         """ Get configured database DSN converted into the key/value format
41             understood by libpq and psycopg.
42         """
43         dsn = self.DATABASE_DSN
44
45         if dsn.startswith('pgsql:'):
46             # Old PHP DSN format. Convert before returning.
47             return dsn[6:].replace(';', ' ')
48
49         return dsn
50
51     def get_os_env(self):
52         """ Return a copy of the OS environment with the Nominatim configuration
53             merged in.
54         """
55         env = dict(self._config)
56         env.update(os.environ)
57
58         return env