对烧瓶应用程序执行后命令时,出现“ TypeError:无法解包不可迭代的用户对象”。 我设法将用户手动添加到数据库。当我尝试使用post端点创建另一个用户时,出现了电子邮件存在的正确验证错误。但是,当我尝试发布一个新的时,出现了错误: TypeError:无法解压缩不可迭代的User对象
我正在使用Python 3.7.4 烧瓶1.1.1 烧瓶棉花糖0.10.1
这是我的模特
class User(db.Model, UserMixin):
__tablename__ = "user"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), index=True, unique=True, nullable=False)
password = db.Column(db.String(128), nullable=False)
stride_account_id = db.Column(db.Integer, db.ForeignKey('stride_account.id'),
nullable=True)
def __repr__(self):
return '<User {} with password {}>'.format(self.email, self.password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def check_password(self, password):
return bcrypt.check_password_hash(self.password, password)
def generate_auth_token(self):
""" Create a jwt token for the user to access the api """
session_exp = datetime.utcnow() + timedelta(minutes=15)
if current_app.config['APP_CONFIG'] != 'config.Production':
session_exp = datetime.utcnow() + timedelta(hours=12)
payload = {
'sub': self.id,
'iat': datetime.utcnow(),
'exp': session_exp
}
token = jwt.encode(payload, current_app.config['SECRET_KEY'])
return token.decode('unicode_escape')
def save(self):
db.session.add(self)
db.session.commit()
这是架构:
class UserSchema(ma.ModelSchema):
email = field_for(User, 'email', required=True,
validate=[
must_not_be_blank,
validate.Email(),
validators.validate_email]
)
password = field_for(User, 'password', required=True,
validate=[
must_not_be_blank,
validators.validate_password]
)
class Meta:
model = User
load_only = ('password',)
我的观点
lass UserView(Resource):
def get(self):
user = User.query.filter(id='1')
return 'Hello World'
@data_required
def post(self):
data = request.get_json()#json.loads(request.data)
print('data is: ', data)
user, errors = serializers.UserSchema().load(data)
print('Hoooraaay')
# user = User(email=data['email'], password=data['password'])
user.set_password(user.password)
user.save()
return serializers.UserSchema().jsonify(user)
完整的错误消息是:
[2019-09-28 17:36:35,465] ERROR in app: Exception on /api/user [POST]
Traceback (most recent call last):
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/ronshteinberg/development/stride-core/app/decorators.py", line 13, in wrapped_view
return view(*args, **kwargs)
File "/Users/ronshteinberg/development/stride-core/app/accounts/views.py", line 20, in post
user, errors = serializers.UserSchema().load(data)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/marshmallow_sqlalchemy/schema.py", line 214, in load
return super().load(data, **kwargs)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/marshmallow/schema.py", line 720, in load
data, many=many, partial=partial, unknown=unknown, postprocess=True
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/marshmallow/schema.py", line 898, in _do_load
raise exc
marshmallow.exceptions.ValidationError: {'email': ['Email already exist']}
127.0.0.1 - - [28/Sep/2019 17:36:35] "POST /api/user HTTP/1.1" 500 -
data is: {'email': 'sssss@aa.com', 'password': 'Qwert12345'}
[2019-09-28 17:36:40,644] ERROR in app: Exception on /api/user [POST]
Traceback (most recent call last):
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask/views.py", line 89, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/ronshteinberg/env/stride/lib/python3.7/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/ronshteinberg/development/stride-core/app/decorators.py", line 13, in wrapped_view
return view(*args, **kwargs)
File "/Users/ronshteinberg/development/stride-core/app/accounts/views.py", line 20, in post
user, errors = serializers.UserSchema().load(data)
TypeError: cannot unpack non-iterable User object
预先感谢
答案 0 :(得分:0)
我发现了问题。 代码是从某个地方复制的,似乎serializers.UserSchema()。load(data)不会返回tupple,只是对象 所以这行应该是:
user = serializers.UserSchema().load(data)
答案 1 :(得分:0)
上述与SO相关且相同的问题:
以前版本的
flask-sqlachemy或长颈瓶棉花糖
load函数返回了2个值
user, errors = serializers.UserSchema().load(data)
在此源代码包中进行了一些更新之后,它开始返回一个值,因此要解决此问题,您需要为响应分配1个值:
user = serializers.UserSchema().load(data)
处理验证错误的正确方法:
try:
obj = schema.load(data)
except ValidationError as error:
print(error.messages)