How to display an array of objects using python flask and mongoalchemy

做~自己de王妃 提交于 2019-12-24 08:12:11

问题


How to write an end point which will return a array of json objects for mongoalchemy

I am trying to do as shown below:

@authenticate_bp.route('/users',methods=['GET'])
def user_list():
    users = [x.serialize for x in TokenBasedAuth.query.all()]
    return jsonify({'usersList': users})

the schema is as shown below

    class TokenBasedAuth(db.Document):
    username = db.StringField()
    password = db.StringField()
    email = db.StringField()
    firstName = db.StringField()
    lastName = db.StringField()

def serialize(g):
    return {
        "_id" : str(g._id),
        "username" : g.username,
        "firstName" : g.firstName,
        "lastName" : g.lastName,
        "password" : g.password,
        "email" : g.email
    }

and the data in db i as shown below

{ 
    "_id" : ObjectId("586a0f01558b6728388161be"), 
    "username" : "sam", 
    "firstName" : "sam", 
    "lastName" : "123", 
    "password" : "123", 
    "email" : "email@123"
}

I am getting error as shown below

AttributeError: 'TokenBasedAuth' object has no attribute 'serialize' // Werkzeug Debugger

Alternate route which is working as expected is as shown below

@authenticate_bp.route('/users/list')
def users_listItr():
    try:
        users =  TokenBasedAuth.query.all()
        formatted_users=[]
        for user in users:
            print user
            formatted_users.append({
                'username':user.username,
                'password':user.password,
                'email':user.email,
                'firstName':user.firstName,
                'lastName':user.lastName

            })
        return json.dumps({'users':formatted_users}),
        200,{'Content-Type':'application/json'}

    except Exception,e:
        return jsonify(status='ERROR',message=str(e))

But this is not a good idea as i am trying built the api for a schema which might contain few thousand documents with much more complex structure please suggest a way to go about it please

Please help in getting the array of objects


回答1:


The easiest way in my opinion is to use a generator on the result set with a function to serialize the result object to valid JSON:

def serialize(row):
    return {
        "_id" : str(row._id),
        "username" : row.username,
        "firstName" : row.firstName,
        "lastName" : row.lastName,
        "password" : row.password,
        "email" : row.email
    } 

@authenticate_bp.route('/users',methods=['GET'])
def user_list():
    users = [serialize(x) for x in TokenBasedAuth.query.all()]
    return jsonify({'usersList': users})

There are some ways you can try to create a custom JSON encoder: See this post. Generally speaking I've found, for Flask, if I need to JSONify something I need to stick to lists and dicts as it is much simpler.



来源:https://stackoverflow.com/questions/41463425/how-to-display-an-array-of-objects-using-python-flask-and-mongoalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!