Package: drf-yasg-edge
NOTE: this is a modified version based on  drf-yasg for myself usage!New Features新增:增加TYPE_ENUM用来自定义增加 x-enum 类型,后面将支持 Django 3 的 TextChoices新增:增加ENABLE_SPEC_VALIDATOR选项,默认禁用 spec validation. 因为自定义的 x-enum 通不过变更:默认允许输出Unicode 字面量优化:源代码增加类型声明GeneraterealSwagger/OpenAPI 2.0 specifications from a Django Rest Framework API.Compatible withDjango Rest Framework: 3.10Django:  2.2Python:  3.7, 3.8Only the latest patch version of eachmajor.minorseries of Python, Django and Django REST Framework is supported.Only the latest version of drf-yasg is supported.Support of old versions is dropped immediately with the release
of a new version. Please do not create issues before upgrading to the latest release available at the time. Regression
reports are accepted and will be resolved with a new release as quickly as possible. Removed features will usually go
through a deprecation cycle of a few minor releases.Resources:Source:https://github.com/banxi1988/drf-yasg/Documentation:https://drf-yasg.readthedocs.io/Changelog:https://drf-yasg.readthedocs.io/en/stable/changelog.htmlLive demo:https://drf-yasg-demo.herokuapp.com/Featuresfull support for nested Serializers and Schemasresponse schemas and descriptionsmodel definitions compatible with codegen toolscustomization hooks at all points in the spec generation processJSON and YAML format for specbundles latest version ofswagger-uiandredocfor viewing the generated documentationschema view is cacheable out of the boxgenerated Swagger schema can be automatically validated byswagger-spec-validatorsupports Django REST Framework API versioning withURLPathVersioningandNamespaceVersioning; other DRF
or custom versioning schemes are not currently supportedFully nested request and response schemas.Choose between redoc and swagger-ui.Real Model definitions.Table of contentsContentsNew FeaturesFeaturesTable of contentsUsage0. Installation1. Quickstart2. Configurationa.get_schema_viewparametersb.SchemaViewoptionsc.SWAGGER_SETTINGSandREDOC_SETTINGS3. Caching4. Validationswagger-uivalidation badgeOnlineOfflineUsingswagger-cliManually on editor.swagger.io5. Code generation6. Example projectThird-party integrationsdjangorestframework-camel-casedjangorestframework-recursiveUsage0. InstallationThe preferred instalation method is directly from pypi:pip install -U drf-yasg-edgeAdditionally, if you want to use the built-in validation mechanisms (see4. Validation), you need to install
some extra requirements:pip install -U drf-yasg-edge[validation]1. QuickstartInsettings.py:INSTALLED_APPS=[...'drf_yasg',...]Inurls.py:...fromrest_frameworkimportpermissionsfromdrf_yasg.viewsimportget_schema_viewfromdrf_yasgimportopenapi...schema_view=get_schema_view(openapi.Info(title="Snippets API",default_version='v1',description="Test description",terms_of_service="https://www.google.com/policies/terms/",contact=openapi.Contact(email="contact@snippets.local"),license=openapi.License(name="BSD License"),),public=True,permission_classes=(permissions.AllowAny,),)urlpatterns=[url(r'^swagger(?P<format>\.json|\.yaml)$',schema_view.without_ui(cache_timeout=0),name='schema-json'),url(r'^swagger/$',schema_view.with_ui('swagger',cache_timeout=0),name='schema-swagger-ui'),url(r'^redoc/$',schema_view.with_ui('redoc',cache_timeout=0),name='schema-redoc'),...]This exposes 4 endpoints:A JSON view of your API specification at/swagger.jsonA YAML view of your API specification at/swagger.yamlA swagger-ui view of your API specification at/swagger/A ReDoc view of your API specification at/redoc/2. Configurationa.get_schema_viewparametersinfo- Swagger API Info object; if omitted, defaults toDEFAULT_INFOurl- API base url; if left blank will be deduced from the location the view is served atpatterns- passed to SchemaGeneratorurlconf- passed to SchemaGeneratorpublic- if False, includes only endpoints the current user has access tovalidators- a list of validator names to apply on the generated schema; onlyssvis currently supportedgenerator_class- schema generator class to use; should be a subclass ofOpenAPISchemaGeneratorauthentication_classes- authentication classes for the schema view itselfpermission_classes- permission classes for the schema view itselfb.SchemaViewoptionsSchemaView.with_ui(renderer,cache_timeout,cache_kwargs)- get a view instance using the
specified UI renderer; one ofswagger,redocSchemaView.without_ui(cache_timeout,cache_kwargs)- get a view instance with no UI renderer;
same asas_cached_viewwith no kwargsSchemaView.as_cached_view(cache_timeout,cache_kwargs,**initkwargs)- same asas_view,
but with optional cachingyou can, of course, callas_viewas usualAll of the first 3 methods take two optional arguments,cache_timeoutandcache_kwargs; if present,
these are passed on to Django’scached_pagedecorator in order to enable caching on the resulting view.
See3. Caching.c.SWAGGER_SETTINGSandREDOC_SETTINGSAdditionally, you can include some more settings in yoursettings.pyfile.
Seehttps://drf-yasg.readthedocs.io/en/stable/settings.htmlfor details.3. CachingSince the schema does not usually change during the lifetime of the django process, there is out of the box support for
caching the schema view in-memory, with some sane defaults:caching is enabled by thecache_pagedecorator, using the default Django cache backend, can be changed using thecache_kwargsargumentHTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemasthe cached schema varies on theCookieandAuthorizationHTTP headers to enable filtering of visible endpoints
according to the authentication credentials of each user; note that this means that every user accessing the schema
will have a separate schema cached in memory.4. ValidationGiven the numerous methods to manually customize the generated schema, it makes sense to validate the result to ensure
it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger
libraries, and can be activated by passingvalidators=['ssv']toget_schema_view; if the generated
schema is not valid, aSwaggerValidationErroris raised by the handling codec.Warning:This internal validation can slow down your server.
Caching can mitigate the speed impact of validation.The provided validation will catch syntactic errors, but more subtle violations of the spec might slip by them. To
ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:swagger-uivalidation badgeOnlineIf your schema is publicly accessible,swagger-uiwill automatically validate it against the official swagger
online validator and display the result in the bottom-right validation badge.OfflineIf your schema is not accessible from the internet, you can run a local copy ofswagger-validatorand set theVALIDATOR_URLaccordingly:SWAGGER_SETTINGS={...'VALIDATOR_URL':'http://localhost:8189',...}$dockerrun--nameswagger-validator-d-p8189:8080--add-hosttest.local:10.0.75.1swaggerapi/swagger-validator84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2$curlhttp://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi{}Usingswagger-clihttps://www.npmjs.com/package/swagger-cli$npminstall-gswagger-cli[...]$swagger-clivalidatehttp://test.local:8002/swagger.yamlhttp://test.local:8002/swagger.yaml is validManually oneditor.swagger.ioImporting the generated spec intohttps://editor.swagger.io/will automatically trigger validation on it.
This method is currently the only way to get both syntactic and semantic validation on your specification.
The other validators only provide JSON schema-level validation, but miss things like duplicate operation names,
improper content types, etc5. Code generationYou can use the specification outputted by this library together withswagger-codegento generate client code in your language of choice:$dockerrun--rm-v${PWD}:/localswaggerapi/swagger-codegen-cligenerate-i/local/tests/reference.yaml-ljavascript-o/local/.codegen/jsSee the github page linked above for more details.6. Example projectFor additional usage examples, you can take a look at the test project in thetestprojdirectory:$gitclonehttps://github.com/banxi1988/drf-yasg.git$cddrf-yasg$virtualenvvenv$sourcevenv/bin/activate(venv)$cdtestproj(venv)$python-mpipinstall-Upipsetuptools(venv)$pipinstall-U-rrequirements.txt(venv)$pythonmanage.pymigrate(venv)$pythonmanage.pyrunserver(venv)$firefoxlocalhost:8000/swagger/Third-party integrationsdjangorestframework-camel-caseIntegration withdjangorestframework-camel-caseis
provided out of the box - if you havedjangorestframework-camel-caseinstalled and yourAPIViewusesCamelCaseJSONParserorCamelCaseJSONRenderer, all property names will be converted tocamelCaseby default.djangorestframework-recursiveIntegration withdjangorestframework-recursiveis
provided out of the box - if you havedjangorestframework-recursiveinstalled.