example_a_bottle.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # -*- coding: utf-8 -*-
  2. import json
  3. from http import HTTPStatus
  4. import bottle
  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, HelloFileSchema
  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 Controllers(object):
  34. @hapic.with_api_doc()
  35. # @hapic.ext.bottle.bottle_context()
  36. @hapic.handle_exception(ZeroDivisionError, http_code=HTTPStatus.BAD_REQUEST)
  37. @hapic.input_path(HelloPathSchema())
  38. @hapic.input_query(HelloQuerySchema())
  39. @hapic.output_body(HelloResponseSchema())
  40. def hello(self, name: str, hapic_data: HapicData):
  41. """
  42. my endpoint hello
  43. ---
  44. get:
  45. description: my description
  46. parameters:
  47. - in: "path"
  48. description: "hello"
  49. name: "name"
  50. type: "string"
  51. responses:
  52. 200:
  53. description: A pet to be returned
  54. schema: HelloResponseSchema
  55. """
  56. if name == 'zero':
  57. raise ZeroDivisionError('Don\'t call him zero !')
  58. return {
  59. 'sentence': 'Hello !',
  60. 'name': name,
  61. }
  62. @hapic.with_api_doc()
  63. # @hapic.ext.bottle.bottle_context()
  64. # @hapic.error_schema(ErrorResponseSchema())
  65. @hapic.input_path(HelloPathSchema())
  66. @hapic.input_body(HelloJsonSchema())
  67. @hapic.output_body(HelloResponseSchema())
  68. @bob
  69. def hello2(self, name: str, hapic_data: HapicData):
  70. return {
  71. 'sentence': 'Hello !',
  72. 'name': name,
  73. 'color': hapic_data.body.get('color'),
  74. }
  75. kwargs = {'validated_data': {'name': 'bob'}, 'name': 'bob'}
  76. @hapic.with_api_doc()
  77. # @hapic.ext.bottle.bottle_context()
  78. # @hapic.error_schema(ErrorResponseSchema())
  79. @hapic.input_path(HelloPathSchema())
  80. @hapic.output_body(HelloResponseSchema())
  81. def hello3(self, name: str, hapic_data: HapicData):
  82. return {
  83. 'sentence': 'Hello !',
  84. 'name': name,
  85. }
  86. @hapic.with_api_doc()
  87. @hapic.input_files(HelloFileSchema())
  88. @hapic.output_file(['image/jpeg'])
  89. def hellofile(self, hapic_data: HapicData):
  90. return hapic_data.files['myfile']
  91. def bind(self, app):
  92. app.route('/hello/<name>', callback=self.hello)
  93. app.route('/hello/<name>', callback=self.hello2, method='POST')
  94. app.route('/hello3/<name>', callback=self.hello3)
  95. app.route('/hellofile', callback=self.hellofile)
  96. app = bottle.Bottle()
  97. controllers = Controllers()
  98. controllers.bind(app)
  99. hapic.set_context(hapic.ext.bottle.BottleContext(app))
  100. time.sleep(1)
  101. s = hapic.generate_doc()
  102. ss = json.loads(json.dumps(s))
  103. for path in ss['paths']:
  104. for method in ss['paths'][path]:
  105. for response_code in ss['paths'][path][method]['responses']:
  106. ss['paths'][path][method]['responses'][int(response_code)] = ss['paths'][path][method]['responses'][response_code]
  107. del ss['paths'][path][method]['responses'][int(response_code)]
  108. print(yaml.dump(ss, default_flow_style=False))
  109. time.sleep(1)
  110. #print(json.dumps(hapic.generate_doc()))
  111. app.run(host='localhost', port=8080, debug=True)