0

I have a little app which queries the records from the database and need to convert it to JSON and have to store it in local file.

I have reached this far:

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)

I am getting the error as:

TypeError: datetime.datetime(2011, 10, 16, 15, 14, 57) is not JSON serializable

How to proceed further ?

ajknzhol
  • 6,322
  • 13
  • 45
  • 72
  • Duplicate of [455580](http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript), or [12289466](http://stackoverflow.com/questions/12289466/get-python-json-to-serialize-datetime), or [12122007](http://stackoverflow.com/questions/12122007/python-json-encoder-to-support-datetime). – mknecht Jan 12 '14 at 10:39

1 Answers1

0

You have to convert your time from User class to string

EDIT:

My educated guess

time = db.Column(db.DateTime, default=None, index=True).ctime()
volcano
  • 3,578
  • 21
  • 28