使用flask和apispec构建和记录restapi

flask-apispec-rovanion的Python项目详细描述


Latest versionDocumentation statusTravis-CICode coverage

flask apispec是在flask中构建restapi的轻量级工具。flask apispec使用webargs进行请求解析,使用marshmallow进行响应格式化,使用apispec自动生成扩展标记。您可以将flask apispec与香草烧瓶或功能更丰富的框架(如Flask-RESTful)一起使用。

安装

pip install flask-apispec

快速启动

fromflaskimportFlaskfromflask_apispecimportuse_kwargs,marshal_withfrommarshmallowimportfields,Schemafrom.modelsimportPetapp=Flask(__name__)classPetSchema(Schema):classMeta:fields=('name','category','size')@app.route('/pets')@use_kwargs({'category':fields.Str(),'size':fields.Str()})@marshal_with(PetSchema(many=True))defget_pets(**kwargs):returnPet.query.filter_by(**kwargs)

flask apispec可用于基于函数和类的视图:

fromflaskimportmake_responsefromflask_apispec.viewsimportMethodResourceclassPetResource(MethodResource):@marshal_with(PetSchema)defget(self,pet_id):returnPet.query.filter(Pet.id==pet_id).one()@use_kwargs(PetSchema)@marshal_with(PetSchema,code=201)defpost(self,**kwargs):returnPet(**kwargs)@use_kwargs(PetSchema)@marshal_with(PetSchema)defput(self,pet_id,**kwargs):pet=Pet.query.filter(Pet.id==pet_id).one()pet.__dict__.update(**kwargs)returnpet@marshal_with(None,code=204)defdelete(self,pet_id):pet=Pet.query.filter(Pet.id==pet_id).one()pet.delete()returnmake_response('',204)

flask apispec为视图函数和类生成夸张的标记。默认情况下,swagger json服务于/swagger/,swagger ui服务于/swagger ui/

fromapispecimportAPISpecfromflask_apispec.extensionimportFlaskApiSpecapp.config.update({'APISPEC_SPEC':APISpec(title='pets',version='v1',plugins=['apispec.ext.marshmallow'],),'APISPEC_SWAGGER_URL':'/swagger/',})docs=FlaskApiSpec(app)docs.register(get_pets)docs.register(PetResource)

注释

<^ {STR 1 } $烧瓶ApPEPEC<强>受到{{8}和Flask-RESTplus的强烈启发,但试图提供类似的功能,具有更大的灵活性和更少的代码。

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

推荐PyPI第三方库


热门话题
java通过两个整数数组对正整数和负整数进行排序   java无参数和默认构造函数混淆   java加载文件MD5的最快方法是什么?   java如何在变量声明中使用带“e”的float   java将项目导入到STS iMac   java在使用图像时旋转图像   java Break语句不起作用   java提供了错误类型Spring的id   java如何为多个变量设置相同的函数属性?   JavaMaven:如何添加编译阶段后生成的资源   java HashMap已损坏/性能问题   java Hibernate SQL中间表b/w父表和子表(不同类型)   java PDFbox找不到字体:/Helv   Java:向自实现的双链接列表添加排序函数   为使用Java BouncyCastle生成的X509Certificate提供密钥使用的安全性   java Hibernate在读写方面的性能   C#相当于Java的DataOutputStream?