Coverage for src/ensae_teaching_cs/td_1a/simple_flask_site.py: 65%

43 statements  

« prev     ^ index     » next       coverage.py v7.1.0, created at 2023-04-28 06:23 +0200

1# -*- coding: utf-8 -*- 

2""" 

3@file 

4@brief Defines a simple web site in Flask which allows unit testing 

5""" 

6import logging 

7from flask import Flask, request 

8from .flask_helper import Text2Response, Exception2Response 

9 

10 

11def create_application(global_params): 

12 """ 

13 Creates a :epkg:`Flask` application. 

14 """ 

15 if global_params is None: 

16 global_params = {} 

17 params = global_params 

18 log = logging.getLogger('werkzeug') 

19 log.setLevel(logging.ERROR) 

20 app = Flask(__name__) 

21 

22 def shutdown_server(): 

23 """ 

24 To shutdown the service. 

25 """ 

26 func = request.environ.get('werkzeug.server.shutdown') 

27 if func is None: 

28 params['thread'].raise_exception() 

29 return 

30 func() 

31 

32 @app.route('/shutdown/', methods=['POST']) 

33 def shutdown(): # pylint: disable=W0612 

34 """ 

35 Shuts down the service. 

36 """ 

37 shutdown_server() 

38 return Text2Response('Server shutting down...') 

39 

40 @app.route('/help/<path:command>') 

41 def help_command(command): # pylint: disable=W0612 

42 """ 

43 Returns a very basic help message on command command. 

44 

45 @param command command 

46 @return help 

47 """ 

48 try: 

49 if command is None or command == "exception": 

50 raise RuntimeError(f"no help for command: {command}") 

51 return Text2Response(f"help for command: {command}") 

52 except Exception as e: 

53 return Exception2Response(e) 

54 

55 @app.route('/form/', methods=['POSTS']) 

56 def form(): # pylint: disable=W0612 

57 """ 

58 process a form 

59 """ 

60 try: 

61 rows = [] 

62 for k, v in request.form.to.dict().items(): 

63 rows.append(f"{k}={v}") 

64 return Text2Response("\n".join(rows)) 

65 except Exception as e: 

66 return Exception2Response(e) 

67 

68 @app.route('/') 

69 def main_page(): # pylint: disable=W0612 

70 """ 

71 Defines the main page. 

72 """ 

73 message = """Simple Flask Site 

74 / help on command 

75 /help/<command> help on command command 

76 /upload/ upload a file (use post) 

77 /shutdown/ shutdown the server (for unit test) 

78 /form/ process a form 

79 """.replace(" ", "") 

80 return Text2Response(message) 

81 

82 return app