webargs sanic提供webargs与sanic应用程序的集成
webargs-sanic的Python项目详细描述
webargs sanic
Sanic与Webargs集成。解析和验证请求参数:头、参数、cookies、文件、json等。
webargs是一个用于解析和验证http请求参数的python库,内置了对流行web框架的支持。webargs sanic允许您将其用于Sanic应用程序。要了解有关webargs使用的更多信息,请检查Quickstart
示例代码
简单应用
fromsanicimportSanicfromsanic.responseimporttextfromwebargsimportfieldsfromwebargs_sanic.sanicparserimportuse_argsapp=Sanic(__name__)hello_args={'name':fields.Str(required=True)}@app.route('/')@use_args(hello_args)asyncdefindex(args):returntext('Hello '+args['name'])
基于类的sanic应用程序和args/kwargs
fromsanicimportSanicfromsanic.viewsimportHTTPMethodViewfromsanic.responseimportjsonfromwebargsimportfieldsfromwebargs_sanic.sanicparserimportuse_args,use_kwargsapp=Sanic(__name__)classEchoMethodViewUseArgs(HTTPMethodView):@use_args({"val":fields.Int()})asyncdefpost(self,request,args):returnjson(args)app.add_route(EchoMethodViewUseArgs.as_view(),"/echo_method_view_use_args")classEchoMethodViewUseKwargs(HTTPMethodView):@use_kwargs({"val":fields.Int()})asyncdefpost(self,request,val):returnjson({"val":val})app.add_route(EchoMethodViewUseKwargs.as_view(),"/echo_method_view_use_kwargs")
不带decorator的解析器,返回错误为json
fromsanicimportSanicfromsanic.responseimportjsonfromwebargsimportfieldsfromwebargs_sanic.sanicparserimportparser,HandleValidationErrorapp=Sanic(__name__)@app.route("/echo_view_args_validated/<value>",methods=["GET"])asyncdefecho_use_args_validated(request,args):parsed=awaitparser.parse({"value":fields.Int(required=True,validate=lambdaargs:args["value"]>42)},request,locations=("view_args",))returnjson(parsed)# Return validation errors as JSON@app.exception(HandleValidationError)asyncdefhandle_validation_error(request,err):returnjson({"errors":err.exc.messages},status=422)
更复杂的自定义示例
fromsanicimportSanicfromsanicimportresponsefromsanicimportBlueprintfromwebargs_sanic.sanicparserimportuse_kwargsfromsome_CUSTOM_storageimportInMemoryfromwebargsimportfieldsfromwebargsimportvalidateimportmarshmallow.fieldsfromvalidate_emailimportvalidate_email#usually this should not be here, better to import ;)#please check examples for more infoclassEmail(marshmallow.fields.Field):def__init__(self,*args,**kwargs):super(Email,self).__init__(*args,**kwargs)def_deserialize(self,value,attr,obj):value=value.strip().lower()ifnotvalidate_email(value):self.fail('validator_failed')returnvalueuser_update={'user_data':fields.Nested({'email':Email(),'password':fields.Str(validate=lambdavalue:len(value)>=8),'first_name':fields.Str(validate=lambdavalue:len(value)>=1),'last_name':fields.Str(validate=lambdavalue:len(value)>=1),'middle_name':fields.Str(),'gender':fields.Str(validate=validate.OneOf(["M","F"])),'birth_date':fields.Date(),}),'user_id':fields.Str(required=True,validate=lambdax:len(x)==32),}blueprint=Blueprint('app')storage=InMemory()@blueprint.put('/user/')@use_kwargs(user_update)asyncdefupdate_user(request,user_id,user_data):storage.update_or_404(user_id,user_data)returnresponse.text('',status=204)app=Sanic(__name__)app.blueprint(blueprint,url_prefix='/')
有关更多示例和检查如何使用自定义验证(电话、电子邮件等),请检查Examples中的应用程序
安装
从pip
pip install webargs-sanic
或来源
git clone git@github.com:EndurantDevs/webtest-sanic.git
cd webtest-sanic
python setup.py install
运行测试
项目使用来自webargs包的公共测试。感谢Steven Loria对sharing tests in webargs v4.1.0的支持。 大多数测试由webtest通过webtest-sanic运行。 一些自己的测试通过sanic的testclient运行。
要确保从源代码安装之前一切正常,请运行:
pip -r requirements.txt
然后
python setup.py test
或
pytest tests/
作者
许可证
这个项目是根据麻省理工学院的许可证授权的-请参见LICENSE文件了解详细信息