Я пытаюсь создать объект ассоциации UserRelationship
, который определяет отношения "follow" между User
и User
.Когда я взаимодействую с этим объектом через оболочку, он ведет себя так, как я ожидал, но при реализации в функции маршрута он создает `TypeError: объект типа UserRelationship не является JSON serializable '
class UserRelationship(db.Model):
follows_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
bank = db.Column(db.String(100))
follows = db.relationship('User', backref=db.backref('followers'))
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
follows = db.relationship('UserRelationship', backref=db.backref('followers', lazy=True))
Это приводит к ожидаемым результатамв оболочке:
user1=User(username='joe')
user2=User(username='paul')
user3=User(username='phil')
new_follow = UserRelationship(follows=user2, bank='1000')
new_follow2 = UserRelationship(follows=user3, bank='1000')
user2.follows.append(new_follow)
user2.follows.append(new_follow2)
db.session.commit()
user2.follows
>>[<UserRelationship (transient 2627038264968)>, <UserRelationship (transient 2627038286344)>]
user2.follows[0].bank
'1000'
user2.follows[0].follows
<User Paul>
Однако, когда у меня это на самом деле есть в моем приложении Flask, оно запускает ошибку:
`TypeError: Объект типа UserRelationship не является сериализуемым JSON '
Вот как я пытаюсь реализовать настоящее приложение:
@app.route('/follow/<to_follow>', methods=['GET', 'POST'])
@login_required
def follow(to_follow):
follow_target = User.query.filter_by(username=to_follow).first()
form = FollowForm()
if form.validate_on_submit():
new_follow = UserRelationship(bank='1000', follows=follow_target)
current_user.follows.append(new_follow)
db.session.commit()
flash(current_user.follows)
return redirect(profile)
return render_template('follow.html',
title=f'Follow {to_follow}',
form=form,
to_follow=follow_target)
Полный возврат:
Traceback (most recent call last):
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 1969, in finalize_request
response = self.process_response(response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 2268, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type UserRelationship is not JSON serializable
[2019-09-29 16:10:38,924] ERROR in app: Request finalizing failed with an error while handling an error
Traceback (most recent call last):
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 1969, in finalize_request
response = self.process_response(response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 2268, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type UserRelationship is not JSON serializable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 1969, in finalize_request
response = self.process_response(response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\app.py", line 2268, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\sessions.py", line 378, in save_session
val = self.get_signing_serializer(app).dumps(dict(session))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 166, in dumps
payload = want_bytes(self.dump_payload(obj))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\url_safe.py", line 42, in dump_payload
json = super(URLSafeSerializerMixin, self).dump_payload(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\itsdangerous\serializer.py", line 133, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\tag.py", line 305, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\phill\anaconda3\envs\zigenv\lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "c:\users\phill\anaconda3\envs\zigenv\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type UserRelationship is not JSON serializable