Django-REST框架的openapi3模式生成
drf-spectacular的Python项目详细描述
为Django REST framework生成合理而灵活的OpenAPI 3.0模式。在
- 这个项目有3个目标:
- 从DRF中提取尽可能多的模式信息。在
- 提供灵活性,使模式在现实世界中可用(不仅仅是玩具示例)。在
- 生成一个与最流行的客户机生成器协同工作的模式。在
代码是经过大量修改的 DRF OpenAPI generator, 缺少以下列出的所有功能。在
- 功能
- 作为组件建模的序列化程序。(支持任意嵌套和递归)
- @extend_schema装饰器,用于定制apiew、视图集、基于函数的视图和@action
- 附加参数
- 请求/响应序列化程序重写(带状态代码)
- 使用PolymorphicProxySerializerhelper或通过rest_polymorphic的多态序列化程序手动进行多态响应)
- …和更多自定义选项
- 身份验证支持(包括DRF本机,易于扩展)
- 自定义序列化程序类支持(易于扩展)
- MethodSerializerField()type通过类型暗示或@extend_schema_fieldtype
- i18n支持
- 标记提取
- 从docstrings
- 理智的回退
- Saneoperation_id命名(基于路径)
- 使用SpectacularAPIView服务的架构(还提供Redoc和Swagger UI视图)
- 可选的输入/输出序列化程序组件拆分
- 支持:
- django-polymorphic/django-rest-polymorphic
- SimpleJWT
- DjangoOAuthToolkit
- djangorestframework-jwt(测试叉drf-jwt)
- dj-rest-auth(维护django-rest-auth的分叉)
- djangorestframework-camel-case(通过后处理钩子camelize_serializer_fields)
- django-filter(开箱即用的基本支持;使用SpectacularDjangoFilterBackendMixin或drf specialty的DjangoFilterBackend)改进类型
有关详细信息,请访问documentation。在
许可证
由T. Franzel,Cashlink Technologies GmbH.Licensed under 3-Clause BSD提供。在
要求
- Python>;=3.6
- Django(2.2,3.0,3.1)
- Django REST框架(3.10,3.11)
安装
使用pip安装
$ pip install drf-spectacular
然后在settings.py
^{pr2}$最后在我们的DRF注册
REST_FRAMEWORK={# YOUR SETTINGS'DEFAULT_SCHEMA_CLASS':'drf_spectacular.openapi.AutoSchema',}
发布管理
drf specific故意保持低于版本1.x.x,以表示 新版本可能会让你崩溃。对于生产,我们强烈建议 更新时版本和检查架构差异。在
话虽如此,我们的目标是极其防御性的w.r.t.打破API更改。然而, 我们也承认,即使是轻微的模式更改也可能会破坏您的工具链, 因为任何现有的bug都可能被用作一个特性。在
我们用以下语义定义版本增量。y-stream增量可以包含 可能会破坏API和架构的更改。z-stream增量永远不会中断 API,并且可能只包含架构更改,这些更改不太可能破坏您。在
转一圈吧
使用CLI生成架构:
$ ./manage.py spectacular --file schema.yml $ docker run -p 80:8080 -e SWAGGER_JSON=/schema.yml -v ${PWD}/schema.yml:/schema.yml swaggerapi/swagger-ui
如果还想验证架构,请添加–validate标志。或者直接为你的模式服务 从你的API。我们还为swagger ui或redoc提供方便的包装。在
fromdrf_spectacular.viewsimportSpectacularAPIView,SpectacularRedocView,SpectacularSwaggerViewurlpatterns=[# YOUR PATTERNSpath('api/schema/',SpectacularAPIView.as_view(),name='schema'),# Optional UI:path('api/schema/swagger-ui/',SpectacularSwaggerView.as_view(url_name='schema'),name='swagger-ui'),path('api/schema/redoc/',SpectacularRedocView.as_view(url_name='schema'),name='redoc'),]
使用
drf specific开箱即用效果非常好。您可能还需要为API设置一些元数据。 只需在您的settings.py中创建一个SPECTACULAR_SETTINGS字典并覆盖默认值。 看看available settings。在
玩具的例子不包括你的箱子吗?没问题,你可以大量定制我们的模式将被呈现。在
使用@extend_schema
大多数定制案例应该由extend_schemadecorator覆盖。我们通常 在指定OpenApiParameter和拆分请求/响应序列化程序方面,已经很快了,但是 天涯海角。在
fromdrf_spectacular.utilsimportextend_schema,OpenApiParameterfromdrf_spectacular.typesimportOpenApiTypesclassAlbumViewset(viewset.ModelViewset)serializer_class=AlbumSerializer@extend_schema(request=AlbumCreationSerializerresponses={201:AlbumSerializer},)defcreate(self,request):# your non-standard behaviourreturnsuper().create(request)@extend_schema(# extra parameters added to the schemaparameters=[OpenApiParameter(name='artist',description='Filter by artist',required=False,type=str),OpenApiParameter(name='release',type=OpenApiTypes.DATE,location=OpenApiParameter.QUERY,description='Filter by release date',),],# override default docstring extractiondescription='More descriptive text',# provide Authentication class that deviates from the views defaultauth=None,# change the auto-generated operation nameoperation_id=None,# or even completely override what AutoSchema would generate. Provide raw Open API spec as Dict.operation=None,)deflist(self,request):# your non-standard behaviourreturnsuper().list(request)@extend_schema(request=AlbumLikeSerializerresponses={204:None},)@action(detail=True,methods=['post'])defset_password(self,request,pk=None):# your action behaviour
更多定制
还是不满意?你想要更多!我们还是会掩护你的。 有关详细信息,请访问customization。在
测试
安装测试要求。在
$ pip install -r requirements.txt
用runtests运行。在
$ ./runtests.py
您还可以使用优秀的tox测试工具来运行测试 针对所有支持的Python和Django版本。安装tox 全局,然后简单地运行:
$ tox
- 项目
标签: