0

My python version is 2.7 and Flask version is 0.10. Below is my script:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import request, jsonify
from flask import Response
import json
from pprint import pprint

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/postgres'
app.debug = True
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r' % self.username

 @app.route('/users', methods=['GET'])
 def get_users():
    myUsers = User.query.all()
    pprint(myUsers)
    return jsonify({'users': myUsers})

@app.route('/post_user', methods=['POST'])
def post_user():
    data = request.get_json()
    user = User(data['username'], data['email'])
    db.session.add(user)
    db.session.commit()
    return jsonify(**data)

if __name__ == '__main__':
    app.run()

The post call works fine and I can see the data in the database. But when I try to get the users,I get the below error:

'TypeError: &lt;User u'John' is not JSON serializable // Werkzeug Debugger'. 

The output of the 'print' is as below:

[<User u'John', <User u'Jane']

It isn't printing the entire object in the list i.e. the id, username and email. I am not sure what is the problem here. I have gone through many stackoverflow post about returing a list with Flask but nothing works. Also, the versions that I need to use are quite old so that is also a limitation here.

davidism
  • 121,510
  • 29
  • 395
  • 339
T Anna
  • 874
  • 5
  • 21
  • 52

1 Answers1

1

I expect that the problem is in your __repr__ function that it returns the string '<User %r' % self.username and doesn't return the whole object data.

I can suggest that you use a serialize function in your User class like that:

    @property
    def serialize(self):
        return {
            'id': self.id,
            'username': self.username
            'email': self.email
        }

And then you will be able to return JSON output using:

users = session.query(User).all()
return jsonify(users=[i.serialize for i in users])