example_a_flask.py 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # -*- coding: utf-8 -*-
  2. import json
  3. from http import HTTPStatus
  4. from flask import Flask
  5. import time
  6. import yaml
  7. from beaker.middleware import SessionMiddleware
  8. import hapic
  9. from example import HelloResponseSchema, HelloPathSchema, HelloJsonSchema, \
  10. ErrorResponseSchema, HelloQuerySchema
  11. from hapic.data import HapicData
  12. # hapic.global_exception_handler(UnAuthExc, StandardErrorSchema)
  13. # hapic.global_exception_handler(UnAuthExc2, StandardErrorSchema)
  14. # hapic.global_exception_handler(UnAuthExc3, StandardErrorSchema)
  15. # bottle.default_app.push(app)
  16. # session_opts = {
  17. # 'session.type': 'file',
  18. # 'session.data_dir': '/tmp',
  19. # 'session.cookie_expires': 3600,
  20. # 'session.auto': True
  21. # }
  22. # session_middleware = SessionMiddleware(
  23. # app,
  24. # session_opts,
  25. # environ_key='beaker.session',
  26. # key='beaker.session.id',
  27. # )
  28. # app = session_middleware.wrap_app
  29. def bob(f):
  30. def boby(*args, **kwargs):
  31. return f(*args, **kwargs)
  32. return boby
  33. app = Flask(__name__)
  34. class Controllers(object):
  35. @hapic.with_api_doc()
  36. # @hapic.ext.bottle.bottle_context()
  37. @hapic.handle_exception(ZeroDivisionError, http_code=HTTPStatus.BAD_REQUEST)
  38. @hapic.input_path(HelloPathSchema())
  39. @hapic.input_query(HelloQuerySchema())
  40. @hapic.output_body(HelloResponseSchema())
  41. def hello(self, name: str, hapic_data: HapicData):
  42. """
  43. my endpoint hello
  44. ---
  45. get:
  46. description: my description
  47. parameters:
  48. - in: "path"
  49. description: "hello"
  50. name: "name"
  51. type: "string"
  52. responses:
  53. 200:
  54. description: A pet to be returned
  55. schema: HelloResponseSchema
  56. """
  57. if name == 'zero':
  58. raise ZeroDivisionError('Don\'t call him zero !')
  59. return {
  60. 'sentence': 'Hello !',
  61. 'name': name,
  62. }
  63. @hapic.with_api_doc()
  64. # @hapic.ext.bottle.bottle_context()
  65. # @hapic.error_schema(ErrorResponseSchema())
  66. @hapic.input_path(HelloPathSchema())
  67. @hapic.input_body(HelloJsonSchema())
  68. @hapic.output_body(HelloResponseSchema())
  69. @bob
  70. def hello2(self, name: str, hapic_data: HapicData):
  71. return {
  72. 'sentence': 'Hello !',
  73. 'name': name,
  74. 'color': hapic_data.body.get('color'),
  75. }
  76. kwargs = {'validated_data': {'name': 'bob'}, 'name': 'bob'}
  77. @hapic.with_api_doc()
  78. # @hapic.ext.bottle.bottle_context()
  79. # @hapic.error_schema(ErrorResponseSchema())
  80. @hapic.input_path(HelloPathSchema())
  81. @hapic.output_body(HelloResponseSchema())
  82. def hello3(self, name: str,hapic_data: HapicData ):
  83. return {
  84. 'sentence': 'Hello !',
  85. 'name': name,
  86. }
  87. def bind(self, app):
  88. pass
  89. app.add_url_rule('/hello/<name>', "hello", self.hello)
  90. app.add_url_rule('/hello/<name>', "hello2",
  91. self.hello2, methods=['POST', ])
  92. app.add_url_rule('/hello3/<name>', "hello3", self.hello3)
  93. #app = bottle.Bottle()
  94. controllers = Controllers()
  95. controllers.bind(app)
  96. # time.sleep(1)
  97. # s = hapic.generate_doc(app)
  98. # ss = json.loads(json.dumps(s))
  99. # for path in ss['paths']:
  100. # for method in ss['paths'][path]:
  101. # for response_code in ss['paths'][path][method]['responses']:
  102. # ss['paths'][path][method]['responses'][int(response_code)] = ss['paths'][path][method]['responses'][response_code]
  103. # del ss['paths'][path][method]['responses'][int(response_code)]
  104. # print(yaml.dump(ss, default_flow_style=False))
  105. # time.sleep(1)
  106. hapic.set_context(hapic.ext.flask.FlaskContext(app))
  107. print(json.dumps(hapic.generate_doc()))
  108. #import pdb; pdb.set_trace()
  109. app.run(host='localhost', port=8080, debug=True)