TypeError:IntegrityError类型的对象不可JSON序列化

时间:2019-09-16 12:53:14

标签: python flask-sqlalchemy flask-restful

这里我有一个简单的Web API,可以用flask-restfulmarshmallow将用户注册为序列化器,

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


当我这样通过邮递员输入用户详细信息时,

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

它在控制台上返回以下错误,

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

UserModel.py类中具有save_to_db()方法,

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()

我能够将一个条目保存到db,但是第二次由于该错误而失败时,我不知道代码发生了什么。

预先感谢

1 个答案:

答案 0 :(得分:0)

我知道了,

access_tokenrefresh_token设置为unique = True并将默认值设置为as, 因此下一个对access_tokenrefresh_token具有相同值的值,因为它设置为唯一,所以会抛出 IntegrityError