gpt4 book ai didi

django - 如何在 Django REST Framework 中使用自定义 YAML 文件作为 API 文档?

转载 作者:行者123 更新时间:2023-12-04 11:50:33 25 4
gpt4 key购买 nike

我需要将 API 文档添加到我的项目中。我使用 swagger 编辑器编写了我的自定义架构,现在我有一个 YAML 文件,如下所示:

swagger: "2.0"
info:
description: "This is the documentation of Orion Protocol API"
version: "1.0.0"
title: "Orion Protocol API"
host: "127.0.0.1:8000"
basePath: "/api/"
paths:
/api/decode:
post:
tags:
- "pet"
summary: "Decode the payload"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "body"
description: "Packet data"
required: true
schema:
$ref: "#/definitions/PacketData"
responses:
"405":
description: "Invalid input"

/api/encode:
post:
description: "Encoding configuration parameters for the devices"
produces:
- "string"
parameters:
- in: "body"
name: "body"
description: "Addresses and values of configuration parameters"
required: true
schema:
$ref: "#/definitions/ConfigPayload"
responses:
"405":
description: "Invalid input"


definitions:
PacketData:
type: "object"
required:
- "payload"
properties:
payload:
type: "string"
description: "Packet string starting with 78"
example: "78010013518BB325140400000500000AAA0000002A6E0000004AC05D00006A00000000"
ConfigPayload:
type: "object"
properties:
Addresses of the configuration parameter:
type: "string"
description: "According to the documentation of configuration protocol"
example: "542"

现在我如何将它添加到项目中?它应该在项目中的什么位置? View 可以呈现这个文件吗?
我需要有以下路径:
urlpatterns = [
path('documentation/', some-view-that-will-render-yaml)
]

最佳答案

我找到了一个解决方案,这很容易。我们需要将 yaml 转换为 json 并将其保存在静态文件夹中。然后:
网址.py

urlpatterns =  [
...
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url': 'openapi-schema'}
), name='swagger-ui'),
]

模板/招摇-ui.html:
{% load static %}
<html>
<head>
<title>Documentation</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>

const ui = SwaggerUIBundle({
url: "{% static 'swagger.json' %}" ,
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
})
</script>
</body>
</html>

并将您的自定义架构保存为静态文件夹中的 json。作品!

关于django - 如何在 Django REST Framework 中使用自定义 YAML 文件作为 API 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com