example_a_aiohttp.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # coding: utf-8
  2. import json
  3. import yaml
  4. from aiohttp import web
  5. from hapic import async as hapic
  6. from hapic import async as HapicData
  7. import marshmallow
  8. from hapic.ext.aiohttp.context import AiohttpContext
  9. class HandleInputPath(marshmallow.Schema):
  10. name = marshmallow.fields.String(
  11. required=False,
  12. allow_none=True,
  13. )
  14. class HandleInputBody(marshmallow.Schema):
  15. foo = marshmallow.fields.String(
  16. required=True,
  17. )
  18. class Handle2OutputBody(marshmallow.Schema):
  19. data = marshmallow.fields.Dict(
  20. required=True,
  21. )
  22. class HandleOutputBody(marshmallow.Schema):
  23. sentence = marshmallow.fields.String(
  24. required=True,
  25. )
  26. @hapic.with_api_doc()
  27. @hapic.input_path(HandleInputPath())
  28. # @hapic.output_body(HandleOutputBody())
  29. async def handle(request, hapic_data):
  30. name = request.match_info.get('name', "Anonymous")
  31. text = "Hello, " + name
  32. return web.json_response({
  33. 'sentence': text,
  34. })
  35. @hapic.with_api_doc()
  36. @hapic.input_body(HandleInputBody())
  37. @hapic.output_body(Handle2OutputBody())
  38. async def handle2(request, hapic_data: HapicData):
  39. data = hapic_data.body
  40. return {
  41. 'data': data,
  42. }
  43. async def do_login(request):
  44. data = await request.json()
  45. login = data['login']
  46. password = data['password']
  47. return web.json_response({
  48. 'login': login,
  49. })
  50. app = web.Application(debug=True)
  51. app.add_routes([
  52. web.get('/n/', handle),
  53. web.get('/n/{name}', handle),
  54. web.post('/n/{name}', handle),
  55. web.post('/b/', handle2),
  56. web.post('/login', do_login),
  57. ])
  58. hapic.set_context(AiohttpContext(app))
  59. # print(yaml.dump(
  60. # json.loads(json.dumps(hapic.generate_doc())),
  61. # default_flow_style=False,
  62. # ))
  63. web.run_app(app)