Flask-Swagger-UI does not recognize path to swagger.json

会有一股神秘感。 提交于 2020-12-31 07:39:03

问题


I'm building an API, using Flask and flask-restful and flask-swagger-ui. I have now modified the project structure and now I can no longer access the project's swagger.json file.

Based on the package documentation flask-swagger-ui, you would only need to change the parameter API_URL to the correct path. But even when entering relative path or full path, I can no longer access the file.

My Code:

from flask import Flask, jsonify
from flask_migrate import Migrate
from flask_restful import Api
from flask_swagger_ui import get_swaggerui_blueprint

def create_app(config_name):

    app = Flask(__name__)

    app.config.from_object(config[config_name])

    api = Api(app, prefix="/api/v1")

    '''swagger specific'''
    SWAGGER_URL = '/api/v1/docs'
    # API_URL = 'templates/swagger.json'
    API_URL = 'app/templates/docs/swagger.json'
    SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
        SWAGGER_URL,
        API_URL,
        config={
            'app_name': "My Rest App"
        }
    )

    app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)

    db.init_app(app)
    Migrate(app, db)

    return app

My Tree Structure:

├── API
│   ├── app
│   │   ├── __init__.py
│   │   ├── models
│   │   │   ├── __init__.py
│   │   │   ├── db.py  
│   │   │   └── db2.py
│   │   ├── routes
│   │   │   ├── __init__.py
│   │   │   ├── resources.py
│   │   └── templates
│   │       └── docs
│   │           └── swagger.json
│   ├── app.db
│   ├── config.py
│   ├── main.py
│   ├── migrations
│   ├── requeriments
│   └── tests
└── README.md

I need help, to understand the problem of the path to the file and thus correct the problem.


回答1:


I believe that its a restriction on flask's end, but it seems like you must place static files in a folder explicitly named static/ at the root of your flask app.

Try changing

API_URL = 'app/templates/docs/swagger.json'

to

API_URL = '/static/swagger.json'

Then create a static/ folder in API/app/, and move your json into it. Like so: API/app/static/swagger.json

If that doesn't work, make sure you have the static/ folder in the correct directory, try print(app.root_path) after defining your flask app variable in order to see what flask considered the root path to be.



来源:https://stackoverflow.com/questions/55733136/flask-swagger-ui-does-not-recognize-path-to-swagger-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!