Coverage for app.py: 75%

40 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2024-11-05 04:22 +0000

1import os 

2import logging 

3from flask import Flask 

4from model import * 

5from mongo import * 

6 

7 

8def app(): 

9 # Create a flask app 

10 app = Flask(__name__) 

11 app.config['PREFERRED_URL_SCHEME'] = 'https' 

12 app.url_map.strict_slashes = False 

13 setup_smtp(app) 

14 # Register flask blueprint 

15 api2prefix = [ 

16 (auth_api, '/auth'), 

17 (profile_api, '/profile'), 

18 (problem_api, '/problem'), 

19 (submission_api, '/submission'), 

20 (course_api, '/course'), 

21 (homework_api, '/homework'), 

22 (test_api, '/test'), 

23 (ann_api, '/ann'), 

24 (ranking_api, '/ranking'), 

25 (post_api, '/post'), 

26 (copycat_api, '/copycat'), 

27 (health_api, '/health'), 

28 (user_api, '/user'), 

29 ] 

30 for api, prefix in api2prefix: 

31 app.register_blueprint(api, url_prefix=prefix) 

32 

33 if not User('first_admin'): 

34 ADMIN = { 

35 'username': 'first_admin', 

36 'password': 'firstpasswordforadmin', 

37 'email': 'i.am.first.admin@noj.tw' 

38 } 

39 PROFILE = { 

40 'displayed_name': 'the first admin', 

41 'bio': 'I am super good!!!!!' 

42 } 

43 admin = User.signup(**ADMIN) 

44 # TODO: use a single method to active. 

45 # we won't call `activate` here because it required the 

46 # course 'Public' should exist, but create a course 

47 # also need a teacher. 

48 # but at least make it can work now... 

49 # admin.activate(PROFILE) 

50 admin.update( 

51 active=True, 

52 role=0, 

53 profile=PROFILE, 

54 ) 

55 if not Course('Public'): 

56 Course.add_course('Public', 'first_admin') 

57 

58 if __name__ != '__main__': 

59 logger = logging.getLogger('gunicorn.error') 

60 app.logger.handlers = logger.handlers 

61 app.logger.setLevel(logger.level) 

62 

63 return app 

64 

65 

66def setup_smtp(app: Flask): 

67 logger = logging.getLogger('gunicorn.error') 

68 if os.getenv('SMTP_SERVER') is None: 

69 logger.info( 

70 '\'SMTP_SERVER\' is not set. email-related function will be disabled' 

71 ) 

72 return 

73 if os.getenv('SMTP_NOREPLY') is None: 

74 raise RuntimeError('missing required configuration \'SMTP_NOREPLY\'') 

75 if os.getenv('SMTP_NOREPLY_PASSWORD') is None: 

76 logger.info('\'SMTP_NOREPLY\' set but \'SMTP_NOREPLY_PASSWORD\' not') 

77 # config for external URLs 

78 server_name = os.getenv('SERVER_NAME') 

79 if server_name is None: 

80 raise RuntimeError('missing required configuration \'SERVER_NAME\'') 

81 app.config['SERVER_NAME'] = server_name 

82 if (application_root := os.getenv('APPLICATION_ROOT')) is not None: 

83 app.config['APPLICATION_ROOT'] = application_root