爱抱
aiohug的Python项目详细描述
目标:
- 将aiohttp(>;=3.1)请求解包到带注释的参数
- 验证处理程序参数
- 生成夸张的规范
示例
来自path和query的参数
fromaiohttpimportwebfromaiohugimportRouteTableDefroutes=RouteTableDef()@routes.get("/hello/{name}/")asyncdefhello(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)
处理程序签名中不再有request对象-只需要参数。
具有模式的正文
fromaiohttpimportwebfromaiohugimportRouteTableDefroutes=RouteTableDef()classPayloadSchema(Schema):count=fields.Int()@routes.get("/")asyncdefwith_body(body:PayloadSchema()):returnbodyapp=create_app()app.add_routes(routes)client=awaittest_client(app)resp=awaitclient.get("/",json={"count":"5","another":7})assertawaitresp.json()=={"count":5}
另一个快捷方式
@routes.post("/ping/")asyncdefping():return201,"pong"
招摇过市
使用aiohug_swagger包。
装饰师
由于aiohttp路由的方式,所有装饰器都可以工作到资源处理程序 必须在aiohug的路由修饰符(即
之前应用。defsome_decorator(func):@wraps(func)defwrapper(request,*args,**kwargs):# Some logic for decoratorreturnfunc(*args,**kwargs)returnwrapper@routes.get("/ping/")@some_decoratorasyncdefhello():return"pong"
此外,确保使用functools模块中的wrapsdecorator装饰包装函数 -否则aiohug将无法访问原始处理程序的参数和注释。
待办事项:
- 不传递默认参数