example_a_aiohttp.py 1.7KB

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