example_a_flask.py 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # -*- coding: utf-8 -*-
  2. import json
  3. try: # Python 3.5+
  4. from http import HTTPStatus
  5. except ImportError:
  6. from http import client as HTTPStatus
  7. from flask import Flask
  8. import hapic
  9. from example import HelloResponseSchema, HelloPathSchema, HelloJsonSchema, \
  10. ErrorResponseSchema, HelloQuerySchema
  11. from hapic.data import HapicData
  12. from hapic.ext.flask import FlaskContext
  13. def bob(f):
  14. def boby(*args, **kwargs):
  15. return f(*args, **kwargs)
  16. return boby
  17. app = Flask(__name__)
  18. class Controllers(object):
  19. @hapic.with_api_doc()
  20. # @hapic.ext.bottle.bottle_context()
  21. @hapic.handle_exception(ZeroDivisionError, http_code=HTTPStatus.BAD_REQUEST)
  22. @hapic.input_path(HelloPathSchema())
  23. @hapic.input_query(HelloQuerySchema())
  24. @hapic.output_body(HelloResponseSchema())
  25. def hello(self, name: str, hapic_data: HapicData):
  26. """
  27. my endpoint hello
  28. ---
  29. get:
  30. description: my description
  31. parameters:
  32. - in: "path"
  33. description: "hello"
  34. name: "name"
  35. type: "string"
  36. responses:
  37. 200:
  38. description: A pet to be returned
  39. schema: HelloResponseSchema
  40. """
  41. if name == 'zero':
  42. raise ZeroDivisionError('Don\'t call him zero !')
  43. return {
  44. 'sentence': 'Hello !',
  45. 'name': name,
  46. }
  47. @hapic.with_api_doc()
  48. # @hapic.ext.bottle.bottle_context()
  49. # @hapic.error_schema(ErrorResponseSchema())
  50. @hapic.input_path(HelloPathSchema())
  51. @hapic.input_body(HelloJsonSchema())
  52. @hapic.output_body(HelloResponseSchema())
  53. @bob
  54. def hello2(self, name: str, hapic_data: HapicData):
  55. return {
  56. 'sentence': 'Hello !',
  57. 'name': name,
  58. 'color': hapic_data.body.get('color'),
  59. }
  60. kwargs = {'validated_data': {'name': 'bob'}, 'name': 'bob'}
  61. @hapic.with_api_doc()
  62. # @hapic.ext.bottle.bottle_context()
  63. # @hapic.error_schema(ErrorResponseSchema())
  64. @hapic.input_path(HelloPathSchema())
  65. @hapic.output_body(HelloResponseSchema())
  66. def hello3(self, name: str,hapic_data: HapicData ):
  67. return {
  68. 'sentence': 'Hello !',
  69. 'name': name,
  70. }
  71. def bind(self, app):
  72. pass
  73. app.add_url_rule('/hello/<name>', "hello", self.hello)
  74. app.add_url_rule('/hello/<name>', "hello2",
  75. self.hello2, methods=['POST', ])
  76. app.add_url_rule('/hello3/<name>', "hello3", self.hello3)
  77. controllers = Controllers()
  78. controllers.bind(app)
  79. hapic.set_context(FlaskContext(app))
  80. hapic.add_documentation_view('/api-doc', 'DOC', 'Generated doc')
  81. print(json.dumps(hapic.generate_doc()))
  82. app.run(host='localhost', port=8080, debug=True)