Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1

前端 未结 4 1566
时光取名叫无心
时光取名叫无心 2021-02-03 10:43

I forked the Flask example, Minitwit, to work with MongoDB and it was working fine on Flask 0.9, but after upgrading to 0.10.1 I get the error in title when I login when I try t

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-03 11:08

    EDIT: Even easier fix. You don't even need to do any JSON encoding/decoding.

    Just save the session['_id'] as a string:

    user = db.minitwit.user.find_one({'username': request.form['username']})
    session['_id'] = str(user['_id'])
    

    And then everywhere you want to do something with the session['_id'] you have to wrap it with ObjectId() so it's passed as a ObjectId object to MongoDB.

    if '_id' in session:
        g.user = db.minitwit.user.find_one({'_id': session['_id']})
    

    to:

    if '_id' in session:
        g.user = db.minitwit.user.find_one({'_id': ObjectId(session['_id'])})
    

    You can see the full diff for the fix on my github repo.

    If anyone cares to know why the 'TypeError: ObjectId('') is not JSON serializable' "issue" appeared in Flask 0.10.1, it's because they changed the way sessions are stored. They are now stored as JSON so since the '_id' object in MongoDB isn't standard JSON, it failed to serialize the session token, thus giving the TypeError. Read about the change here: http://flask.pocoo.org/docs/upgrading/#upgrading-to-010

提交回复
热议问题