marshmallow-annotations¶
Version 2.4.1 (Change Log)
marshmallow-annotations allows you to create marshmallow schema from classes with annotations on them:
# music.py
from typing import List
class Album:
id: int
name: str
def __init__(self, id: int, name: str):
self.id = id
self.name = name
class Artist:
id: int
name: str
albums: List[Album]
def __init__(self, id: int, name: str, albums: List[Album]):
self.id = id
self.name = name
self.albums = albums
# schema.py
from marshmallow_annotations import AnnotationSchema
from .music import Album, Artist
class AlbumScheme(AnnotationSchema):
class Meta:
target = Album
register_as_scheme = True
class ArtistScheme(AnnotationSchema):
class Meta:
target = Artist
register_as_scheme = True
scheme = ArtistScheme()
scheme.dump(
Artist(
id=1, name="Abominable Putridity",
albums=[
Album(
id=1,
name="The Anomalies of Artificial Origin"
)
]
)
)
# {
# "albums": [
# {
# "id": 1,
# "name": "The Anomalies of Artificial Origin"
# }
# ],
# "id": 1,
# "name": "Abominable Putridity"
# }
Installation¶
marshmallow-annotations is available on pypi and installable with:
pip install marshmallow-annotations
marshmallow-annotations supports Python 3.6+ and marshmallow 2.x.x
Note
If you are install marshmallow-annotations
outside of a virtual
environment, consider installing with
pip install --user marshmallow-annotations
rather than using sudo or
adminstrator privileges to avoid installing it into your system Python.