[英]Django rest framework Api documentation Swagger 2.0
我在配置Swagger UI時遇到了困難。 這是非常說明性的文檔: https : //django-rest-swagger.readthedocs.io/en/latest/
不建議使用YAML文檔字符串。 有人知道如何從python代碼中配置Swagger UI(查詢參數等)嗎?
如果由於某種奇怪的原因不可能。 有什么可行的替代方法,還是最好手動編寫api文檔?
好,找到了。 這不是理想的解決方案-但前端(Web和移動)開發人員需要此解決方案-並且它可以完成工作。
基本上, rest_framework.schemas import SchemaGenerator
最新的DRF和Swagger使用rest_framework.schemas import SchemaGenerator
為Swagger提供文檔。
所以我幾乎不需要擴展它:
# -*- coding: utf-8 -*-
import urlparse
import coreapi
from rest_framework.schemas import SchemaGenerator
class ParamsSchemaGenerator(SchemaGenerator):
def get_link(self, path, method, callback, view):
"""
Return a `coreapi.Link` instance for the given endpoint.
"""
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
fields += self.get_pagination_fields(path, method, callback, view)
fields += self.get_filter_fields(path, method, callback, view)
fields += self.get_docs_fields(path, method, callback, view) # this is the extended line;
if fields and any([field.location in ('form', 'body') for field in fields]):
encoding = self.get_encoding(path, method, callback, view)
else:
encoding = None
if self.url and path.startswith('/'):
path = path[1:]
return coreapi.Link(
url=urlparse.urljoin(self.url, path),
action=method.lower(),
encoding=encoding,
fields=fields
)
# and this is fully custom additional docs method;
def get_docs_fields(self, path, method, callback, view):
fields = []
if hasattr(view, 'docs_fields'):
for field in view.docs_fields:
field = coreapi.Field(
name=field.get('name'),
location=field.get('query'),
required=field.get('required'),
type=field.get('type'),
description=field.get('description')
)
fields.append(field)
return fields
然后,我需要定義一個函數,該函數將使用上面定義的生成器返回架構:
# -*- coding: utf-8 -*-
# monkey patching FTW!
from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_swagger import renderers
from kolomnie.core.schema.generator import ParamsSchemaGenerator
def get_params_swagger_view(title=None, url=None):
"""
Returns schema view which renders Swagger/OpenAPI.
(Replace with DRF get_schema_view shortcut in 3.5)
"""
class SwaggerSchemaView(APIView):
_ignore_model_permissions = True
exclude_from_schema = True
permission_classes = [AllowAny]
renderer_classes = [
CoreJSONRenderer,
renderers.OpenAPIRenderer,
renderers.SwaggerUIRenderer
]
def get(self, request):
generator = ParamsSchemaGenerator(title=title, url=url)
schema = generator.get_schema(request=request)
if not schema:
raise exceptions.ValidationError(
'The schema generator did not return a schema Document'
)
return Response(schema)
return SwaggerSchemaView.as_view()
這就是我將其放在網址中的方式:
if settings.DEBUG:
api_views = get_params_swagger_view(title='Some API')
現在,更神奇的是,我為存儲文檔字段的視圖定義了一個混合:
# -*- coding: utf-8 -*-
class DocsMixin(object):
"""
This mixin can be used to document the query parameters in GET
if there's no other way to do it. Please refer to the: ParamsSchemaGenerator.get_links
for more information;
"""
docs_fields = []
這就是我的用法:
class BaseSearchResultsView(generics.GenericAPIView, SearchDocs):
....
其中SearchDocs是:
class SearchDocs(DocsMixin):
"""
Documents the get query in search;
"""
docs_fields = [
{
'name': 'q',
'location': 'query',
'required': False,
'type': 'string',
'description': 'The base query for the search;',
},
...
只是發現我不需要mixin :)只需在視圖上定義docs_fields即可。
可能這不能滿足您的所有需求-但認為這是一個不錯的開始:)
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.