Allows using a Marshmallow Schema directly in a hug input type annotation
| 657 | |
| 658 | |
| 659 | class MarshmallowInputSchema(Type): |
| 660 | """Allows using a Marshmallow Schema directly in a hug input type annotation""" |
| 661 | |
| 662 | __slots__ = "schema" |
| 663 | |
| 664 | def __init__(self, schema): |
| 665 | self.schema = schema |
| 666 | |
| 667 | @property |
| 668 | def __doc__(self): |
| 669 | return self.schema.__doc__ or self.schema.__class__.__name__ |
| 670 | |
| 671 | def __call__(self, value, context): |
| 672 | self.schema.context = context |
| 673 | # In marshmallow 2 schemas return tuple (`data`, `errors`) upon loading. They might also raise on invalid data |
| 674 | # if configured so, but will still return a tuple. |
| 675 | # In marshmallow 3 schemas always raise Validation error on load if input data is invalid and a single |
| 676 | # value `data` is returned. |
| 677 | if MARSHMALLOW_MAJOR_VERSION is None or MARSHMALLOW_MAJOR_VERSION == 2: |
| 678 | value, errors = ( |
| 679 | self.schema.loads(value) if isinstance(value, str) else self.schema.load(value) |
| 680 | ) |
| 681 | else: |
| 682 | errors = {} |
| 683 | try: |
| 684 | value = ( |
| 685 | self.schema.loads(value) if isinstance(value, str) else self.schema.load(value) |
| 686 | ) |
| 687 | except ValidationError as e: |
| 688 | errors = e.messages |
| 689 | |
| 690 | if errors: |
| 691 | raise InvalidTypeData( |
| 692 | "Invalid {0} passed in".format(self.schema.__class__.__name__), errors |
| 693 | ) |
| 694 | return value |
| 695 | |
| 696 | |
| 697 | class MarshmallowReturnSchema(Type): |