Python Flask自动生成的SwaggerOpenAPI 3.0[已关闭]。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Flask自动生成的SwaggerOpenAPI 3.0[已关闭]。相关的知识,希望对你有一定的参考价值。
我试图为我现有的Flask应用程序生成swagger文档,我尝试了用 Flask-RESTPlus
最初,发现现在项目很丰富,于是在分叉的项目上进行了检查。flask-restx
https:/github.compython-restxflask-restx。 但我仍然不认为他们支持openapi 3.0。
我对如何选择适合我需要的包有点困惑。我想解决一个问题,我们不想手动为我们的API创建swagger doc,而是想用一个包自动生成。
import os
import requests
import json, yaml
from flask import Flask, after_this_request, send_file, safe_join, abort
from flask_restx import Resource, Api, fields
from flask_restx.api import Swagger
app = Flask(__name__)
api = Api(app=app, doc='/docs', version='1.0.0-oas3', title='TEST APP API',
description='TEST APP API')
response_fields = api.model('Resource',
'value': fields.String(required=True, min_length=1, max_length=200, description='Book title')
)
@api.route('/compiler/', endpoint='compiler')
# @api.doc(params='id': 'An ID')
@api.doc(responses=403: 'Not Authorized')
@api.doc(responses=402: 'Not Authorized')
# @api.doc(responses=200: 'Not Authorized')
class DemoList(Resource):
@api.expect(response_fields, validate=True)
@api.marshal_with(response_fields, code=200)
def post(self):
"""
returns a list of conferences
"""
api.payload["value"] = 'Im the response ur waiting for'
return api.payload
@api.route('/swagger')
class HelloWorld(Resource):
def get(self):
data = json.loads(json.dumps(api.__schema__))
with open('yamldoc.yml', 'w') as yamlf:
yaml.dump(data, yamlf, allow_unicode=True, default_flow_style=False)
file = os.path.abspath(os.getcwd())
try:
@after_this_request
def remove_file(resp):
try:
os.remove(safe_join(file, 'yamldoc.yml'))
except Exception as error:
log.error("Error removing or closing downloaded file handle", error)
return resp
return send_file(safe_join(file, 'yamldoc.yml'), as_attachment=True, attachment_filename='yamldoc.yml', mimetype='application/x-yaml')
except FileExistsError:
abort(404)
# main driver function
if __name__ == '__main__':
app.run(port=5003, debug=True)
上面的代码是我在不同的包上尝试的组合,但它可以生成swagger 2.0的文档,但我想生成openapi 3.0的文档。
有谁能给我推荐一个支持openapi 3.0的好包来生成swagger yaml或json。
答案
我找到了一个生成openapi 3.0文档的包。
https:/apispec.readthedocs.ioenlatestinstall.html。
这个包的作用很整齐。详细使用方法请找下面的代码。
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from marshmallow import Schema, fields
from flask import Flask, abort, request, make_response, jsonify
from pprint import pprint
import json
class DemoParameter(Schema):
gist_id = fields.Int()
class DemoSchema(Schema):
id = fields.Int()
content = fields.Str()
spec = APISpec(
title="Demo API",
version="1.0.0",
openapi_version="3.0.2",
info=dict(
description="Demo API",
version="1.0.0-oas3",
contact=dict(
email="admin@donofden.com"
),
license=dict(
name="Apache 2.0",
url='http://www.apache.org/licenses/LICENSE-2.0.html'
)
),
servers=[
dict(
description="Test server",
url="https://resources.donofden.com"
)
],
tags=[
dict(
name="Demo",
description="Endpoints related to Demo"
)
],
plugins=[FlaskPlugin(), MarshmallowPlugin()],
)
spec.components.schema("Demo", schema=DemoSchema)
# spec.components.schema(
# "Gist",
#
# "properties":
# "id": "type": "integer", "format": "int64",
# "name": "type": "string",
#
# ,
# )
#
# spec.path(
# path="/gist/gist_id",
# operations=dict(
# get=dict(
# responses="200": "content": "application/json": "schema": "Gist"
# )
# ),
# )
# Extensions initialization
# =========================
app = Flask(__name__)
@app.route("/demo/<gist_id>", methods=["GET"])
def my_route(gist_id):
"""Gist detail view.
---
get:
parameters:
- in: path
schema: DemoParameter
responses:
200:
content:
application/json:
schema: DemoSchema
201:
content:
application/json:
schema: DemoSchema
"""
# (...)
return jsonify('foo')
# Since path inspects the view and its route,
# we need to be in a Flask request context
with app.test_request_context():
spec.path(view=my_route)
# We're good to go! Save this to a file for now.
with open('swagger.json', 'w') as f:
json.dump(spec.to_dict(), f)
pprint(spec.to_dict())
print(spec.to_yaml())
希望对大家有所帮助! :)
以上是关于Python Flask自动生成的SwaggerOpenAPI 3.0[已关闭]。的主要内容,如果未能解决你的问题,请参考以下文章
python自动化自动化测试平台开发:2.flask技术讲解上
用于下载 Python3 Flask 生成的 Zip 文件的 Javascript 按钮