该模块使用python 3类型提示来验证flask python api中的请求和响应数据,并生成api文档。
doctor的Python项目详细描述
此模块使用python类型验证 烧瓶python api。它使用python 3 type hints 验证请求参数并生成api文档。它还支持 普通字典的通用模式验证。生成的示例 API文档可以 是found in the docs。
安装
可以使用pip轻松安装医生:
$ pip install doctor
快速启动
定义一些将用于验证请求参数的类型。
# mytypes.pyfromdoctorimporttypes# doctor provides helper functions to easily define simple types.FooId=types.integer('The foo ID.')FetchBars=types.boolean('A flag that indicates if we should fetch bars')# You can also inherit from type classes to create more complex types.classFoo(types.Object):description='A Foo object'example={'foo_id':1}properties={'foo_id':FooId}required=['foo_id']additional_properties=False
定义端点将路由到的逻辑函数:
# foo.pyfrommytypesimportFoo,FooId,FetchBars# Note the type annotations on this function definition. This tells Doctor how# to parse and validate parameters for routes attached to this logic function.# The return type annotation will validate the response conforms to an# expected definition in development environments. In non-development# environments a warning will be logged.defget_foo(foo_id:FooId,fetch_bars:FetchBars=False)->Foo:"""Fetches the Foo object and optionally related bars."""returnFoo.get_by_id(foo_id,fetch_bars=fetch_bars)
现在用一个路由将端点绑定到逻辑函数:
fromflaskimportFlaskfromflask_restfulimportApifromdoctor.routingimportcreate_routes,get,Routefromfooimportget_fooroutes=(Route('/foo/<int:foo_id>/',methods=(get(get_foo),)),)app=Flask(__name__)api=Api(app)forroute,resourceincreate_routes(routes):api.add_resource(resource,route)
就这样,您现在有了一个能够正常工作的api端点,您可以卷曲它,并且根据 架构。逻辑函数中的位置参数被认为是必需的请求参数,关键字参数被认为是必需的 可选。另外,使用autoflasksphinx指令,您还将获得 自动生成的API文档。
文档
文档和完整示例可在readthedocs获得。
运行测试
可以使用tox运行测试。它将处理将依赖项安装到 virtualenv、运行测试和重建文档。
然后运行tox:
cd doctor
tox
您可以直接向pytest传递参数:
tox -- test/test_flask.py