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: <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.