10

First of I'm new to python and flask. I've searched around and tried something things to no avail. I have a model that has a DateTimeField as one of the members, let's call it "created_at". When I go to return the query set as JSON I see this for the field

...
"created_at": {
    "$date": 1412938697488
} 
...

Is there anyway to get the output, either through a custom JSON encoder, etc to get it to look like this :

"created_at": "2014-10-10T07:33:04Z",

Any guidance or suggestions would be greatly appreciated.

Thanks!

KMLong
  • 8,345
  • 2
  • 16
  • 19
  • Is this what you are looking for? http://stackoverflow.com/questions/15041953/is-there-a-way-to-display-timestamp-in-unix-format-to-isodate – CodeLikeBeaker Oct 10 '14 at 20:45
  • Not really. I believe it is a python/mongo issue in the way it de/serializes the python datetime – KMLong Oct 10 '14 at 20:59
  • What kind of format is this time value '1412938697488' in? unixtime?or? – Stephen Lin Oct 11 '14 at 03:11
  • 1
    By the tags you used you're using mongoengine to create database models. When you use a mongoengine `DatetimeField` the data is stored as a MongoDB ISODate which looks like: ISODate("2014-11-24T15:32:45.930Z") When loading a document, mongoengine will create a python datetime object to hold this date. – Emanuel Ey Nov 24 '14 at 16:55
  • You can use mongoengine and flask-restful to marshal objects. – Vahid Kharazi Apr 12 '16 at 10:02
  • 1
    I could really use an answer to this question. If anyone has any advice, please let me know. – Del Mar 27 '19 at 13:20

1 Answers1

3

Here is an example using flask and flask-mongoengine to get a date as ISO 8601 string

import datetime

from bson.json_util import dumps
from flask import Flask, Response, request
from flask_mongoengine import MongoEngine

app = Flask(__name__)
db = MongoEngine()

class Movie(db.Document):
    name = db.StringField(required=True, unique=True)
    casts = db.ListField(db.StringField(), required=True)
    genres = db.ListField(db.StringField(), required=True)
    created_at = db.DateTimeField(default=datetime.datetime.utcnow)


@app.route('/movies')
def get_movies():
    movies = Movie.objects()
    movies_list = []
    for movie in movies:
        movie_dict = movie.to_mongo().to_dict()
        movie_dict['created_at'] = movie.created_at.isoformat()
        movies_list.append(movie_dict)
    movies_josn = dumps(movies_list)
    return Response(movies_josn, mimetype="application/json", status=200)


@app.route('/movies', methods=['POST'])
def add_movie():
    body = request.get_json()
    movie = Movie(**body).save()
    id = movie.id
    return {'id': str(id)}, 200


if __name__ == '__main__':

    app.config['MONGODB_SETTINGS'] = {
        'host': 'mongodb://localhost/movie-bag'
    }


    db.init_app(app)
    app.run()
Ilyes KAANICH
  • 336
  • 1
  • 3
  • 7