【问题标题】:Flask Swagger UI not able to find swagger.jsonFlask Swagger UI 无法找到 swagger.json
【发布时间】:2020-07-29 13:13:23
【问题描述】:

我正在尝试运行烧瓶 swagger ui,但它提示我找不到 API 定义的消息。 我正在使用请求获取在线 swagger.json 并将其放入 static > swagger.json 。 无法共享在线招摇网址,因为它是组织财产。

文件夹结构:

| App
    | static
           | swagger.json
    | app.py
    | requirements.txt

代码:

import requests
import json
import argparse
import os
from flask import Flask, jsonify, make_response
from flask_cors import CORS
from flask_swagger_ui import get_swaggerui_blueprint
from flask import Blueprint

REQUEST_API = Blueprint('request_api', __name__)
PATH = "C:/Users/swagger/api/static/swagger.json"

def get_blueprint():
    """Return the blueprint for the main app module"""
    return REQUEST_API

APP = Flask(__name__)

### swagger specific ###
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'

json_data = requests.get('https://url/api/swagger.json') 
data = json_data.content
with open(PATH, 'wb') as f:
    f.write(data)

SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
    config={
        'app_name': "API"
    }
)
APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
### end swagger specific ###


APP.register_blueprint(get_blueprint())

if __name__ == '__main__':

    PARSER = argparse.ArgumentParser(
        description="API doc")

    PARSER.add_argument('--debug', action='store_true',
                        help="Use flask debug/dev mode with file change reloading")
    ARGS = PARSER.parse_args()

    PORT = int(os.environ.get('PORT', 5000))

    if ARGS.debug:
        print("Running in debug mode")
        CORS = CORS(APP)
        APP.run(host='0.0.0.0', port=PORT, debug=True)
    else:
        APP.run(host='0.0.0.0', port=PORT, debug=False)
      

错误:

【问题讨论】:

  • /static/swagger.json 看起来像一个绝对路径(我不知道它在 Windows 环境中是如何解释的)但是您正在将文件写入C:/Users/swagger/api/static/swagger.json。也许你的意思是static/swagger.json(没有斜线)代表API_URL。为防止出现任何一致性问题,您可以使用相同的常量来写入文件并将其传递给 get_swaggerui_blueprint

标签: python flask swagger


【解决方案1】:

flask-swagger-ui 的基本示例明确表示接受本地资源。所以这应该有效:

from pathlib import Path

API_URL = Path("C:/Users/swagger/api/static/swagger.json")  # maybe you need a .resolve() if Path objects are not supported

【讨论】:

  • 实际上并不适合我,但是是的,无论如何都不接受它所说的 Path 对象和 Windows 路径对象。所以应该只写基于文本的路径