python flask怎么能把swagger.yaml 文件引到swagger中 并在页面展示出来测试页面
时间: 2024-12-17 16:55:41 浏览: 25
要将`swagger.yaml`文件引入Flask应用并将其显示为测试页面,你需要使用`flasgger`库。`flasgger`是一个基于Swagger UI的API文档生成器,非常适合Flask项目。首先,请确保已经安装了`flasgger`:
```bash
pip install flasgger
```
然后,按照以下步骤配置你的项目:
1. 安装依赖项(如果尚未安装):
```python
pip install Flask Swagger UI
```
2. 导入所需模块并在应用程序中初始化`Flasgger`:
```python
from flask import Flask, render_template, request
from flasgger import Swagger
app = Flask(__name__)
swagger = Swagger(app)
```
3. 创建或编辑`swagger.yaml`文件,通常放在`templates/swagger`目录下(如果不存在,可以自定义路径)。这个文件包含了API的描述信息,例如路径、请求方法、参数等。基本结构可能类似这样:
```yaml
openapi: "3.0.2"
info:
title: "My API"
version: "1.0.0"
paths:
/api-endpoint:
get:
summary: "Endpoint Description"
description: "This is an example GET endpoint."
responses:
'200':
description: "Success"
```
4. 配置`Flasgger`以使用`swagger.yaml`:
```python
@app.route('/')
def index():
swag = {
"specs": [
{"endpoint": "apispec_1", "route": "/apispec_1", "rule_filter": lambda rule: True, "model": "schema", "filename": "swagger.yaml"}
],
"static_url_path": "/flasgger_static",
"static_folder": "templates/swagger",
"openapi": "3.0.2"
}
return render_template("flasgger.html", config=swag)
```
这里,我们设置了一个路由,渲染`flasgger.html`模板并将`swagger.yaml`包含其中。
5. 创建`flasgger.html`模板,通常在`templates`目录下,这将显示Swagger UI界面:
```html
{% extends "base.html" %}
{% block content %}
{{ super() }}
<div id="swagger-ui">
<!-- swagger-ui will be inserted here -->
</div>
<script src="{{ url_for('static', filename='swagger-ui-bundle.js') }}"></script>
<script src="{{ url_for('static', filename='swagger-ui-standalone-preset.js') }}"></script>
<script>
window.onload = function () {
var url = "{{ url_for('apispec_1') }}";
SwaggerUIBundle({
url: url,
dom_id: '#swagger-ui',
presets: [SwaggerUIBundle.presets.apis],
plugins: [],
layout: "BaseLayout"
});
};
</script>
{% endblock %}
```
6. 最后,创建一个处理API规范的路由,这通常是不直接提供服务的,只是返回`yaml`内容:
```python
@app.route('/apispec_1')
def apispec_1():
with open('templates/swagger/swagger.yaml', 'r') as file:
spec_dict = yaml.safe_load(file)
return jsonify(spec_dict), 200, {'Content-Type': 'application/json'}
```
现在,当你运行应用时,访问`http://localhost:5000/`将会显示Swagger UI界面,你可以根据`swagger.yaml`中的内容进行测试和文档查看。
阅读全文