Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Flask / MongoEngine DateTimeField

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!

like image 485
KMLong Avatar asked Oct 10 '14 20:10

KMLong


People also ask

How do you use MongoEngine with a flask?

Connecting to a MongoDB Database Instance Now that we have installed Flask and Flask-MongoEngine, we need to connect our Flask app with a MongoDB instance. Which we'll use to initialize a MongoEngine object. But before the initialization is done, we'll need a reference to our MongoDB instance.

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

What is Document in MongoEngine?

MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database.

How do I delete MongoEngine?

You can either delete an single Document instance by calling its delete method: lunch = Food. objects. first() // Get a single 'Food' instance lunch.


1 Answers

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()
like image 115
Ilyes KAANICH Avatar answered Sep 22 '22 22:09

Ilyes KAANICH