简体   繁体   中英

TypeError: Object of type IntegrityError is not JSON serializable

Here i have simple web api to register a user with flask-restful and marshmallow as serializer,

class UserRegistration(Resource):
    def post(self):
        data = request.get_json(force=True)

        if not data:
            return {'message':'No input data provided'}, 400

        data2 = user_schema.load(user_schema.dump(data))
        print('data2')
        print(data2)
        print(data['username'])

        if UserModel.find_by_username(data['username']):
            return {'message': 'User {} already exists'.format(data['username'])}

        print('passed')
        print(UserModel.generate_hash(data['password']))

        new_user = UserModel(
            username = data['username'],
            password = UserModel.generate_hash(data['password']),
            user_role = data['user_role']
        )

        try:
            print('inside try')
            new_user.save_to_db()
            print('passed2')
            return { 'message': 'User {} was created'.format(data['username']) }

        except Exception as e:
            return {'message': 'Something went wrong','error': e}, 500


as i enter the user details through postman like this,

{
 "username":"test2",
 "password":"test2pswd",
 "user_role":"admin"
}

it returns following error on console,

data2
{'user_role': 'admin', 'password': 'test2pswd', 'username': 'test2'}
test2
passed
$pbkdf2-sha256$29000$vZdSak2pNcb4P.dc671XKg$s0ZAL.HcwzNDMs1po2FN4jmyJfGLNHxT9yANs1arZBc
inside try
127.0.0.1 - - [16/Sep/2019 16:27:05] "POST /registration HTTP/1.1" 500 -
.
.
.
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type IntegrityError is not JSON serializable

in UserModel.py class have save_to_db() method,

class UserModel(db.Model):
    __tablename__ = 'users'

    id            = db.Column(db.Integer, primary_key = True)
    username      = db.Column(db.String(120), unique = True, nullable = False)
    password      = db.Column(db.String(120), nullable = False)
    user_role     = db.Column(db.String(10), nullable = False)
    access_token  = db.Column(db.String(120), unique = True, nullable = True, default='as' )
    refresh_token = db.Column(db.String(120), unique = True, nullable = True, default='as' )

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

i was able to save one entry to db, but when the second time it fails with this error, i have no clue what happened with code.

Thanks in advance,

I figured it out,

access_token and refresh_token are set unique = True and set default value to as, so next values having same value to both access_token and refresh_token , because it set unique, it throws IntegrityError .

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