Api 端点未在 Flask-Restx 中注册

Api endpoints do not register in Flask-Restx

我一直在学习一些教程 (basic examples), trying to create a RESTful API with Flask-Restx. However, when I try to register endpoints with a more complex project structure(following this example),但没有 API 个端点被注册。 我定义了端点的命名空间并尝试在 app.py:

中注册它
from flask import Flask, Blueprint, url_for, jsonify
from flask_login import LoginManager
import settings
from database import db
from BE.api.__init__ import api
from BE.api.endpoints.images import ns as image_api
from werkzeug.middleware.proxy_fix import ProxyFix



app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

#flask_restx API supports prior flask_restplus api
def configure_app(app):
    app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_EXPANSION
    app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VAL
    app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI
    app.config['UPLOAD_FOLDER'] = settings.UPLOAD_FOLDER
    app.config['MAX_UPLOAD_LENGTH'] = 24 * 1024 * 1024  # limits filesize to 24 mb

def init_app(app):
    configure_app(app)
    api.add_namespace(image_api)
    app.register_blueprint(api, url_prefix='/api/1')
    api.init_app(app)
    db.init_app(app)
[....main etc]

API init.py 看起来如下:

from flask_restx import Api


api = Api(version='0.1', title='Backend API', description='Backend API for sticker generation')

以及我要注册的端点:

from flask import request, flash, Blueprint, redirect, send_file
from flask_restx import Resource, Namespace
from BE.database import db as database
from BE.database.models import Image as dbImage
from BE.api.api_definition import image
[....]

ns = Namespace('image', path='/image', description='Available Ops')

@ns.route('/test')
class TestClass(Resource):
    def get(self):
        return "Hello World"
[....]

虽然@app.route('/') 在app.py 中有效,但@ns.route('/') 仍然不成功,我不知道为什么。

回答我自己的问题:

事实证明 PyCharm 中的 运行ning app.py 不是 运行 通过 main() 或者是以错误的方式配置,而是似乎只是从初始 app = Flask(__name__) 启动 Flask 服务器。因此 configure_app() 或 init_app() 永远不会被调用。 将项目布局转换为更类似于 Flask's intended layout 的内容可以部分解决该问题,从而使预期的端点正常工作。