Coverage for yaptide/application.py: 87%

38 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-07-01 12:55 +0000

1import os 

2 

3from flask import Flask 

4from flask_restful import Api 

5from flask_swagger_ui import get_swaggerui_blueprint 

6from yaptide.persistence.models import create_all 

7from yaptide.persistence.database import db 

8from yaptide.admin import git_submodules 

9 

10 

11def create_app(): 

12 """Function starting Flask Server""" 

13 git_submodules.check_submodules() 

14 

15 # Main_routes module is importing (in-directly) the converter module which is cloned as submodule. 

16 # Lack of this submodule would result in the ModuleNotFoundError. 

17 from yaptide.routes.main_routes import initialize_routes 

18 

19 flask_name = __name__.split('.')[0] 

20 app = Flask(flask_name) 

21 app.logger.info("Creating Flask app %s", flask_name) 

22 

23 # Print env variables 

24 for item in os.environ.items(): 

25 app.logger.debug("Environment variable: %s", item) 

26 

27 # Load configuration from environment variables 

28 # Load any environment variables that start with FLASK_, dropping the prefix from the env key for the config key. 

29 # Values are passed through a loading function to attempt to convert them to more specific types than strings. 

30 app.config.from_prefixed_env() 

31 for item in app.config.items(): 

32 app.logger.debug("Flask config variable: %s", item) 

33 

34 if app.config.get('USE_CORS'): 

35 app.logger.info("enabling cors") 

36 from flask_cors import CORS 

37 cors_config = { 

38 "origins": ["http://127.0.0.1:3000", "http://localhost:3000"], 

39 "supports_credentials": True, 

40 "resources": { 

41 r"/*": { 

42 "origins": ["http://127.0.0.1:3000", "http://localhost:3000"] 

43 } 

44 }, 

45 "allow_headers": ["Content-Type", "Authorization"], 

46 "expose_headers": ["Access-Control-Allow-Origin"], 

47 "send_wildcard": False, 

48 "always_send": True, 

49 } 

50 

51 CORS(app, **cors_config) 

52 

53 SWAGGER_URL = '/api/docs' 

54 API_URL = '/static/openapi.yaml' 

55 

56 swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL, config={'app_name': "yaptide"}) 

57 

58 app.register_blueprint(swaggerui_blueprint) 

59 

60 app.logger.info(f"Initializing Flask to use SQLAlchemy ORM @ {app.config['SQLALCHEMY_DATABASE_URI']}") 

61 db.init_app(app) 

62 

63 # Find a better solution (maybe with Flask-Migrate) to handle migration of data from past versions 

64 with app.app_context(): 

65 app.logger.debug("Creating models") 

66 create_all() 

67 app.logger.debug(f"Created {len(db.metadata.tables)} tables") 

68 

69 api = Api(app) 

70 initialize_routes(api) 

71 

72 return app 

73 

74 

75if __name__ == "__main__": 

76 create_app()