用户模型:
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
restaurant = db.Column(db.String(128))
username = db.Column(db.String(128), unique=True)
email = db.Column(db.String(128), unique=True)
active = db.Column(db.Boolean(), default=True)
password = db.Column(db.String(255), nullable=False)
admin = db.Column(db.Boolean, default=False, nullable=False)
created_date = db.Column(db.DateTime, default=func.now())
tracks = db.relationship("Track",
backref=db.backref('user'),
uselist=True)
playlists = db.relationship("Playlist",
backref=db.backref('user'),
uselist=True)
def __init__(self, restaurant, username, email, password):
self.restaurant = restaurant
self.username = username
self.email = email
self.password = bcrypt.generate_password_hash(
password, current_app.config.get('BCRYPT_LOG_ROUNDS')
).decode()
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id': self.id,
'username': self.username,
'email': self.email,
'active': self.active,
'admin': self.admin,
'playlists' : self.playlists,
}
中学:
tracks = db.Table('tracks',
db.Column('track_id', db.Integer, db.ForeignKey('track.id')),
db.Column('playlist_id', db.Integer, db.ForeignKey('playlist.id')))
播放列表模型:
class Playlist(db.Model):
"""
Model for storing playlist information belonging to a specific user
"""
__tablename__ = 'playlist'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
artist = db.Column(db.String(50)) # we always need one for tagging purposes
created = db.Column(db.DateTime, default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
menu_id = db.Column(db.Integer, db.ForeignKey('menu.id'))
consumer_id = db.Column(db.Integer, db.ForeignKey('consumer.id'))
tracks = db.relationship('Track',
secondary=tracks,
backref=db.backref('playlists',
lazy='dynamic'))
def __init__(self, title, user):
self.title = title
self.user = user
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id' : self.id,
'created' : self.created,
'title': self.title,
'artist': self.artist,
'tracks': [ item.serialize() for item in self.tracks]
}
但是当我试图从数据库中获取数据时,就像这样:
from flask import Blueprint, jsonify, request, render_template
from flask_restful import Resource, Api
class UsersList(Resource):
method_decorators = {'post': [authenticate_restful]}
def get(self):
"""Get all users"""
response_object = {
'status': 'success',
'data': {
'users': [user.serialize() for user in User.query.all()]
}
}
return response_object, 200
api.add_resource(UsersList, '/users')
尽管调用了serialize()
,但出现以下错误:
web_1| TypeError: Object of type 'Playlist' is not JSON serializable
完整追溯:
web_1 | 172.18.0.9 - - [30/Apr/2019 19:53:08] "GET /users HTTP/1.0" 500 -
web_1 | Traceback (most recent call last):
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
web_1 | return self.wsgi_app(environ, start_response)
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
web_1 | response = self.handle_exception(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_restful/__init__.py", line 269, in error_router
web_1 | return original_handler(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
web_1 | return cors_after_request(app.make_response(f(*args, **kwargs)))
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
web_1 | reraise(exc_type, exc_value, tb)
web_1 | File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 34, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
web_1 | response = self.full_dispatch_request()
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
web_1 | rv = self.handle_user_exception(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_restful/__init__.py", line 269, in error_router
web_1 | return original_handler(e)
web_1 | File "/usr/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function
web_1 | return cors_after_request(app.make_response(f(*args, **kwargs)))
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
web_1 | reraise(exc_type, exc_value, tb)
web_1 | File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 34, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
web_1 | rv = self.dispatch_request()
web_1 | File "/usr/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
web_1 | return view_func(**req.view_args)
web_1 | File "/usr/lib/python3.6/site-packages/flask_restful/__init__.py", line 462, in wrapper
web_1 | return self.make_response(data, code, headers=headers)
web_1 | File "/usr/lib/python3.6/site-packages/flask_restful/__init__.py", line 491, in make_response
web_1 | resp = self.representations[mediatype](data, *args, **kwargs)
web_1 | File "/usr/lib/python3.6/site-packages/flask_restful/representations/json.py", line 21, in output_json
web_1 | dumped = dumps(data, **settings) + "\n"
web_1 | File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
web_1 | **kw).encode(obj)
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 201, in encode
web_1 | chunks = list(chunks)
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 430, in _iterencode
web_1 | yield from _iterencode_dict(o, _current_indent_level)
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
web_1 | yield from chunks
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
web_1 | yield from chunks
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 325, in _iterencode_list
web_1 | yield from chunks
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 404, in _iterencode_dict
web_1 | yield from chunks
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 325, in _iterencode_list
web_1 | yield from chunks
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 437, in _iterencode
web_1 | o = _default(o)
web_1 | File "/usr/lib/python3.6/json/encoder.py", line 180, in default
web_1 | o.__class__.__name__)
web_1 | TypeError: Object of type 'Playlist' is not JSON serializable
我想念什么?