【发布时间】:2020-08-14 05:29:17
【问题描述】:
在flask-restplus中,我使用api.model装饰器定义了响应体数据结构,我期望api函数的输出应该产生我定义的精确数据结构。我不知道如何准确地做到这一点。谁能指出我如何验证烧瓶中的 json 响应内容?使用定义的模式验证 json 响应输出的任何解决方法?有什么想法吗?
当前输出:
这是我向 api 函数发出 POST 请求后的当前输出:myfunc:
"{\n\r\n \"score\": [72.188, 62.0955, 19.3374, 45.6086, 77.8891, 22.188, 45.9938, 91.9877, 14.2527, 1.5408, 62.5578],\n\r\n \"category\": \"low\",\n\r\n \"direction\": \"text description\",\n\r\n \"is_ready\": true,\n\r\n \"features_used\": {\n\r\n \"name\": \"heart_rate\",\n\r\n \"value\": null,\n\r\n \"range_value\": [3.6667, 5, 6.3333, 7.6667, 9, 10.3333, 11.6667, 13, 14.3333],\n\r\n \"range_frequency\": [0.0024, 0, 0.0049, 0.0016, 0.0073, 0.0195, 0.0098, 0.0138, 0.9406],\n\r\n \"level\": 0\n\r\n }\n\r\n} \n"
问题是当前输出的格式没有产生定义的响应正文。如何解决这个问题?如何验证烧瓶中的 json 响应内容?任何可能的方法来实现这一点?谢谢
具有指定响应 json 正文的最小 api
from flask import Flask, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse
from flask_restplus import Api
app = Flask(__name__)
api = Api(app)
ns = api.namespace('hello-world')
used_features = {}
used_features['name'] = fields.String(attribute='name')
used_features['value'] = fields.Integer(attribute='value')
used_features['range_value'] = fields.List(
fields.Integer, attribute='range_value')
used_features['range_frequency'] = fields.List(
fields.Integer, attribute='range_frequency')
used_features['level'] = fields.Integer(attribute='level')
used_features_payload = api.model('feature_payload', used_features)
response_body= api.model('response', {
'score': fields.Integer,
'category': fields.String,
'direction': fields.String,
'is_ready': fields.Boolean,
'features_used': fields.Nested(used_features_payload)
})
目标:
我想验证当前输出的 JSON 模式。如何使用响应正文 JSON 模式验证函数输出?有什么想法吗?
【问题讨论】:
-
您的
post方法正在对变量res进行字符串化,您是否要改为return jsonify(res)?
标签: python json validation flask