Flask集成Swagger加载API定义失败(报错INTERNAL SERVER ERROR /docs.json)求助
Flask集成Swagger加载API定义失败(报错INTERNAL SERVER ERROR /docs.json)求助
看起来你在给Flask项目集成Swagger(用Flasgger)的时候遇到了500服务器错误,我帮你梳理几个最可能的问题和解决办法:
先把你的代码整理出来方便排查:
from flask import Flask, jsonify from flasgger import Swagger, swag_from from flask.json import JSONEncoder from flask_lazyviews import LazyString, LazyJSONEncoder # 假设你导入了这些依赖 app = Flask(__name__) app.json_encoder = LazyJSONEncoder swagger_template = dict( info = { 'title': 'API Documentation for Data Processing and Modeling', 'version': '1.0.0', 'description': 'Dokumentasi API untuk Data Processing dan Modeling', } # host = LazyString(lambda: request.host) # 注释部分没问题 ) swagger_config = { "headers": [], "specs": [ { "endpoint": 'docs', "route": '/docs.json', } ], "static_url_path": "/flasgger_static", "swagger_ui": True, "specs_route": "/docs/" } swagger = Swagger(app, template=swagger_template, config=swagger_config) @app.route('/', methods=['GET']) # jika terdapat folder docs# @swag_from('..\DS_1\docs\colors.yml') #jika file yml satu level dengan file py @swag_from('docs\hello_world.yml') def hello_world(): json_response = { 'status_code': 200, 'description': "Menyapa Hello World", 'data ': "Hello World", # 这里data后面多了个空格,建议去掉避免后续问题 } response_data = jsonify(json_response) return response_data if __name__ == '__main__': app.run # 这里少了括号!应该是app.run()
最可能的问题及解决步骤:
文件路径转义问题(最常见)
Windows系统里的反斜杠\在Python字符串中是转义字符,你写的@swag_from('docs\hello_world.yml')里的\h会被Python解析成转义字符,导致程序找不到正确的文件路径。
解决办法:- 改用正斜杠:
@swag_from('docs/hello_world.yml') - 或者用双反斜杠:
@swag_from('docs\\hello_world.yml')
- 改用正斜杠:
YAML文件格式错误
如果修正路径后还是报错,大概率是hello_world.yml的格式有问题,比如缩进不对、键名格式错误、字符串未正确闭合等。
给你一个符合Flasgger要求的yml示例,你可以对照检查:--- parameters: [] responses: 200: description: 成功返回Hello World schema: type: object properties: status_code: type: integer description: type: string data: type: string代码里的启动错误
你的启动代码app.run少了括号,应该改成app.run(),否则程序无法正确启动Flask服务,这也会导致访问时出现服务器错误。依赖版本兼容问题
如果上面的方法都试过还是不行,可以检查Flasgger和Flask的版本是否兼容。建议尝试安装一组稳定的版本组合:pip install flask==2.0.3 flasgger==0.9.5
先从路径问题开始排查吧,这是新手最容易踩的坑,希望这些方法能帮你解决问题!
备注:内容来源于stack exchange,提问作者Anom Bhuja Sukardika
相关产品推荐
相关产品推荐

