File: index.rst

package info (click to toggle)
python-flask-marshmallow 0.14.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 360 kB
  • sloc: python: 867; makefile: 145; sh: 17
file content (257 lines) | stat: -rw-r--r-- 7,710 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
*********************************************************
Flask-Marshmallow: Flask + marshmallow for beautiful APIs
*********************************************************

:ref:`changelog <changelog>` //
`github <http://github.com/marshmallow-code/flask-marshmallow>`_ //
`pypi <http://pypi.python.org/pypi/flask-marshmallow>`_ //
`issues <http://github.com/marshmallow-code/flask-marshmallow/issues>`_


Flask + marshmallow for beautiful APIs
======================================

Flask-Marshmallow is a thin integration layer for `Flask`_ (a Python web framework) and `marshmallow`_ (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_.

Get it now
----------
::

    pip install flask-marshmallow


Create your app.

.. code-block:: python

    from flask import Flask
    from flask_marshmallow import Marshmallow

    app = Flask(__name__)
    ma = Marshmallow(app)

Write your models.

.. code-block:: python

    from your_orm import Model, Column, Integer, String, DateTime


    class User(Model):
        email = Column(String)
        password = Column(String)
        date_created = Column(DateTime, auto_now_add=True)


Define your output format with marshmallow.

.. code-block:: python


    class UserSchema(ma.Schema):
        class Meta:
            # Fields to expose
            fields = ("email", "date_created", "_links")

        # Smart hyperlinking
        _links = ma.Hyperlinks(
            {
                "self": ma.URLFor("user_detail", values=dict(id="<id>")),
                "collection": ma.URLFor("users"),
            }
        )


    user_schema = UserSchema()
    users_schema = UserSchema(many=True)


Output the data in your views.

.. code-block:: python

    @app.route("/api/users/")
    def users():
        all_users = User.all()
        return users_schema.dump(all_users)


    @app.route("/api/users/<id>")
    def user_detail(id):
        user = User.get(id)
        return user_schema.dump(user)


    # {
    #     "email": "fred@queen.com",
    #     "date_created": "Fri, 25 Apr 2014 06:02:56 -0000",
    #     "_links": {
    #         "self": "/api/users/42",
    #         "collection": "/api/users/"
    #     }
    # }



Optional Flask-SQLAlchemy Integration
-------------------------------------

Flask-Marshmallow includes useful extras for integrating with `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_ and `marshmallow-sqlalchemy <https://marshmallow-sqlalchemy.readthedocs.io>`_.

To enable SQLAlchemy integration, make sure that both Flask-SQLAlchemy and marshmallow-sqlalchemy are installed.  ::

    pip install -U flask-sqlalchemy marshmallow-sqlalchemy

Next, initialize the `~flask_sqlalchemy.SQLAlchemy` and `~flask_marshmallow.Marshmallow` extensions, in that order.

.. code-block:: python

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_marshmallow import Marshmallow

    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test.db"

    # Order matters: Initialize SQLAlchemy before Marshmallow
    db = SQLAlchemy(app)
    ma = Marshmallow(app)

.. admonition:: Note on initialization order

    Flask-SQLAlchemy **must** be initialized before Flask-Marshmallow.


Declare your models like normal.


.. code-block:: python

    class Author(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(255))


    class Book(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(255))
        author_id = db.Column(db.Integer, db.ForeignKey("author.id"))
        author = db.relationship("Author", backref="books")


Generate marshmallow `Schemas <marshmallow.Schema>` from your models using `~flask_marshmallow.sqla.SQLAlchemySchema` or `~flask_marshmallow.sqla.SQLAlchemyAutoSchema`.

.. code-block:: python

    class AuthorSchema(ma.SQLAlchemySchema):
        class Meta:
            model = Author

        id = ma.auto_field()
        name = ma.auto_field()
        books = ma.auto_field()


    class BookSchema(ma.SQLAlchemyAutoSchema):
        class Meta:
            model = Book
            include_fk = True

You can now use your schema to dump and load your ORM objects.


.. code-block:: python

    db.create_all()
    author_schema = AuthorSchema()
    book_schema = BookSchema()
    author = Author(name="Chuck Paluhniuk")
    book = Book(title="Fight Club", author=author)
    db.session.add(author)
    db.session.add(book)
    db.session.commit()
    author_schema.dump(author)
    # {'id': 1, 'name': 'Chuck Paluhniuk', 'books': [1]}


`~flask_marshmallow.sqla.SQLAlchemySchema` is nearly identical in API to `marshmallow_sqlalchemy.SQLAlchemySchema` with the following exceptions:

- By default, `~flask_marshmallow.sqla.SQLAlchemySchema` uses the scoped session created by Flask-SQLAlchemy.
- `~flask_marshmallow.sqla.SQLAlchemySchema` subclasses `flask_marshmallow.Schema`, so it includes the `~flask_marshmallow.Schema.jsonify` method.
Note: By default, Flask's `jsonify` method sorts the list of keys and returns consistent results to ensure that external HTTP caches aren't trashed. As a side effect, this will override `ordered=True <https://marshmallow.readthedocs.io/en/latest/quickstart.html#ordering-output>`_ 
in the SQLAlchemySchema's `class Meta` (if you set it). To disable this, set `JSON_SORT_KEYS=False` in your Flask app config. In production it's recommended to let `jsonify` sort the keys and not set `ordered=True` in your `~flask_marshmallow.sqla.SQLAlchemySchema` in order to minimize generation time and maximize cacheability of the results.

You can also use `ma.HyperlinkRelated <flask_marshmallow.sqla.HyperlinkRelated>` fields if you want relationships to be represented by hyperlinks rather than primary keys.


.. code-block:: python

    class BookSchema(ma.SQLAlchemyAutoSchema):
        class Meta:
            model = Book

        author = ma.HyperlinkRelated("author_detail")

.. code-block:: python

    with app.test_request_context():
        print(book_schema.dump(book))
    # {'id': 1, 'title': 'Fight Club', 'author': '/authors/1'}

The first argument to the `~flask_marshmallow.sqla.HyperlinkRelated` constructor is the name of the view used to generate the URL, just as you would pass it to the `~flask.url_for` function. If your models and views use the ``id`` attribute
as a primary key, you're done; otherwise, you must specify the name of the
attribute used as the primary key.

To represent a one-to-many relationship, wrap the `~flask_marshmallow.sqla.HyperlinkRelated` instance in a `marshmallow.fields.List` field, like this:

.. code-block:: python

    class AuthorSchema(ma.SQLAlchemyAutoSchema):
        class Meta:
            model = Author

        books = ma.List(ma.HyperlinkRelated("book_detail"))

.. code-block:: python

    with app.test_request_context():
        print(author_schema.dump(author))
    # {'id': 1, 'name': 'Chuck Paluhniuk', 'books': ['/books/1']}


API
===

.. automodule:: flask_marshmallow
    :members:

.. automodule:: flask_marshmallow.fields
    :members:

.. automodule:: flask_marshmallow.sqla
    :members:


Useful Links
============

- `Flask docs`_
- `marshmallow docs`_

.. _marshmallow docs: http://marshmallow.readthedocs.io

.. _Flask docs: http://flask.pocoo.org/docs/

Project Info
============

.. toctree::
   :maxdepth: 1

   license
   changelog


.. _marshmallow: http://marshmallow.readthedocs.io

 .. _Flask: http://flask.pocoo.org