Coverage for src/counter_os/infrastructure/flask_web/flask_web_app.py: 74%

39 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-29 10:32 -0600

1import sys 

2 

3from flask import Flask 

4from gunicorn.app.base import BaseApplication as gunicorn_base 

5 

6from counter_os.bootstrap.application_configuration import ApplicationConfiguration 

7from counter_os.bootstrap.application_container import ApplicationContainer 

8from counter_os.bootstrap.application_environment_type import ApplicationEnvironmentType 

9from counter_os.infrastructure.flask_web.flask_app_factory import create_flask_app 

10 

11 

12class FlaskWebApp: 

13 app_config: ApplicationConfiguration 

14 flask_app: Flask 

15 

16 def __init__( 

17 self, app_config: ApplicationConfiguration, app_container: ApplicationContainer 

18 ): 

19 self.app_config = app_config 

20 self.flask_app = create_flask_app(app_config, app_container) 

21 

22 def run(self) -> int: 

23 match self.app_config.app_env: 

24 case ApplicationEnvironmentType.DEVELOPMENT: 

25 self.flask_app.run( 

26 host="127.0.0.1", 

27 port=self.app_config.flask_port, 

28 debug=True, 

29 ) 

30 return 0 

31 case ApplicationEnvironmentType.PRODUCTION: 

32 gunicorn_run(self.app_config, self.flask_app) 

33 return 0 

34 case _: 

35 print( 

36 f'"{self.app_config.app_env}" is not a valid APP_ENV', 

37 file=sys.stderr, 

38 ) 

39 print( 

40 'Starting app with "development" application environment type', 

41 file=sys.stderr, 

42 ) 

43 self.flask_app.run( 

44 host="127.0.0.1", 

45 port=self.app_config.flask_port, 

46 debug=True, 

47 ) 

48 return 0 

49 

50 

51def gunicorn_run(app_config: ApplicationConfiguration, flask_app: Flask): 

52 options: dict[str, object] = { 

53 "bind": f"0.0.0.0:{app_config.flask_port}", 

54 "workers": 1, 

55 } 

56 StandaloneGunicornApplication(flask_app, options).run() 

57 

58 

59class StandaloneGunicornApplication(gunicorn_base): 

60 def __init__(self, app: Flask, options: dict[str, object]): 

61 self.application = app 

62 self.options = options 

63 super().__init__() 

64 

65 def load_config(self) -> None: 

66 assert self.cfg is not None 

67 for key, value in self.options.items(): 

68 if key in self.cfg.settings and value is not None: 

69 self.cfg.set(key.lower(), value) 

70 

71 def load(self) -> Flask: 

72 return self.application