Python / Flask / MongoEngine DateTimeField
Asked Answered
F

1

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!

Furgeson answered 10/10, 2014 at 20:18 Comment(6)
Is this what you are looking for? #15042453Segalman
Not really. I believe it is a python/mongo issue in the way it de/serializes the python datetimeFurgeson
What kind of format is this time value '1412938697488' in? unixtime?or?Namedropping
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.Serviceable
You can use mongoengine and flask-restful to marshal objects.Griffis
I could really use an answer to this question. If anyone has any advice, please let me know.Annoying
L
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()
Legg answered 13/1, 2021 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.