Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/flask/config.py: 27%

108 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-09 07:17 +0000

1from __future__ import annotations 

2 

3import errno 

4import json 

5import os 

6import types 

7import typing as t 

8 

9from werkzeug.utils import import_string 

10 

11 

12class ConfigAttribute: 

13 """Makes an attribute forward to the config""" 

14 

15 def __init__(self, name: str, get_converter: t.Callable | None = None) -> None: 

16 self.__name__ = name 

17 self.get_converter = get_converter 

18 

19 def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any: 

20 if obj is None: 

21 return self 

22 rv = obj.config[self.__name__] 

23 if self.get_converter is not None: 

24 rv = self.get_converter(rv) 

25 return rv 

26 

27 def __set__(self, obj: t.Any, value: t.Any) -> None: 

28 obj.config[self.__name__] = value 

29 

30 

31class Config(dict): 

32 """Works exactly like a dict but provides ways to fill it from files 

33 or special dictionaries. There are two common patterns to populate the 

34 config. 

35 

36 Either you can fill the config from a config file:: 

37 

38 app.config.from_pyfile('yourconfig.cfg') 

39 

40 Or alternatively you can define the configuration options in the 

41 module that calls :meth:`from_object` or provide an import path to 

42 a module that should be loaded. It is also possible to tell it to 

43 use the same module and with that provide the configuration values 

44 just before the call:: 

45 

46 DEBUG = True 

47 SECRET_KEY = 'development key' 

48 app.config.from_object(__name__) 

49 

50 In both cases (loading from any Python file or loading from modules), 

51 only uppercase keys are added to the config. This makes it possible to use 

52 lowercase values in the config file for temporary values that are not added 

53 to the config or to define the config keys in the same file that implements 

54 the application. 

55 

56 Probably the most interesting way to load configurations is from an 

57 environment variable pointing to a file:: 

58 

59 app.config.from_envvar('YOURAPPLICATION_SETTINGS') 

60 

61 In this case before launching the application you have to set this 

62 environment variable to the file you want to use. On Linux and OS X 

63 use the export statement:: 

64 

65 export YOURAPPLICATION_SETTINGS='/path/to/config/file' 

66 

67 On windows use `set` instead. 

68 

69 :param root_path: path to which files are read relative from. When the 

70 config object is created by the application, this is 

71 the application's :attr:`~flask.Flask.root_path`. 

72 :param defaults: an optional dictionary of default values 

73 """ 

74 

75 def __init__( 

76 self, root_path: str | os.PathLike, defaults: dict | None = None 

77 ) -> None: 

78 super().__init__(defaults or {}) 

79 self.root_path = root_path 

80 

81 def from_envvar(self, variable_name: str, silent: bool = False) -> bool: 

82 """Loads a configuration from an environment variable pointing to 

83 a configuration file. This is basically just a shortcut with nicer 

84 error messages for this line of code:: 

85 

86 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) 

87 

88 :param variable_name: name of the environment variable 

89 :param silent: set to ``True`` if you want silent failure for missing 

90 files. 

91 :return: ``True`` if the file was loaded successfully. 

92 """ 

93 rv = os.environ.get(variable_name) 

94 if not rv: 

95 if silent: 

96 return False 

97 raise RuntimeError( 

98 f"The environment variable {variable_name!r} is not set" 

99 " and as such configuration could not be loaded. Set" 

100 " this variable and make it point to a configuration" 

101 " file" 

102 ) 

103 return self.from_pyfile(rv, silent=silent) 

104 

105 def from_prefixed_env( 

106 self, prefix: str = "FLASK", *, loads: t.Callable[[str], t.Any] = json.loads 

107 ) -> bool: 

