我需要将 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"
现在我该如何将其添加到项目中?它应该位于项目中的哪个位置?视图可以渲染这个文件吗?
我需要有以下路径:
urlpatterns = [
path('documentation/', some-view-that-will-render-yaml)
]
我找到了一个解决方案,而且非常简单。我们需要将 yaml 转换为 json 并将其保存在 static 文件夹中。然后:
urls.py
urlpatterns = [
...
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url': 'openapi-schema'}
), name='swagger-ui'),
]
模板/swagger-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 形式保存在静态文件夹中。作品!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)