serve_flask.py 3.8KB

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