Package: webargs-sanic
webargs-sanicSanicintegration withWebargs.Parsing and validating request arguments: headers, arguments, cookies, files, json, etc.IMPORTANT: From version 2.0.0 webargs-sanic requires you to have webargs >=7.0.1. Please be aware of changes happened in version of webargs > 6.0.0. If you need support of webargs 5.x with no location definition, please use previous version(1.5.0) of this module from pypi.webargsis a Python library for parsing and validating HTTP request arguments, with built-in support for popular web frameworks. webargs-sanic allows you to use it forSanicapps. To read more about webargs usage, please checkQuickstartExample CodeSimple ApplicationfromsanicimportSanicfromsanic.responseimporttextfromwebargsimportfieldsfromwebargs_sanic.sanicparserimportuse_argsapp=Sanic(__name__)hello_args={'name':fields.Str(required=True)}@app.route('/')@use_args(hello_args,location="query")asyncdefindex(request,args):returntext('Hello '+args['name'])Class-based Sanic app and args/kwargsfromsanicimportSanicfromsanic.viewsimportHTTPMethodViewfromsanic.responseimportjsonfromwebargsimportfieldsfromwebargs_sanic.sanicparserimportuse_args,use_kwargsapp=Sanic(__name__)classEchoMethodViewUseArgs(HTTPMethodView):@use_args({"val":fields.Int()},location="form")asyncdefpost(self,request,args):returnjson(args)app.add_route(EchoMethodViewUseArgs.as_view(),"/echo_method_view_use_args")classEchoMethodViewUseKwargs(HTTPMethodView):@use_kwargs({"val":fields.Int()},location="query")asyncdefpost(self,request,val):returnjson({"val":val})app.add_route(EchoMethodViewUseKwargs.as_view(),"/echo_method_view_use_kwargs")Parser without decorator with returning errors as JSONfromsanicimportSanicfromsanic.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,location="view_args")returnjson(parsed)# Return validation errors as JSON@app.exception(HandleValidationError)asyncdefhandle_validation_error(request,err):returnjson({"errors":err.exc.messages},status=422)More complicated custom examplefromsanicimportSanicfromsanicimportresponsefromsanicimportBlueprintfromwebargs_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,location="json_or_form")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='/')For more examples and checking how to use custom validations (phones, emails, etc.) please check apps inExamplesInstallingIt is easy to do frompippip install webargs-sanicor from sourcesgit clone git@github.com:EndurantDevs/webtest-sanic.git
cd webtest-sanic
python setup.py installRunning the testsProject uses common tests from webargs package. Thanks toSteven Loriaforsharing tests in webargs v4.1.0.
Most of tests are run by webtest viawebtest-sanic.
Some own tests get run via Sanic's TestClient.To be sure everything is fine before installation from sources, just run:pip-rrequirements.txtand thenpythonsetup.pytestOrpytesttests/AuthorsLicenseThis project is licensed under the MIT License - see theLICENSEfile for details