webargs sanic提供webargs与sanic应用程序的集成

webargs-sanic的Python项目详细描述


webargs sanic

SanicWebargs集成。解析和验证请求参数:头、参数、cookies、文件、json等。

Build StatusLatest VersionPython VersionsTests Coverage

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 Loriasharing tests in webargs v4.1.0的支持。 大多数测试由webtest通过webtest-sanic运行。 一些自己的测试通过sanic的testclient运行。

要确保从源代码安装之前一切正常,请运行:

pip -r requirements.txt

然后

python setup.py test

pytest tests/

作者

Endurant Developers Python Team

许可证

这个项目是根据麻省理工学院的许可证授权的-请参见LICENSE文件了解详细信息

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
安卓软件包与java代码中的类型冲突   谷歌应用引擎Java还是Python?   如何将java bean传递到jsp页面,以便jqQrid使用json显示?   在编译kotlin代码时,kotlin编译器如何处理java代码?   java不准确地更改JTextPane中的文本颜色   反应式编程AWS SDK v2 SdkAsyncHttpClient使用Java 11 Java实现。网http HttpClient sendAsync   在Spring AMQP中,java根据队列的消费者计数来消费队列   java在ArrayList的add()方法中创建新对象会导致内存泄漏。我能做什么不同的事?   未将java BufferedReader特定行追加到字符串   用于聊天程序格式化的java JavaFX 2文本区   java如何从netbeans项目生成exexutable文件?   swing如何在Java中使用JButton操作调整JWindow的宽度和高度?   java有没有办法在spring boot中使用jasypt aes加密和解密?   java通过使用泛型如何将映射作为集合传递给方法?   java如何替换不推荐使用的构造函数DynamoDBMapperFieldModel