- Unpack aiohttp (>=3.1) request to arguments with annotations
- Validate handlers arguments
- Generate swagger specification
from aiohttp import web
from aiohug import RouteTableDef
from marshmallow import fields
routes = RouteTableDef()
@routes.get("/hello/{name}/")
async def hello(name: fields.String(), greeting: fields.String() = "Hello"):
return {"msg": f"{greeting}, {name}"}
app = web.Application()
app.add_routes(routes)
if __name__ == "__main__":
web.run_app(app)
There is no request
object in handler signature anymore - only required arguments.
from aiohttp import web
from aiohug import RouteTableDef
routes = RouteTableDef()
class PayloadSchema(Schema):
count = fields.Int()
@routes.get("/")
async def with_body(body: PayloadSchema()):
return body
app = create_app()
app.add_routes(routes)
client = await test_client(app)
resp = await client.get("/", json={"count": "5", "another": 7})
assert await resp.json() == {"count": 5}
@routes.post("/ping/")
async def ping():
return 201, "pong"
Use aiohug_swagger package.
Because of the way aiohttp
routing works all decorators to resource handlers
must be applied BEFORE aiohug
's routing decorator, i.e.
def some_decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
# Some logic for decorator
return func(*args, **kwargs)
return wrapper
@routes.get("/ping/")
@some_decorator
async def hello():
return "pong"
Moreover, make sure to decorate wrapper functions with wraps
decorator from functools
module
- otherwise aiohug
won't be able to access original handler's arguments and annotations.
It's just hug API implementation for aiohttp
- don’t pass default arguments