我的API返回的是空白json,而不是所需的嵌套模式 [英] My API is returning blank json, instead of desired nested schema

查看:83
本文介绍了我的API返回的是空白json,而不是所需的嵌套模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模式是:

import time
from marshmallow import fields, Schema
from ramas_core.api.resources.base import CamelCaseSchema, base_filters, unfilterable_fields

class colorMapLayersSchema(CamelCaseSchema):
    #raster_layer
    id = fields.UUID()
    visibility = fields.Boolean()
    color_map_type = fields.String()
    #capture
    field_id = fields.UUID()
    event_date = fields.DateTime()
    event_date_time = fields.String()

class gridMapLayersSchema(CamelCaseSchema):
    #raster_layer
    id = fields.UUID()
    visibility = fields.Boolean()
    metric_type = fields.String()
    #capture
    field_id = fields.UUID()
    event_date = fields.DateTime()
    event_date_time = fields.String()

class indexMapLayersSchema(CamelCaseSchema):
    #raster_layer
    id = fields.UUID()
    visibility = fields.Boolean()
    index_map_type = fields.String()
    #capture
    field_id = fields.UUID()
    event_date = fields.DateTime()
    event_date_time = fields.String()

class LayersSchema(CamelCaseSchema):
    color_map_layers = fields.List(fields.Nested(colorMapLayersSchema))
    grid_map_layers = fields.List(fields.Nested(gridMapLayersSchema))
    index_map_layers = fields.List(fields.Nested(indexMapLayersSchema))

filterable_fields = {
    "capture_id": fields.UUID()
}

filterable_fields.update(base_filters)
filterable_fields.update(unfilterable_fields)

layers_schema = LayersSchema()

我的API代码是:

import logging
import json

import flask
from flask_smorest import Blueprint
from datetime import datetime

from ramas_core.api.resources.v1.layers import layers_schema
from ramas_core.models.ramas import User
from ramas_core.models.raster_layer import RasterLayer
from ramas_core.models.capture import Capture

from sqlalchemy import func
from sqlalchemy.dialects.postgresql import JSON

logger = logging.getLogger(__name__)
blueprint = Blueprint("layers_v1", __name__)

@blueprint.route("", methods=["GET"])
@blueprint.response(layers_schema)
def get_layers():
    """Return current user details."""
    session = flask.g.session
    username = flask.g.identity.username
    
    color = session.query(
        RasterLayer.id,
        RasterLayer.tags['visibility'].label('visibility'),
        RasterLayer.tags['legacy_sub_layer_type'].label('color_map_type'),
        Capture.field_id,
        Capture.capture_datetime.label('event_date'), 
    ).join(Capture, RasterLayer.capture_id == Capture.id) \
    .filter(RasterLayer.tags['legacy_layer_type'].astext == 'color').all() 

    grid = session.query(
        RasterLayer.id,
        RasterLayer.tags['visibility'].label('visibility'),
        RasterLayer.tags['legacy_sub_layer_type'].label('metric_type'),
        Capture.field_id,
        Capture.capture_datetime.label('event_date'), 
    ).join(Capture, RasterLayer.capture_id == Capture.id) \
    .filter(RasterLayer.tags['legacy_layer_type'].astext == 'grid').all()

    index = session.query(
        RasterLayer.id,
        RasterLayer.tags['visibility'].label('visibility'),
        RasterLayer.tags['legacy_sub_layer_type'].label('index_map_type'),
        Capture.field_id,
        Capture.capture_datetime.label('event_date'), 
    ).join(Capture, RasterLayer.capture_id == Capture.id) \
    .filter(RasterLayer.tags['legacy_layer_type'].astext == 'index').all()
    
    color_map_layers = flask.jsonify(color)
    grid_map_layers = flask.jsonify(grid)
    index_map_layers = flask.jsonify(index)

    result = {"colorMapLayers": [color_map_layers], "gridMapLayers": [grid_map_layers], "indexMapLayers": [index_map_layers]}
 
    return result

我的预期答复是:

{
  "colorMapLayers": [
    {
      "colorMapType": "rgb",
      "eventDate": "string",
      "eventDateTime": "2020-07-28T14:33:58.464Z",
      "fieldId": 0,
      "id": "string",
      "visibility": true
    }
  ],
  "gridMapLayers": [
    {
      "eventDate": "string",
      "eventDateTime": "2020-07-28T14:33:58.464Z",
      "fieldId": 0,
      "id": "string",
      "metricType": "plant_count",
      "visibility": true
    }
  ],
  "indexMapLayers": [
    {
      "eventDate": "string",
      "eventDateTime": "2020-07-28T14:33:58.464Z",
      "fieldId": 0,
      "id": "string",
      "indexMapType": "ndvi",
      "visibility": true
    }
  ]
}

但是我当前得到的响应是:空的json {}

But the response I get currently is : empty json {}

关于我在这里做错什么的任何想法吗?

Any idea on what am I doing wrong here??

我还想知道如何在旅途中将dateTime转换为字符串?

I would also like to know how do I convert the dateTime to string on the go?

这也是定义嵌套数组json的正确方法吗?我需要操纵查询吗?

Also is this the correct way to define a nested array json? Do I need to manipulate the query?

推荐答案

基于棉花糖dump_serialize的源代码

Base on the source code from Marshmallow's dump and _serialize methods, it looks like a schema is parsed by looping over the attributes, checking which are in the dictionary, and ignoring missing keys. However, the keys of that are checked are based on, in your case layers_schema.__dict__ - and those are probably snake_case, while the keys of the object you return are camelCase. Could it be that changing the keys of the dictionary fixes the problem? So

result = {"color_map_layers": [color_map_layers], "grid_map_layers": [grid_map_layers], "index_map_layers": [index_map_layers]}

这篇关于我的API返回的是空白json,而不是所需的嵌套模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