簡體   English   中英

在 Marshmallow 的 HATEOAS 序列化過程中如何處理一對多關系?

[英]How to handle one-to-many relationship during HATEOAS serialization in Marshmallow?

嘗試使用 HATEOAS 資源鏈接在 Python(SQLAlchemy + Marshmallow)中實現一個相當簡單的 REST API,我在嘗試為一對多關系創建“智能超鏈接”時遇到困難。

讓我們考慮經典的書籍示例:一本書只有一個出版商,但有 1 到 n 個作者。 為簡單起見,在我的用例中,如果每個作者都能寫本書就足夠了。 我的 class 結構可能如下所示:

models/book.py

class Book(db.Model):

    __tablename__ = 'book'
    book_id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    publisher_id = db.Column('publisher_id', db.Integer, db.ForeignKey('publisher.publisher_id'))
    authors = db.relationship('Author', back_populates='book_id')
 
    # some more methods ...

    @staticmethod
    def get_by_id(book_id):
        return Book.query.get(book_id)

models/author.py

class Author(db.Model):

    __tablename__ = 'author'

    author_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    book_id = db.Column('book_id', db.Integer, db.ForeignKey('book.book_id'))
    booking = db.relationship('Book', back_populates='authors')

    # some more methods ..

    @staticmethod
    def get_by_id(author_id):
        return Authors.query.get(author_id)

models/book_schema.py

class BookSchema(ma.SQLAlchemyAutoSchema):

    class Meta:
        model = Book

    book_id=fields.Integer()
    title = fields.String()

    # Smart hyperlinking
    _links = ma.Hyperlinks(
        {
            "self": {"href": ma.AbsoluteURLFor("book", book_id="<booking_id>")},
            "publisher": {"href": ma.AbsoluteURLFor("publishers", publisher_id="<publisher_id>")},
            "authors": {"href": ma.AbsoluteURLFor("authors", author_id="<authors>")} #!!!
        }
    )

app/__init__.py


def create_app(config_name):

    #...

    api.add_resource(Book, '/books/<int:book_id>', endpoint='books')

    #...

book_schema.py中用#!!!表示的行是惹麻煩的。 我明白, authors是一個集合,因此沒有單一author_id 但是我還沒有找到任何方法將這個集合添加到超鏈接中。

在查詢一本書時,我想得到什么,比方說, /books/123看起來像這樣:

{
    "book_id": 123,
    "title": "How to think of a good book title"
    "_links": {
        "publisher": {
            "href": "https://localhost:5000/publishers/4711"
        },
        "authors": [
            { "href": "https://localhost:5000/authors/42" },
            { "href": "https://localhost:5000/authors/333" },
            { "href": "https://localhost:5000/authors/1337" }
        ]
    }
}

關於除一對多關系之外的所有其他關系,它工作得很好。 發布者關系也按預期填充。 我還可以驗證一本書的作者是否從數據庫中正確加載(通過在Book類的get_by_id中調試)。

此外,我發現了這個 GitHub 問題,如果我做對了,它也可以解決我的問題。

所以,最后,我的問題是:有什么辦法可以實現集合序列化嗎? 如果不是通過 Marshmallow 的標准方式(我在那里沒有找到任何東西),那么也許在將響應發送到客戶端之前通過任何合理的后處理方式?

非常感謝!

class Book(db.Model):
    __tablename__ = 'book'
    book_id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    publisher_id = db.Column('publisher_id', db.Integer, db.ForeignKey('publisher.publisher_id'))
    authors = db.relationship('Author', back_populates='book_id')
 
    # some more methods ...

    @staticmethod
    def get_by_id(book_id):
        return Book.query.get(book_id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM