]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/config.py
a22f90ab247b7b63b11b15068845623afa3aa778
[nominatim.git] / nominatim / config.py
1 """
2 Nominatim configuration accessor.
3 """
4 import logging
5 import os
6 from pathlib import Path
7
8 from dotenv import dotenv_values
9
10 from .errors import UsageError
11
12 LOG = logging.getLogger()
13
14 class Configuration:
15     """ Load and manage the project configuration.
16
17         Nominatim uses dotenv to configure the software. Configuration options
18         are resolved in the following order:
19
20          * from the OS environment (or the dirctionary given in `environ`
21          * from the .env file in the project directory of the installation
22          * from the default installation in the configuration directory
23
24         All Nominatim configuration options are prefixed with 'NOMINATIM_' to
25         avoid conflicts with other environment variables.
26     """
27
28     def __init__(self, project_dir, config_dir, environ=None):
29         self.environ = environ or os.environ
30         self.project_dir = project_dir
31         self.config_dir = config_dir
32         self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
33         if project_dir is not None:
34             self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
35
36         # Add defaults for variables that are left empty to set the default.
37         # They may still be overwritten by environment variables.
38         if not self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG']:
39             self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG'] = \
40                 str(config_dir / 'address-levels.json')
41
42
43     def __getattr__(self, name):
44         name = 'NOMINATIM_' + name
45
46         return self.environ.get(name) or self._config[name]
47
48     def get_bool(self, name):
49         """ Return the given configuration parameter as a boolean.
50             Values of '1', 'yes' and 'true' are accepted as truthy values,
51             everything else is interpreted as false.
52         """
53         return self.__getattr__(name).lower() in ('1', 'yes', 'true')
54
55
56     def get_int(self, name):
57         """ Return the given configuration parameter as an int.
58         """
59         try:
60             return int(self.__getattr__(name))
61         except ValueError:
62             LOG.fatal("Invalid setting NOMINATIM_%s. Needs to be a number.", name)
63             raise UsageError("Configuration error.")
64
65
66     def get_libpq_dsn(self):
67         """ Get configured database DSN converted into the key/value format
68             understood by libpq and psycopg.
69         """
70         dsn = self.DATABASE_DSN
71
72         def quote_param(param):
73             key, val = param.split('=')
74             val = val.replace('\\', '\\\\').replace("'", "\\'")
75             if ' ' in val:
76                 val = "'" + val + "'"
77             return key + '=' + val
78
79         if dsn.startswith('pgsql:'):
80             # Old PHP DSN format. Convert before returning.
81             return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
82
83         return dsn
84
85
86     def get_import_style_file(self):
87         """ Return the import style file as a path object. Translates the
88             name of the standard styles automatically into a file in the
89             config style.
90         """
91         style = self.__getattr__('IMPORT_STYLE')
92
93         if style in ('admin', 'street', 'address', 'full', 'extratags'):
94             return self.config_dir / 'import-{}.style'.format(style)
95
96         return Path(style)
97
98
99     def get_os_env(self):
100         """ Return a copy of the OS environment with the Nominatim configuration
101             merged in.
102         """
103         env = dict(self._config)
104         env.update(self.environ)
105
106         return env