如何解决在Flask Restful /棉花糖中生成OpenAPI / Swagger示例的问题
我一直在尝试使用Flask,Flask-Restful,棉花糖模式和Flasgger编写一个宁静的API。目标是拥有一个自记录API,其中包含所有诸如验证之类的奇妙功能。
但是,我遇到了一个问题,因为我无法弄清楚如何使其在OpenAPI视图中产生良好的示例。具体来说,以下是我的运行状况检查代码(目前仅返回一般输出):
VERSION = pkg_resources.require("my-api")[0].version
class Version(fields.Field):
@typechecked
def _deserialize(self,value,*_,**__) -> version.Version:
try:
return version.Version(value)
except version.InvalidVersion as exc:
raise ValidationError("Not a valid version.") from exc
@typechecked
def _serialize(self,**__) -> str:
return str(value)
class StatusCode(fields.Int):
@typechecked
def _deserialize(self,value: int,**__) -> int:
if 0 < value < 600:
return value
raise ValidationError(f"Not a valid status code: {value}")
class NonnegativeInt(fields.Int):
@typechecked
def _deserialize(self,**__) -> int:
if value >= 0:
return value
raise ValidationError(f"Not a positive integer: {value}")
class Health(Schema):
read_access = fields.Bool(required=True)
version = Version(required=True)
write_access = fields.Bool(required=True)
status_codes = fields.Dict(keys=StatusCode(),values=NonnegativeInt(),required=True)
class Healthcheck(Resource,SwaggerView):
validation = True
parameters: List[None] = []
tags = ['infrastructure']
summary = "A healthcheck for the API"
description = "Indicates the health of the server hosting the backend API."
responses = {
200: {
"description": "All is well","schema": Health,},204: {
"description": "All is well,but there is no content to serve","schema": Health
},500: {
"description": ("The server is not healthy for whatever reason. It should not "
"be used and calls should not be routed to it.")
}
}
@staticmethod
@typechecked
def get() -> Tuple[Dict,int]:
return {'read_access': True,'status_codes': {200: 10},'version': VERSION,'write_access': True},200
然后运行此代码的实际代码是:
def swagger_config(route: str = '/apidocs/',debug: bool = False) -> Dict:
return {
"headers": [
],"specs": [
{
"endpoint": 'apispec_1',"route": '/apispec_1.json',"rule_filter": lambda rule: True,# all in
"model_filter": lambda tag: True,# all in
}
],"static_url_path": "/flasgger_static",# "static_folder": "static",# must be set by user
"swagger_ui": debug,"specs_route": "/apidocs/"
}
def main():
debug = True
app = Flask(__name__)
api = Api(app)
Swagger(app,config=swagger_config(debug=debug))
api.add_resource(Healthcheck,'/healthcheck')
app.run(debug=debug)
if __name__ == "__main__":
main()
这有效,我可以毫无问题地卷曲到端点并获取应该返回的运行状况检查数据。问题是,当我转到http://localhost:5000/apidocs
时,得到以下内容作为/healthcheck
端点的示例值:
{
"read_access": true,"status_codes": {
"additionalProp1": 0,"additionalProp2": 0,"additionalProp3": 0
},"write_access": true
}
这有几个问题。一方面,它不包含必需的版本,并且具有"additionalProp#"
而不是有用的状态代码。在某种程度上,这是有道理的,因为我从来没有给它提供可以接受的示例,但是我无法从文档中找出可以为每个端点指定示例的地方。
请告知
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。