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