example_a_aiohttp.py 1.2KB

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