首页 > 解决方案 > Flask restx 返回 Class 而不是实际的返回字符串

问题描述

最近我一直在尝试使用flask-restx添加一个api。即使让 helloworld 工作,我也遇到了一些麻烦。

我在蓝图中拥有一切,因此将 api 也放在自己的蓝图中才有意义。下面是我的 api_routes.py

from flask_login import current_user, login_user, logout_user, login_required
from flask_restx import Resource, Api
from flask import Blueprint
import flask
from . import db

api_bp = Blueprint('api_bp', __name__, url_prefix='/api')
api = Api(api_bp, version='1.0', title='Scribe API',
    description='An API for interfacing with Scribe',
)

@api_bp.route("/hello")
class HelloWorld(Resource):
    def get(self):
        return "Hello"

api.add_resource(HelloWorld, '/hello')

但是,如果你去 swagger ui 并像这样发送一个 get :

curl -X GET "http://127.0.0.1:5000/api/hello" -H  "accept: application/json"

响应为 500:

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a HelloWorld.

因此,出于某种奇怪的原因,我返回了类,而不是“Hello”的实际返回字符串。有谁知道这是为什么以及如何解决这个问题?

标签: flask

解决方案


我决定在发布后不久继续前进,事实证明命名空间是强制性的,您可以使用下面的代码修复我上面的代码以创建命名空间。这将使基本的 helloworld 工作。

hello_ns = api.namespace('', description='Hello World Operations')

@hello_ns.route("/hello")
class HelloWorld(Resource):
    def get(self):
        return "Hello"

推荐阅读