由于写完flask接口后,需要向前端提供swagger接口文档,因此需要自动生成swagger文档。
采用如下命令安装flask-restplus
pip install flask-restplus==0.13.0
安装完成后导入包时报错,这是因为新版的werkzeug中该模块导入发生了变化,需要手动修改下
cannot import name 'cached_property'
/usr/local/lib/python3.7/site-packages/werkzeug/__init__.py
文件中,添加:
from werkzeug.utils import cached_property
from flask import Flask
from flask_restplus import Resource, Api, fields
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)
# swagger文档标题
api = Api(app, version='1.0', title='???',
description='???')
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
# 配置不同模块的命名空间
edi_risk = api.namespace('aRisk', path='/')
# 参数解析
parser = api.parser()
# 配置post方法需要传递的接口输入参数
a_input = api.model('a_input', {
'input_text': fields.String(required=False, description='待查询的文本')
})
# 配置返回参数
a_risk_result = api.model('a_risk_result', {
'risk': fields.Float(description='综合风险'),
})
# 继承参数,子
child = api.model('child_risk_source', {
'is_risk_source': fields.Boolean(
required=True, description='', default=False
),
'risk_source_info': fields.String(
required=True, description='',
default='预警'
)
})
# 继承参数,父
parent = api.model('parent', {'risk_source': fields.Nested(child)})
@a_risk.expect(parser)
class aRisk(Resource):
# 配置输入参数说明
@a_risk.doc(body=a_input)
# 配置返回参数说明
@a_risk.marshal_with(a_risk_result)
def get(self, request):
"""
swagger测试用例-1
"""
results = {'SuccessFlag': True, 'Data': '输入文本成功!'}
receive_params = request.get_data(as_text=True)
receive_params = receive_params.replace("\\\\", "\\")
post_value = json.loads(receive_params,
encoding="utf-8")
input_text = post_value['input_text']
return results, 200
@a_risk.doc(body=a_input)
@a_risk.marshal_with(a_risk_result)
def post(self, request):
"""
swagger测试用例-2
"""
results = {'SuccessFlag': True, 'Data': '输入文本成功!'}
receive_params = request.get_data(as_text=True)
receive_params = receive_params.replace("\\\\", "\\")
post_value = json.loads(receive_params,
encoding="utf-8")
input_text = post_value['input_text']
return results, 200
# 配置各命名空间下的接口
a_risk.add_resource(aRisk, '/aRisk/')
if __name__ == '__main__':
app.run(host="0.0.0.0", port="8000", debug=True)
启动时提示:
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
部署时应当采用WSGI启动,添加如下代码
from gevent import pywsgi
def query_api_wsgi():
"""
部署的WSGI启动模式
"""
server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
server.serve_forever()