Mic*_*oux 5 python django django-rest-framework swagger-ui
在 DRF 中使用架构装饰器来管理我会伤透脑筋并浪费/浪费大量时间。
我关注https://www.django-rest-framework.org/topics/documenting-your-api/并在 sagger-ui 和 redoc-ui 上管理它。但 GET 方法查询参数或 POST 正文 json 字符串有效负载未记录。
所以我试图处理 AutoSchema、ManualSchema 和 Custom 类来生成 api 文档。 https://www.django-rest-framework.org/api-guide/views/#view-schema-decorator
但我从来没有做任何好事。是的,我也在 stackoverflow 上查看 [django-rest-framework] 标签,是的,我在 DRF google 社区上进行了讨论(但还没有答案)。
所以我尝试过。
尝试处理:
import coreapi
import coreschema
from rest_framework.schemas import AutoSchema, ManualSchema
log_file_delete_schema = AutoSchema(
manual_fields=[
coreapi.Field(
"file_path",
required=True,
location="query",
type="string",
description="path of the log to be delete",
)
]
)
Run Code Online (Sandbox Code Playgroud)
但它返回“AutoShema as no get_operation”错误
接下来尝试:
import coreapi
import coreschema
from rest_framework.schemas import AutoSchema, ManualSchema
class CustomLogFileDeleteSchema(AutoSchema):
def __init__(self):
super(CustomLogFileDeleteSchema, self).__init__
def get_manual_fields(self, path, method):
extra_fields = [
coreapi.Field(
"file_path",
required=True,
location="query",
description="log file path",
type="string",
example="/path/to/file/logfile.log",
)
]
manual_fields = super().get_manual_fields(path, method)
return manual_fields + extra_fields
Run Code Online (Sandbox Code Playgroud)
它返回给我“CustomLogFileDeleteSchema”对象没有属性“instance_schemas”
我尝试使用 Django Rest Swagger 但它现在是无人维护的项目所以 ==> 接下来
我对非 ORM api 端点使用基于函数的视图,如下所示:
@api_view(["GET", "POST"])
# @schema(log_file_delete_schema)
#@schema(CustomLogFileDeleteSchema())
@permission_classes((permissions.AllowAny,))
def log_file_delete(request):
"""
@brief
Delete the current log file from the device
@param file_path => this is the log file path to delete
POST and GET requests only
e.g. uri looks like <root>/logs/delete/?file_path=/var/log/gpk/core.log
"""
api_logger.info("access to delete log view")
method = request.method
if "GET" == method:
_arg_file_path = request.GET.get("file_path", None)
if "POST" == method:
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
_arg_file_path = body["file_path"]
if None is _arg_file_path or not _arg_file_path:
return JsonResponse({"error": "file_path arg is missing or empty"}, status=400)
try:
os.remove(Path(_arg_file_path))
open(_arg_file_path, "w") # need recreate empty file after delete
r = {"code": 202, "status_message": "job done! file deleted"}
except Exception as e:
r = {
"code": 400,
"status_message": "Ooops! there is an error when try to delete logs file %s, {}".format(
e
)
% _arg_file_path,
}
return JsonResponse(r, status=r["code"])
Run Code Online (Sandbox Code Playgroud)
View Schema Decorator 示例对我来说太轻了,我不明白我可以使用基于 AutoSchema 的 CustomClass 做什么。
请提供一个比 OpenAPI 格式的 GET 查询和 POST 正文有效负载文档中更好的示例,以通过 swagger-ui 对其进行管理。

我刚刚在 github 上打开了一个问题
经过几个小时的时间在 github、stackoverflow、google、许多开发博客和论坛上我找到了解决方案!
感谢这篇文章,我按照 yaml 文档动态地构建 OpenAPI。 https://www.igeorgiev.eu/python/misc/python-django-rest-framework-openapi-documentation/
所以对于我的情况,编写 yaml 格式的文档字符串
# declare a subclass of
from rest_framework.schemas.openapi import AutoSchema
# not a subclass of
# from rest_framework.schemas import AutoSchema
# don't forget to import yaml from pyyaml package
import yaml
class AutoDocstringSchema(AutoSchema):
@property
def documentation(self):
if not hasattr(self, "_documentation"):
try:
self._documentation = yaml.safe_load(self.view.__doc__)
except yaml.scanner.ScannerError:
self._documentation = {}
return self._documentation
def get_components(self, path, method):
components = super().get_components(path, method)
doc_components = self.documentation.get("components", {})
components.update(doc_components)
return components
def get_operation(self, path, method):
operation = super().get_operation(path, method)
doc_operation = self.documentation.get(method.lower(), {})
operation.update(doc_operation)
return operation
@api_view(["GET", "POST"])
@permission_classes((permissions.AllowAny,))
@schema(AutoDocstringSchema())
def log_file_delete(request):
"""
get:
description: delete log file by using get method
summary: delete log file
parameters:
- name: file_path
in: query
description: file path of the log to delete
schema:
type: string
responses:
'200':
description: log file deleted
content:
'application/json': {}
"""
api_logger.info("access to delete log view")
method = request.method
if "GET" == method:
_arg_file_path = request.GET.get("file_path", None)
if "POST" == method:
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
_arg_file_path = body["file_path"]
if None is _arg_file_path or not _arg_file_path:
return JsonResponse({"error": "file_path arg is missing or empty"}, status=400)
try:
os.remove(Path(_arg_file_path))
open(_arg_file_path, "w") # need recreate empty file after delete
r = {"code": 202, "status_message": "job done! file deleted"}
except Exception as e:
r = {
"code": 400,
"status_message": "Ooops! there is an error when try to delete logs file %s, {}".format(
e
)
% _arg_file_path,
}
return JsonResponse(r, status=r["code"])
Run Code Online (Sandbox Code Playgroud)
注意:在这种情况下,我只是为 get 方法编写了 yaml 文档。
然后在 swagger-ui 上获取参数和我们需要的一切
所以我去github DRF存储库添加这个例子并提交PR来更新DRF文档
| 归档时间: |
|
| 查看次数: |
3792 次 |
| 最近记录: |