Flask-RESTplus不返回sqlalchemy模型

时间:2018-09-09 20:52:56

标签: python flask sqlalchemy flask-restplus

我的api控制器中包含以下代码:

from flask import jsonify, current_app as app
from flask_restplus import Resource, Api, fields
from sqlalchemy import exc

from ..models.db_models import Book

api = Api(version='1.0', ...)

books = api.namespace('books', description='Database books')

@books.route('/<int:id>')
class Book(Resource):
    model = books.model('Book', {
        'id': fields.Integer,
        'sort': fields.String,
        'pubdate': fields.DateTime,
        'isbn': fields.String
    })
    @books.marshal_with(model)
    def get(self, id):
        return Book.query.filter_by(id = id).first()

这是Book db模型:

class Book(db.Model):
    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    sort = db.Column(db.String(200))
    pubdate = db.Column(db.DateTime)
    isbn = db.Column(db.String(13))

    def __init__(self, id, name, sort):
        self.id = id
        self.name = name
        self.sort = sort

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, {
            key: value
            for key, value in self.__dict__.items()
        })

    def serialize(self, links=False):
        serialize = {
            'id' : self.id,
            'sort' : self.sort,
            'pubdate' : self.pubdate,
            'isbn' : self.isbn
        }
        if links:
            serialize['links'] = [{
                'rel' : 'book',
                'href' : '{}/books/{}/authors'.format(app.config('URL'), self.id)
            }]
        return serialize

由于某些原因,当我尝试从sqlalchemy返回结果时,它将返回Internal Server Error。我很确定我的sqlalchemy模型没有任何问题(连接错误或其他错误),我已经能够在没有Flask-RestPlus的情况下返回对象。谁能指出我正确的方向?

0 个答案:

没有答案