108 """Load any environment variables that start with ``FLASK_``, 

109 dropping the prefix from the env key for the config key. Values 

110 are passed through a loading function to attempt to convert them 

111 to more specific types than strings. 

112 

113 Keys are loaded in :func:`sorted` order. 

114 

115 The default loading function attempts to parse values as any 

116 valid JSON type, including dicts and lists. 

117 

118 Specific items in nested dicts can be set by separating the 

119 keys with double underscores (``__``). If an intermediate key 

120 doesn't exist, it will be initialized to an empty dict. 

121 

122 :param prefix: Load env vars that start with this prefix, 

123 separated with an underscore (``_``). 

124 :param loads: Pass each string value to this function and use 

125 the returned value as the config value. If any error is 

126 raised it is ignored and the value remains a string. The 

127 default is :func:`json.loads`. 

128 

129 .. versionadded:: 2.1 

130 """ 

131 prefix = f"{prefix}_" 

132 len_prefix = len(prefix) 

133 

134 for key in sorted(os.environ): 

135 if not key.startswith(prefix): 

136 continue 

137 

138 value = os.environ[key] 

139 

140 try: 

141 value = loads(value) 

142 except Exception: 

143 # Keep the value as a string if loading failed. 

144 pass 

145 

146 # Change to key.removeprefix(prefix) on Python >= 3.9. 

147 key = key[len_prefix:] 

148 

149 if "__" not in key: 

150 # A non-nested key, set directly. 

151 self[key] = value 

152 continue 

153 

154 # Traverse nested dictionaries with keys separated by "__". 

155 current = self 

156 *parts, tail = key.split("__") 

157 

158 for part in parts: 

159 # If an intermediate dict does not exist, create it. 

160 if part not in current: 

161 current[part] = {} 

162 

163 current = current[part] 

164 

165 current[tail] = value 

166 

167 return True 

168 

169 def from_pyfile(self, filename: str | os.PathLike, silent: bool = False) -> bool: 

170 """Updates the values in the config from a Python file. This function 

171 behaves as if the file was imported as module with the 

172 :meth:`from_object` function. 

173 

174 :param filename: the filename of the config. This can either be an 

175 absolute filename or a filename relative to the 

176 root path. 

177 :param silent: set to ``True`` if you want silent failure for missing 

178 files. 

179 :return: ``True`` if the file was loaded successfully. 

180 

181 .. versionadded:: 0.7 

182 `silent` parameter. 

183 """ 

184 filename = os.path.join(self.root_path, filename) 

185 d = types.ModuleType("config") 

186 d.__file__ = filename 

187 try: 

188 with open(filename, mode="rb") as config_file: 

189 exec(compile(config_file.read(), filename, "exec"), d.__dict__) 

190 except OSError as e: 

191 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): 

192 return False 

193 e.strerror = f"Unable to load configuration file ({e.strerror})" 

194 raise 

195 self.from_object(d) 

196 return True 

197 

198 def from_object(self, obj: object | str) -> None: 

199 """Updates the values from the given object. An object can be of one 

200 of the following two types: 

201 

202 - a string: in this case the object with that name will be imported 

203 - an actual object reference: that object is used directly 

204 

205 Objects are usually either modules or classes. :meth:`from_object` 

206 loads only the uppercase attributes of the module/class. A ``dict`` 

207 object will not work with :meth:`from_object` because the keys of a 

208 ``dict`` are not attributes of the ``dict`` class. 

209 

210 Example of module-based configuration:: 

211 

212 app.config.from_object('yourapplication.default_config') 

213 from yourapplication import default_config 

214 app.config.from_object(default_config) 

215 

216 Nothing is done to the object before loading. If the object is a 

217 class and has ``@property`` attributes, it needs to be 

218 instantiated before being passed to this method. 

219 

220 You should not use this function to load the actual configuration but 

221 rather configuration defaults. The actual config should be loaded 

222 with :meth:`from_pyfile` and ideally from a location not within the 

223 package because the package might be installed system wide. 

224 

225 See :ref:`config-dev-prod` for an example of class-based configuration 

226 using :meth:`from_object`. 

227 

228 :param obj: an import name or object 

229 """ 

230 if isinstance(obj, str): 

