简体   繁体   English

如何为JSON响应序列化ndb.GeoPt以满足我在Python / Google App Engine中的需求

[英]How to serialize ndb.GeoPt for JSON response to fit my needs in Python/Google App Engine

this will be a two part questions, 这将是两部分问题,

Here I am sending a GeoPt to my ndb service. 在这里,我将GeoPt发送到我的ndb服务。 Here is what the JSON looks like. 这是JSON的样子。

{
    "DriverId": 1,
    "Startpoint": {
        "longitude": 46.764084,
        "latitude": -71.351396
    },
    "Endpoint": {
        "longitude": 46.764084,
        "latitude": -71.351396
    },
    "Regular": false,
    "DateAndTime": "28/03/2015",
    "PlacesAvailable": 3,
    "ValLift": 3
}

I use this function to serialize my DateTimes 我使用此函数来序列化我的DateTimes

def serialiser__json(objet):

    if isinstance(objet, datetime.datetime):
        return objet.replace(microsecond=0).isoformat()
    elif isinstance(objet, datetime.date):
        return objet.isoformat()
    else:
        return objet

Now I am wondering how I could serialize my GeoPt to JSON and return it to look the same as it was sent for example here is my Route model. 现在我想知道如何将我的GeoPt序列化为JSON并将其返回到与发送时相同的例如这里是我的Route模型。

class Route(ndb.Model):

  driver_id = ndb.IntegerProperty()
  requester_id = ndb.IntegerProperty()
  startpoint = ndb.GeoPtProperty(required=True)
  endpoint = ndb.GeoPtProperty(required=True)
  regular = ndb.BooleanProperty(required=True)
  date_and_time = ndb.DateTimeProperty(required=True)
  places_available = ndb.IntegerProperty()
  val_lift = ndb.IntegerProperty()

And here is how I add the long lat in my POST definiton 以下是我在POST定义中添加long lat的方法

newroute.startpoint = ndb.GeoPt(route_json['Startpoint']['longitude'],route_json['Startpoint']['latitude'])

newroute.endpoint = ndb.GeoPt(route_json['Endpoint']['longitude'],route_json['Endpoint']['latitude'])

So first part, 所以第一部分,

How would I serialize the GeoPt I have stored in model? 我如何序列化我存储在模型中的GeoPt?

Second part, 第二部分,

How to make it look the same way it was sent (return StartPoint with longitude and latitude "members" inside of it)? 如何使它看起来与发送方式相同(返回StartPoint中经度和纬度“成员”)?

Thanks in advance. 提前致谢。

The change you just posted as a self-answer to the body of your peculiarly named serialiser__json (weird to use two adjacent underscores within an identifier, though legal) gives you correct JSON functionality but does not meet your very strict requirement for the "second part": 您刚刚张贴作为自回答您的特有命名的身体的变化serialiser__json (怪异的标识符中使用两个相邻的下划线,但法律)给你正确的JSON功能,但符合您的非常严格的要求,为“第二部分“:

How to make it look the same way it was sent 如何使其外观与发送方式相同

There are several problems with that: (A), order of the keys (it's arbitrary when you use a dict , which may result in quite a different "look" of the resulting JSON string, although with equivalent semantics ); 有几个问题:(A),键的顺序(当你使用dict时它是任意的,这可能导致产生的JSON字符串的“看起来”非常不同,尽管具有相同的语义 ); (B), whitespace (your incoming JSON string apparently has all sort of beautifying whitespace, including newlines and spaces for indentation purposes); (B),空格(你传入的JSON字符串显然有各种美化空白,包括用于缩进目的的换行符和空格); as well as (C), potentially, minor issues with number of significant digits in the formatting of float s. 以及(C),可能是float格式中有效数字的次要问题。

(A) can be fixed by building up a collections.OrderedDict in the order you want the keys to be -- a json.dumps of that ordered dict will respect the keys' ordering. (A)可以通过按照你想要键的顺序构建collections.OrderedDict来修复 - 有序dict的json.dumps将尊重键的排序。 (B) and (C) are subtler are require more "beautification" work -- do you actually need such cosmetics in your output...? (B)和(C)更微妙,需要更多的“美化”工作 - 你的输出中真的需要这样的化妆品吗?

(All of these problems are pretty much independent of being on App Engine, by the way). (顺便说一句,所有这些问题都非常独立于App Engine上)。

Found how to do it 找到了怎么做

elif isinstance(objet, ndb.GeoPt):
            return {'longitude': objet.lon, 'latitude': objet.lat  }

The easiest way would be to override the to_dict method of your model. 最简单的方法是覆盖模型的to_dict方法。 EG: 例如:

to_dict(self):
  return {
    "DriverId": self.driver_id,
    "Startpoint": {
        "longitude": self.startpoint.longitude,
        "latitude": self.startpoint.latitude
    },
    "Endpoint": {
        "longitude": self.endpoint.longitude,
        "latitude": self.endpoint.latitude
    },
    "Regular": self.regular,
    "DateAndTime": serialiser__json(self.date_and_time),
    "PlacesAvailable": self.places_available,
    "ValLift": self.val_lift 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM