Browse Source

fixes bug about default error code for response error

Damien Accorsi 3 years ago
parent
commit
b12050e170

+ 0 - 0
example/fast.py View File


+ 0 - 0
example/usermanagement/__init__.py View File


+ 0 - 0
example/usermanagement/schema.py View File


+ 0 - 0
example/usermanagement/serve_bottle.py View File


+ 116 - 0
example/usermanagement/serve_flask.py View File

@@ -0,0 +1,116 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+from datetime import datetime
4
+from http import HTTPStatus
5
+import json
6
+import flask
7
+import time
8
+from wsgiref.simple_server import make_server
9
+
10
+from hapic import Hapic
11
+from hapic.data import HapicData
12
+from hapic.ext.flask import FlaskContext
13
+
14
+from example.usermanagement.schema import AboutSchema
15
+from example.usermanagement.schema import NoContentSchema
16
+from example.usermanagement.schema import UserDigestSchema
17
+from example.usermanagement.schema import UserIdPathSchema
18
+from example.usermanagement.schema import UserSchema
19
+
20
+from example.usermanagement.userlib import User
21
+from example.usermanagement.userlib import UserLib
22
+from example.usermanagement.userlib import UserNotFound
23
+
24
+hapic = Hapic()
25
+
26
+
27
+class FlaskController(object):
28
+    @hapic.with_api_doc()
29
+    @hapic.output_body(AboutSchema())
30
+    def about(self):
31
+        """
32
+        This endpoint allow to check that the API is running. This description
33
+        is generated from the docstring of the method.
34
+        """
35
+        return {
36
+            'version': '1.2.3',
37
+            'datetime': datetime.now(),
38
+        }
39
+
40
+    @hapic.with_api_doc()
41
+    @hapic.output_body(UserDigestSchema(many=True))
42
+    def get_users(self):
43
+        """
44
+        Obtain users list.
45
+        """
46
+        return UserLib().get_users()
47
+
48
+    @hapic.with_api_doc()
49
+    @hapic.handle_exception(UserNotFound, HTTPStatus.NOT_FOUND)
50
+    @hapic.input_path(UserIdPathSchema())
51
+    @hapic.output_body(UserSchema())
52
+    def get_user(self, id, hapic_data: HapicData):
53
+        """
54
+        Return a user taken from the list or return a 404
55
+        """
56
+        return UserLib().get_user(int(hapic_data.path['id']))
57
+
58
+    @hapic.with_api_doc()
59
+    # TODO - G.M - 2017-12-5 - Support input_forms ?
60
+    # TODO - G.M - 2017-12-5 - Support exclude, only ?
61
+    @hapic.input_body(UserSchema(exclude=('id',)))
62
+    @hapic.output_body(UserSchema())
63
+    def add_user(self, hapic_data: HapicData):
64
+        """
65
+        Add a user to the list
66
+        """
67
+        print(hapic_data.body)
68
+        new_user = User(**hapic_data.body)
69
+        return UserLib().add_user(new_user)
70
+
71
+    @hapic.with_api_doc()
72
+    @hapic.handle_exception(UserNotFound, HTTPStatus.NOT_FOUND)
73
+    @hapic.output_body(NoContentSchema(), default_http_code=204)
74
+    @hapic.input_path(UserIdPathSchema())
75
+    def del_user(self, id, hapic_data: HapicData):
76
+        UserLib().del_user(int(hapic_data.path['id']))
77
+        return NoContentSchema()
78
+
79
+    def bind(self, app: flask.Flask):
80
+        app.add_url_rule('/about', view_func=self.about)
81
+        app.add_url_rule('/users', view_func=self.get_users)
82
+        app.add_url_rule('/users/<id>', view_func=self.get_user)
83
+        app.add_url_rule('/users/', view_func=self.add_user, methods=['POST'])
84
+        app.add_url_rule('/users/<id>', view_func=self.del_user, methods=['DELETE'])  # nopep8
85
+
86
+
87
+if __name__ == "__main__":
88
+    app = flask.Flask(__name__)
89
+    controllers = FlaskController()
90
+    controllers.bind(app)
91
+    hapic.set_context(FlaskContext(app))
92
+
93
+    print('')
94
+    print('')
95
+    print('GENERATING OPENAPI DOCUMENTATION')
96
+    openapi_file_name = 'api-documentation.json'
97
+    with open(openapi_file_name, 'w') as openapi_file_handle:
98
+        openapi_file_handle.write(
99
+            json.dumps(
100
+                hapic.generate_doc(
101
+                    title='Demo API documentation',
102
+                    description='This documentation has been generated from '
103
+                                'code. You can see it using swagger: '
104
+                                'http://editor2.swagger.io/'
105
+                )
106
+            )
107
+        )
108
+
109
+    print('Documentation generated in {}'.format(openapi_file_name))
110
+    time.sleep(1)
111
+
112
+    print('')
113
+    print('')
114
+    print('RUNNING FLASK SERVER NOW')
115
+    # Run app
116
+    app.run(host='127.0.0.1', port=8082, debug=True)

+ 126 - 0
example/usermanagement/serve_pyramid.py View File

