vendredi 30 janvier 2015

Serialize DynamicDB results

I'm using Python/Boto/Flask to build an api to get user gps data.


The issue is there is a Decimal('1422568178.40941') where I expect there to just be 1422568178.40941. I can get the data as expected though for loops but I need to pass it back out as json with flask-restful.


Now when I hit the API i get a



TypeError: Decimal('1422642498.484733') is not JSON serializable



If I try



users={'tester1','tester2'}
locdata = blutrac.getallusers(users)
print locdata


I get



{'tester1': {u'lat': Decimal('68.2354'), u'user': u'tester1', u'epochtime': Decimal('1422568178.40941'), u'log': Decimal('-48.255')}, 'tester2': {u'lat': Decimal('68.2354'), u'user': u'tester2', u'epochtime': Decimal('1422642498.484733'), u'log': Decimal('-48.255')}}


But with



gpstracks = Table('gpstrack')
resuts = gpstracks.query_2(
user__eq='tester1',
reverse=True,
limit=1
)
for result in results:
for item in result:
print item


I get:



68.2354 tester1 1422642498.484733 -48.255



Model:



from boto.dynamodb2.table import Table

def getallusers(users):
locations = {}
for user in users:
userlocation = getuserlast(user)
locations[user] = userlocation
return locations

def getuserlast(user):
userdata = {}
gpstracks = Table('gpstrack')
results = gpstracks.query_2(
user__eq=user,
reverse=True,
limit=1
)
for result in results:
return result._data


View:



# LocationList
# shows a list of most recent locations of listed users
class LocationList(Resource):
def get(self):
users = {'user1', 'user2'}
data = blutrac.getallusers(users)
print data
return data
api.add_resource(LocationList, '/api/locations')


Browser JS code:



<script type="application/javascript">

function GetData() {
$( ".location").empty();
$.ajax({
type: "GET",
url: "/api/locations",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {

console.log(data);
for (user in data ){
console.log(user);

}

},

error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
</script>




Aucun commentaire:

Enregistrer un commentaire