我有一个小应用程序查询数据库中的记录,需要将其转换为JSON
,并且必须将其存储在本地文件中。
我到目前为止:
models.py
from flask.ext.sqlalchemy import SQLAlchemy
from app import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://ajay:12345@localhost/fusion'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=None, index=True)
views.py
from models import User
from flask import render_template
from app import app
from json import dumps
from sqlalchemy.orm import class_mapper
def serialize(model):
columns = [c.key for c in class_mapper(model.__class__).columns]
return dict((c, getattr(model, c)) for c in columns)
@app.route('/')
def index():
data = [ serialize(user) for user in User.query.all() ]
file = open('data.json','w')
json_users = dumps(data)
file.write(json_users)
file.close()
return render_template('index.html', users=json_users)
我收到的错误是:
TypeError: datetime.datetime(2011, 10, 16, 15, 14, 57) is not JSON serializable
如何进一步处理?
答案 0 :(得分:0)
您必须将时间从用户类转换为字符串
修改强>
我有根据的猜测
time = db.Column(db.DateTime, default=None, index=True).ctime()