@@ -0,0 +1,126 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+from datetime import datetime
4
+from http import HTTPStatus
5
+import json
6
+from pyramid.config import Configurator
7
+import time
8
+from wsgiref.simple_server import make_server
9
+
10
+from hapic import Hapic
11
+from hapic.data import HapicData
12
+from hapic.ext.pyramid import PyramidContext
13
+
14
+from example.usermanagement.schema import AboutSchema
15
+from example.usermanagement.schema import NoContentSchema
16
+from example.usermanagement.schema import UserDigestSchema
17
+from example.usermanagement.schema import UserIdPathSchema
18
+from example.usermanagement.schema import UserSchema
19
+
20
+from example.usermanagement.userlib import User
21
+from example.usermanagement.userlib import UserLib
22
+from example.usermanagement.userlib import UserNotFound
23
+
24
+hapic = Hapic()
25
+
26
+
27
+class PyramidController(object):
28
+    @hapic.with_api_doc()
29
+    @hapic.output_body(AboutSchema())
30
+    def about(self, context, request):
31
+        """
32
+        This endpoint allow to check that the API is running. This description
33
+        is generated from the docstring of the method.
34
+        """
35
+        return {
36
+            'version': '1.2.3',
37
+            'datetime': datetime.now(),
38
+        }
39
+
40
+    @hapic.with_api_doc()
41
+    @hapic.output_body(UserDigestSchema(many=True))
42
+    def get_users(self, context, request):
43
+        """
44
+        Obtain users list.
45
+        """
46
+        return UserLib().get_users()
47
+
48
+    @hapic.with_api_doc()
49
+    @hapic.handle_exception(UserNotFound, HTTPStatus.NOT_FOUND)
50
+    @hapic.input_path(UserIdPathSchema())
51
+    @hapic.output_body(UserSchema())
52
+    def get_user(self, context, request, hapic_data: HapicData):
53
+        """
54
+        Return a user taken from the list or return a 404
55
+        """
56
+        return UserLib().get_user(int(hapic_data.path['id']))
57
+
58
+    @hapic.with_api_doc()
59
+    # TODO - G.M - 2017-12-5 - Support input_forms ?
60
+    # TODO - G.M - 2017-12-5 - Support exclude, only ?
61
+    @hapic.input_body(UserSchema(exclude=('id',)))
62
+    @hapic.output_body(UserSchema())
63
+    def add_user(self, context, request, hapic_data: HapicData):
64
+        """
65
+        Add a user to the list
66
+        """
67
+        print(hapic_data.body)
68
+        new_user = User(**hapic_data.body)
69
+        return UserLib().add_user(new_user)
70
+
71
+    @hapic.with_api_doc()
72
+    @hapic.handle_exception(UserNotFound, HTTPStatus.NOT_FOUND)
73
+    @hapic.output_body(NoContentSchema(), default_http_code=204)
74
+    @hapic.input_path(UserIdPathSchema())
75
+    def del_user(self, context, request, hapic_data: HapicData):
76
+        UserLib().del_user(int(hapic_data.path['id']))
77
+        return NoContentSchema()
78
+
79
+    def bind(self, configurator: Configurator):
80
+        configurator.add_route('about', '/about', request_method='GET')
81
+        configurator.add_view(self.about, route_name='about', renderer='json')
82
+
83
+        configurator.add_route('get_users', '/users', request_method='GET')  # nopep8
84
+        configurator.add_view(self.get_users, route_name='get_users', renderer='json')  # nopep8
85
+
86
+        configurator.add_route('get_user', '/users/{id}', request_method='GET')  # nopep8
87
+        configurator.add_view(self.get_user, route_name='get_user', renderer='json')  # nopep8
88
+
89
+        configurator.add_route('add_user', '/users', request_method='POST')  # nopep8
90
+        configurator.add_view(self.add_user, route_name='add_user', renderer='json')  # nopep8
91
+
92
+        configurator.add_route('del_user', '/users/{id}', request_method='DELETE')  # nopep8
93
+        configurator.add_view(self.del_user, route_name='del_user', renderer='json')  # nopep8
94
+
95
+
96
+if __name__ == "__main__":
97
+    configurator = Configurator(autocommit=True)
98
+    controllers = PyramidController()
99
+    controllers.bind(configurator)
100
+    hapic.set_context(PyramidContext(configurator))
101
+
102
+    print('')
103
+    print('')
104
+    print('GENERATING OPENAPI DOCUMENTATION')
105
+    openapi_file_name = 'api-documentation.json'
106
+    with open(openapi_file_name, 'w') as openapi_file_handle:
107
+        openapi_file_handle.write(
108
+            json.dumps(
109
+                hapic.generate_doc(
110
+                    title='Demo API documentation',
111
+                    description='This documentation has been generated from '
112
+                                'code. You can see it using swagger: '
113
+                                'http://editor2.swagger.io/'
114
+                )
115
+            )
116
+        )
117
+
118
+    print('Documentation generated in {}'.format(openapi_file_name))
119
+    time.sleep(1)
120
+
121
+    print('')
122
+    print('')
123
+    print('RUNNING PYRAMID SERVER NOW')
124
+    # Run app
125
+    server = make_server('127.0.0.1', 8083, configurator.make_wsgi_app())
126
+    server.serve_forever()

+ 0 - 0
example/usermanagement/userlib.py View File


+ 1 - 1
hapic/hapic.py View File

@@ -115,7 +115,7 @@ class Hapic(object):
115 115
         schema: typing.Any,
116 116
         processor: ProcessorInterface = None,
117 117
         context: ContextInterface = None,
118
-        error_http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
118
+        error_http_code: HTTPStatus = HTTPStatus.INTERNAL_SERVER_ERROR,
119 119
         default_http_code: HTTPStatus = HTTPStatus.OK,
120 120
     ) -> typing.Callable[[typing.Callable[..., typing.Any]], typing.Any]:
121 121
         processor = processor or MarshmallowOutputProcessor()