API元数据和架构工具,用于生成测试和文档
项目描述
Acceptable是python工具,用于注解和捕获围绕您的python网络API的元数据。这些元数据可用于验证、文档、测试和代码的linting。
它作为独立工具使用,或可以集成到Flask(对Django的beta支持)网络应用中,以实现更丰富的集成。
设计目标
紧密耦合代码、元数据和文档,以减少偏差并增加DRY。
JSON输入和输出的验证
为开发人员提供工具,以安全地更改API
使生成API文档变得容易。
从API元数据生成测试双工工具。
使用方法
以下是一个flask示例
from acceptable import AcceptableService service = AcceptableService('example') foo_api = service.api('foo', '/foo', introduced_at=1, methods=['POST']) foo_api.request_schema = <JSON Schema...> foo_api.response_schema = <JSON Schema...> foo_api.changelog(3, 'Changed other thing') foo_api.changelog(2, 'Changed something') @foo_api def view(): ...
您可以使用此元数据将URL绑定到flask应用
from acceptable import get_metadata() app = Flask(__name__) get_metadata().bind_all(app)
现在可以生成API元数据如下
acceptable metadata your.import.path > api.json
现在可以使用此元数据生成文档,并提供API linting。
Django
注意:目前Django的支持非常有限,主要针对文档。
标记API本身有一些不同
from acceptable import AcceptableService service = AcceptableService('example') # url is looked up from name, like reverse() foo_api = service.django_api('app:foo', introduced_at=1) foo_api.django_form = SomeForm foo_api.changelog(3, 'Changed other thing) foo_api.changelog(2, 'Changed something') @foo_api.handler class MyHandler(BaseHandler): allowed_methods=['POST'] ...
可接受将生成表的单个JSON模式表示,用于文档。
要生成API元数据,您应该在INSTALLED_APPS中添加‘可接受’。这将提供一个‘可接受’管理命令
./manage.py acceptable metadata > api.json # generate metadata
还有
./manage.py acceptable api-version api.json # inspect the current version
文档(测试版)
可接受的一个目标是通过您的API的元数据来构建文档。
一旦您有了上述格式的JSON格式的元数据,就可以将其转换为markdown文档
acceptable render api.json --name 'My Service'
您可以通过一个步骤完成此操作
acceptable metadata path/to/files*.py | acceptable render --name 'My Service'
此markdown设计为通过文档构建器 <https://docs.ubuntu.com/documentation-builder/en/>渲染为html
documentation-builder --base-directory docs
可包含的Makefile
如果您正在使用make文件来自动化构建,您可能会发现这很有用。
可接受软件包包含一个可包含的make文件片段,可以提供以下目标
api-lint - 检查向后兼容性和版本号;
api-update-metadata - 类似于api-lint,然后更新保存的元数据;
api-version - 打印保存的元数据和当前API版本;
api-docs-markdown - 生成markdown文档。
make文件有以下变量,您可以在需要时覆盖它们
ACCEPTABLE_ENV - 已安装可接受的虚拟环境,默认为$(ENV)。
ACCEPTABLE_METADATA - 保存的元数据文件名,默认为api.json;
ACCEPTABLE_DOCS - api-docs-markdown将在其中生成文档的目录,默认为docs。
您将需要手动使用acceptable metadata命令创建保存的元数据,并将其保存到ACCEPTABLE_METADATA的值中。
make文件假设以下变量
ACCEPTABLE_MODULES 是包含可接受注释服务的模块的空格分隔列表;
ACCEPTABLE_SERVICE_TITLE 是由api-docs-markdown使用的服务的标题。
ACCEPTABLE_SERVICE_TITLE 应该不带引号,例如。
ACCEPTABLE_SERVICE_TITLE := Title of the Service
要包含该文件,您需要获取其路径,如果上述变量和条件存在,您可以将此放在您的make文件中
include $(shell $(ENV)/bin/python -c 'import pkg_resources; print(pkg_resources.resource_filename("acceptable", "make/Makefile.acceptable"))' 2> /dev/null)
开发
make test和make tox应该无错误运行。
要运行单个测试模块,请调用
python setup.py test --test-suite acceptable.tests.test_module
或
tox -epy38 -- --test-suite acceptable.tests.test_module
……后者仅在Python 3.8上运行“test_module”。