231 obj = import_string(obj) 

232 for key in dir(obj): 

233 if key.isupper(): 

234 self[key] = getattr(obj, key) 

235 

236 def from_file( 

237 self, 

238 filename: str | os.PathLike, 

239 load: t.Callable[[t.IO[t.Any]], t.Mapping], 

240 silent: bool = False, 

241 text: bool = True, 

242 ) -> bool: 

243 """Update the values in the config from a file that is loaded 

244 using the ``load`` parameter. The loaded data is passed to the 

245 :meth:`from_mapping` method. 

246 

247 .. code-block:: python 

248 

249 import json 

250 app.config.from_file("config.json", load=json.load) 

251 

252 import tomllib 

253 app.config.from_file("config.toml", load=tomllib.load, text=False) 

254 

255 :param filename: The path to the data file. This can be an 

256 absolute path or relative to the config root path. 

257 :param load: A callable that takes a file handle and returns a 

258 mapping of loaded data from the file. 

259 :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` 

260 implements a ``read`` method. 

261 :param silent: Ignore the file if it doesn't exist. 

262 :param text: Open the file in text or binary mode. 

263 :return: ``True`` if the file was loaded successfully. 

264 

265 .. versionchanged:: 2.3 

266 The ``text`` parameter was added. 

267 

268 .. versionadded:: 2.0 

269 """ 

270 filename = os.path.join(self.root_path, filename) 

271 

272 try: 

273 with open(filename, "r" if text else "rb") as f: 

274 obj = load(f) 

275 except OSError as e: 

276 if silent and e.errno in (errno.ENOENT, errno.EISDIR): 

277 return False 

278 

279 e.strerror = f"Unable to load configuration file ({e.strerror})" 

280 raise 

281 

282 return self.from_mapping(obj) 

283 

284 def from_mapping( 

285 self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any 

286 ) -> bool: 

287 """Updates the config like :meth:`update` ignoring items with 

288 non-upper keys. 

289 

290 :return: Always returns ``True``. 

291 

292 .. versionadded:: 0.11 

293 """ 

294 mappings: dict[str, t.Any] = {} 

295 if mapping is not None: 

296 mappings.update(mapping) 

297 mappings.update(kwargs) 

298 for key, value in mappings.items(): 

299 if key.isupper(): 

300 self[key] = value 

301 return True 

302 

303 def get_namespace( 

304 self, namespace: str, lowercase: bool = True, trim_namespace: bool = True 

305 ) -> dict[str, t.Any]: 

306 """Returns a dictionary containing a subset of configuration options 

307 that match the specified namespace/prefix. Example usage:: 

308 

309 app.config['IMAGE_STORE_TYPE'] = 'fs' 

310 app.config['IMAGE_STORE_PATH'] = '/var/app/images' 

311 app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' 

312 image_store_config = app.config.get_namespace('IMAGE_STORE_') 

313 

314 The resulting dictionary `image_store_config` would look like:: 

315 

316 { 

317 'type': 'fs', 

318 'path': '/var/app/images', 

319 'base_url': 'http://img.website.com' 

320 } 

321 

322 This is often useful when configuration options map directly to 

323 keyword arguments in functions or class constructors. 

324 

325 :param namespace: a configuration namespace 

326 :param lowercase: a flag indicating if the keys of the resulting 

327 dictionary should be lowercase 

328 :param trim_namespace: a flag indicating if the keys of the resulting 

329 dictionary should not include the namespace 

330 

331 .. versionadded:: 0.11 

332 """ 

333 rv = {} 

334 for k, v in self.items(): 

335 if not k.startswith(namespace): 

336 continue 

337 if trim_namespace: 

338 key = k[len(namespace) :] 

339 else: 

340 key = k 

341 if lowercase: 

342 key = key.lower() 

343 rv[key] = v 

344 return rv 

345 

346 def __repr__(self) -> str: 

347 return f"<{type(self).__name__} {dict.__repr__(self)}>"