正在创建一个 flask_restful
API与 sqlalchemy
和 marshmallow
.这是我的模型
class User(db.Model):
"""Basic user model
"""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
active = db.Column(db.Boolean, default=True)
is_admin = db.Column(db.Boolean, default=False)
profile = db.relationship("Profile", back_populates="user", uselist=False)
class Profile(db.Model):
"""Profile model
"""
id = db.Column(db.Integer, primary_key=True)
fullname = db.Column(db.String(80), unique=False, nullable=True)
img_url = db.Column(db.String(255), unique=False, nullable=True)
telephone = db.Column(db.String(20), unique=False, nullable=True)
user_id = db.Column(
db.Integer,
db.ForeignKey('user.id'),
nullable=False)
user = db.relationship("User", back_populates="profile")
和这里的用户资源更新 PUT
请求
class UserResource(Resource):
def put(self, user_id):
schema = UserSchema()
user = User.query.get_or_404(user_id)
data = {
'username': 'updated',
"password": 'HRcdxRu45',
'email': '[email protected]',
'profile': {
'telephone': '+2507800112233',
'fullname': 'Mic Lolo',
'img_url': 'images/img.jpg'
}
}
user = schema.load(data, instance=user)
return {"message": "user updated", "data": schema.dump(user)}
这是我的模式
class ProfileSchema(ma.Schema):
id = ma.Int(dump_only=True)
fullname = ma.Str(validate=Length(min=3, max=80, error='empty fullname'))
img_url = ma.Str(validate=Length(min=3, max=80, error='empty image url'))
telephone = ma.Str(validate=Regexp(regex=r"\+[0-9]{7,13}", error="Invalid phone number"))
class Meta:
model = Profile
sqla_session = db.session
class UserSchema(ma.ModelSchema):
id = ma.Int(dump_only=True)
password = ma.Str(load_only=True,
validate=Length(min=8, max=255, error='empty password'))
username = ma.Str(validate=Length(min=3, max=80, error='empty username'))
is_admin = ma.Bool()
email = ma.Email()
profile = ma.Nested(ProfileSchema)
class Meta:
model = User
sqla_session = db.session
越来越AttributeError: 'dict' 对象没有属性 '_sa_instance_state' 。
当我将嵌套的配置文件模式从 UserSchema
万无一失 user.profile
不会被更新。此外,当我删除 instance=user
中的参数 schema.load(data, instance=user)
没有错误,而且我将得到一个有发布数据的用户实例,问题是该用户实例和数据库中现有的用户实例之间没有任何联系,我将不得不手动找到要更新的用户字段。
class ProfileSchema(ma.Schema):
ProfileSchema
应该继承自 ma.ModelSchema