My API is returning blank json, instead of desired nested schema

∥☆過路亽.° 提交于 2020-08-09 09:24:11

问题


My schema is:

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()

My API code is:

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

My expected response is:

{
  "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
    }
  ]
}

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

Any idea on what am I doing wrong here??

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

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


回答1:


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]}


来源:https://stackoverflow.com/questions/63136774/my-api-is-returning-blank-json-instead-of-desired-nested-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!