flask - 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”的实际返回字符串。有谁知道这是为什么以及如何解决这个问题?
解决方案
我决定在发布后不久继续前进,事实证明命名空间是强制性的,您可以使用下面的代码修复我上面的代码以创建命名空间。这将使基本的 helloworld 工作。
hello_ns = api.namespace('', description='Hello World Operations')
@hello_ns.route("/hello")
class HelloWorld(Resource):
def get(self):
return "Hello"
推荐阅读
- sql - 是否有可能无法访问具有 sql 注入漏洞的应用程序上的数据库?
- python - 在 Windows 10 / Python 3.6 上安装 Sybase 包失败
- python - 执行 Postgres SQL 脚本、接受响应并评估的 Python 脚本
- python - 在 Python Gino 中获取池连接(异步)
- python - Cython 实现不比纯 python 快
- javascript - 更改后,日期选择器验证不起作用-BootStrap
- module - 编程中源代码和代码的不同含义是什么?
- python - Python Pandas to_csv,能不能用.replace() 抢先处理双引号转义问题
- java - 为什么我无法使用 StringTokenizer 访问第二个令牌?
- r - 如何覆盖@运算符以访问 R 中 S4 对象的插槽