用webargs解析和验证starlette的声明性请求
webargs-starlette的Python项目详细描述
webargs starlette是一个用于声明性请求解析和 使用Starlette验证, 建在webargs之上。
它具有webargs的所有优点, 为类型注释添加一些额外的糖。
importuvicornfromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")@use_annotations(locations=("query",))asyncdefindex(request,name:str="World"):returnJSONResponse({"Hello":name})if__name__=="__main__":uvicorn.run(app,port=5000)# curl 'http://localhost:5000/'# {"Hello": "World"}# curl 'http://localhost:5000/?name=Ada'# {"Hello": "Ada"}
安装
pip install -U webargs-starlette
用法
分析器用法
使用parser.parse解析starletteRequest和 字段字典。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportparserapp=Starlette()@app.route("/")asyncdefhomepage(request):args={"name":fields.Str(required=True),"greeting":fields.Str(missing="hello")}parsed=awaitparser.parse(args,request)greeting=parsed["greeting"]name=parsed["name"]returnJSONResponse({"message":f"{greeting} {name}"})
装饰师
使用use_argsdecorator注入解析的参数 将字典放入处理程序函数中。下面的代码片段相当于 第一个例子。
important:修饰函数必须是协同函数。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportuse_argsapp=Starlette()@app.route("/")@use_args({"name":fields.Str(required=True),"greeting":fields.Str(missing="hello")})asyncdefhomepage(request,args):greeting=args["greeting"]name=args["name"]returnJSONResponse({"message":f"{greeting} {name}"})
use_kwargsdecorator将解析的参数作为关键字参数注入。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfromwebargs_starletteimportuse_argsapp=Starlette()@app.route("/")@use_kwargs({"name":fields.Str(required=True),"greeting":fields.Str(missing="hello")})asyncdefhomepage(request,name,greeting):returnJSONResponse({"message":f"{greeting} {name}"})
见decorator_example.py 有关use_args和use_kwargs用法的更完整示例。
错误处理
当验证失败时,解析器将引发一个WebargsHTTPException, 它与starlette的HTTPException相同,添加了 在messages(验证消息)、headers、exception(底层异常)和schema(棉花糖Schema)属性中。
可以使用自定义异常处理程序将错误消息返回为 json。
fromstarlette.responsesimportJSONResponsefromwebargs_starletteimportWebargsHTTPException@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)
注释
use_annotationsdecorator允许您解析请求对象 使用类型批注。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")@use_annotations(locations=("query",))asyncdefwelcome(request,name:str="Friend"):returnJSONResponse({"message":f"Welcome, {name}!"})# curl 'http://localhost:5000/'.# {"message":"Welcome, Friend!"}# curl 'http://localhost:5000/?name=Ada'.# {"message":"Welcome, Ada!"}
任何没有默认值的带注释参数都是必需的。 例如,如果在上面的示例中删除name的默认值, 如果未传递?name,则返回422错误响应。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargs_starletteimportuse_annotations,WebargsHTTPExceptionapp=Starlette()@app.route("/")@use_annotations(locations=("query",))asyncdefwelcome(request,name:str):returnJSONResponse({"message":f"Welcome, {name}!"})@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)# curl "http://localhost:5000/"# {"name":["Missing data for required field."]}
在需要时,参数也可以用Field实例进行注释 更多的控制。例如,您可能需要添加验证器。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromwebargsimportfieldsfrommarshmallowimportvalidatefromwebargs_starletteimportuse_annotations,WebargsHTTPExceptionapp=Starlette()@app.route("/")@use_annotations(locations=("query",))asyncdefwelcome(request,name:fields.Str(validate=validate.Length(min=2))):returnJSONResponse({"message":f"Welcome, {name}!"})@app.exception_handler(WebargsHTTPException)asyncdefhttp_exception(request,exc):returnJSONResponse(exc.messages,status_code=exc.status_code,headers=exc.headers)# curl "http://localhost:5000/?name=A"# {"name":["Shorter than minimum length 2."]}
HTTPEndpoint类也可以用use_annotations修饰。
fromstarlette.applicationsimportStarlettefromstarlette.responsesimportJSONResponsefromstarlette.endpointsimportHTTPEndpointfromwebargs_starletteimportuse_annotationsapp=Starlette()@app.route("/")@use_annotations(locations=("query",))classWelcomeEndpoint(HTTPEndpoint):asyncdefget(self,request,name:str="World"):returnJSONResponse({"message":f"Welcome, {name}!"})
见annotation_example.py 有关use_annotations用法的更完整示例。
更多
有关如何使用webargs的更多信息,请参见webargs documentation。
许可证
麻省理工学院许可。有关详细信息,请参见LICENSE文件。