example_a.py 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. from http import HTTPStatus
  3. import bottle
  4. import hapic
  5. from example import HelloResponseSchema, HelloPathSchema, HelloJsonSchema, \
  6. ErrorResponseSchema
  7. from hapic.data import HapicData
  8. app = bottle.Bottle()
  9. def bob(f):
  10. def boby(*args, **kwargs):
  11. return f(*args, **kwargs)
  12. return boby
  13. @hapic.with_api_doc()
  14. # @hapic.ext.bottle.bottle_context()
  15. @hapic.handle_exception(ZeroDivisionError, http_code=HTTPStatus.BAD_REQUEST)
  16. @hapic.input_path(HelloPathSchema())
  17. @hapic.output_body(HelloResponseSchema())
  18. def hello(name: str, hapic_data: HapicData):
  19. if name == 'zero':
  20. raise ZeroDivisionError('Don\'t call him zero !')
  21. return {
  22. 'sentence': 'Hello !',
  23. 'name': name,
  24. }
  25. @hapic.with_api_doc()
  26. # @hapic.ext.bottle.bottle_context()
  27. # @hapic.error_schema(ErrorResponseSchema())
  28. @hapic.input_path(HelloPathSchema())
  29. @hapic.input_body(HelloJsonSchema())
  30. @hapic.output_body(HelloResponseSchema())
  31. @bob
  32. def hello2(name: str, hapic_data: HapicData):
  33. return {
  34. 'sentence': 'Hello !',
  35. 'name': name,
  36. 'color': hapic_data.body.get('color'),
  37. }
  38. kwargs = {'validated_data': {'name': 'bob'}, 'name': 'bob'}
  39. @hapic.with_api_doc()
  40. # @hapic.ext.bottle.bottle_context()
  41. # @hapic.error_schema(ErrorResponseSchema())
  42. @hapic.output_body(HelloResponseSchema())
  43. def hello3(name: str):
  44. return {
  45. 'sentence': 'Hello !',
  46. 'name': name,
  47. }
  48. app.route('/hello/<name>', callback=hello)
  49. app.route('/hello2/<name>', callback=hello2, method='POST')
  50. app.route('/hello3/<name>', callback=hello3)
  51. hapic.generate_doc(app)
  52. app.run(host='localhost', port=8080, debug=True)