serve_flask.py 3.7KB

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