简体   繁体   中英

Flask & MongoDB (mLab) TypeError: ObjectId('5bf0b6ce397b3635dc0b10ab') is not JSON serializable

I'm building a Flask-based web application, and within my database helper class, i have a create_user() function which works fine if the line reads as follows:

users.insert({'user': email, 'password': hashpass})

However when I change it to:

users.insert({'email': email, 'password': hashpass})

I get the following error:

TypeError: ObjectId('5bf0b6ce397b3635dc0b10ab') is not JSON serializable

Database helper class

import bcrypt

class DBHelper:

def __init__(self, mongo):
    self.mongo = mongo

def create_user(self, email, password):
    users = self.mongo.db.users
    hashpass = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    users.insert({'email': email, 'password': hashpass})

Flask code

@app.route("/account")
@login_required
def account():
    return render_template("home.html", options=options, questions=questions)
    return "You are logged in"


@app.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        stored_user = DB.get_user(request.form['email'])

        if stored_user is None:
            DB.create_user(request.form['email'], request.form['pass'])
            #session['username'] = request.form['username']
            user = User(DB.get_user(request.form['email']))
            login_user(user)
            return redirect(url_for('account'))

        return 'That username already exists!'

return render_template('register.html')

The problem was with the below code:

user = User(DB.get_user(request.form['email']))
login_user(user)

I was passing a dictionary to the User class, as opposed to an email address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM