example_a_flask.py 2.6KB

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