10

首先,我是 python 和烧瓶的新手。我四处寻找并尝试了一些无济于事的事情。我有一个模型,它有一个 DateTimeField 作为成员之一,我们称之为“created_at”。当我将查询集返回为 JSON 时,我看到该字段

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

无论如何要通过自定义 JSON 编码器等来获取输出,以使其看起来像这样:

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

任何指导或建议将不胜感激。

谢谢!

4

1 回答 1

3

这是一个使用 flask 和 flask-mongoengine 获取日期为 ISO 8601 字符串的示例

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()
于 2021-01-13T13:42:09.253 回答