gpt4 book ai didi

Python/Flask/MongoEngine DateTimeField

转载 作者:行者123 更新时间:2023-12-03 16:24:32 28 4
gpt4 key购买 nike

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

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

无论如何都可以通过自定义JSON编码器等获取输出以使其看起来像这样:
"created_at": "2014-10-10T07:33:04Z",

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

谢谢!

最佳答案

这是一个使用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()

关于Python/Flask/MongoEngine DateTimeField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307439/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com