Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""LICENSE 

2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of stockstert. 

5 

6stockstert is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11stockstert is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with stockstert. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20import os 

21import json 

22from typing import Optional 

23from stockstert.flask import app 

24 

25 

26def resolve_env_variable( 

27 env_key: str, _type: type = str, default: object = None 

28) -> Optional[object]: 

29 """ 

30 Resolves an environment key. 

31 A non-existant environment key will lead to a KeyError unless the app 

32 is in testing mode, in which case database-related variables won't 

33 cause a KeyError. 

34 KeyErrors can also be provided using the 'default' argument 

35 :param env_key: The environment key to resolve 

36 :param _type: The type of the environment variable 

37 :param default: An optional default value 

38 :return: The resolved environment variable. 

39 None if the app is in testing mode and the variable is db-related 

40 """ 

41 using_sqlite = app.testing or app.config["ENV"] == "development" 

42 try: 

43 return _type(os.environ[env_key]) 

44 except KeyError as e: 

45 if default is not None: 

46 return default 

47 elif using_sqlite and env_key.startswith("DB_"): 

48 return None 

49 else: 

50 raise e 

51 

52 

53def load_secrets(secrets_file: str): 

54 """ 

55 Loads a JSON file filled with configuration details and secrets into 

56 os.environ 

57 :param secrets_file: The file to load 

58 :return: None 

59 """ 

60 if os.path.isfile(secrets_file): 60 ↛ 61line 60 didn't jump to line 61, because the condition on line 60 was never true

61 with open(secrets_file, "r") as f: 

62 secrets = json.load(f) 

63 

64 for secret, value in secrets.items(): 

65 os.environ[secret] = str(value)