example_a_flask.py 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. class FlaskRoute(object):
  34. def __init__(self, app, rule, method, callback, name, **options):
  35. self.app = app
  36. self.rule = rule
  37. self.method = method
  38. self.callback = callback
  39. self.name = name
  40. class Flaskapp(Flask):
  41. @property
  42. def routes(self):
  43. result = []
  44. for r in self.url_map.iter_rules():
  45. rule = r.rule
  46. callback = self.view_functions[r.endpoint]
  47. method = [x for x in r.methods if x not in [
  48. 'OPTIONS', 'HEAD']][0] # TODO : other solution ?
  49. name = r.endpoint
  50. app = self
  51. f = FlaskRoute(self, rule, method, callback, name)
  52. result.append(f)
  53. return result
  54. app = Flaskapp(__name__)
  55. class Controllers(object):
  56. @hapic.with_api_doc()
  57. # @hapic.ext.bottle.bottle_context()
  58. @hapic.handle_exception(ZeroDivisionError, http_code=HTTPStatus.BAD_REQUEST)
  59. @hapic.input_path(HelloPathSchema())
  60. @hapic.input_query(HelloQuerySchema())
  61. @hapic.output_body(HelloResponseSchema())
  62. def hello(self, name: str, hapic_data: HapicData):
  63. """
  64. my endpoint hello
  65. ---
  66. get:
  67. description: my description
  68. parameters:
  69. - in: "path"
  70. description: "hello"
  71. name: "name"
  72. type: "string"
  73. responses:
  74. 200:
  75. description: A pet to be returned
  76. schema: HelloResponseSchema
  77. """
  78. if name == 'zero':
  79. raise ZeroDivisionError('Don\'t call him zero !')
  80. return {
  81. 'sentence': 'Hello !',
  82. 'name': name,
  83. }
  84. @hapic.with_api_doc()
  85. # @hapic.ext.bottle.bottle_context()
  86. # @hapic.error_schema(ErrorResponseSchema())
  87. @hapic.input_path(HelloPathSchema())
  88. @hapic.input_body(HelloJsonSchema())
  89. @hapic.output_body(HelloResponseSchema())
  90. @bob
  91. def hello2(self, name: str, hapic_data: HapicData):
  92. return {
  93. 'sentence': 'Hello !',
  94. 'name': name,
  95. 'color': hapic_data.body.get('color'),
  96. }
  97. kwargs = {'validated_data': {'name': 'bob'}, 'name': 'bob'}
  98. @hapic.with_api_doc()
  99. # @hapic.ext.bottle.bottle_context()
  100. # @hapic.error_schema(ErrorResponseSchema())
  101. @hapic.input_path(HelloPathSchema())
  102. @hapic.output_body(HelloResponseSchema())
  103. def hello3(self, name: str,hapic_data: HapicData ):
  104. return {
  105. 'sentence': 'Hello !',
  106. 'name': name,
  107. }
  108. def bind(self, app):
  109. pass
  110. app.add_url_rule('/hello/<name>', "hello", self.hello)
  111. app.add_url_rule('/hello/<name>', "hello2",
  112. self.hello2, methods=['POST', ])
  113. app.add_url_rule('/hello3/<name>', "hello3", self.hello3)
  114. #app = bottle.Bottle()
  115. controllers = Controllers()
  116. controllers.bind(app)
  117. # time.sleep(1)
  118. # s = hapic.generate_doc(app)
  119. # ss = json.loads(json.dumps(s))
  120. # for path in ss['paths']:
  121. # for method in ss['paths'][path]:
  122. # for response_code in ss['paths'][path][method]['responses']:
  123. # ss['paths'][path][method]['responses'][int(response_code)] = ss['paths'][path][method]['responses'][response_code]
  124. # del ss['paths'][path][method]['responses'][int(response_code)]
  125. # print(yaml.dump(ss, default_flow_style=False))
  126. # time.sleep(1)
  127. hapic.set_context(hapic.ext.flask.FlaskContext(app))
  128. print(json.dumps(hapic.generate_doc()))
  129. #import pdb; pdb.set_trace()
  130. app.run(host='localhost', port=8080, debug=True)