fuhrysteve / marshmallow-jsonschema

JSON Schema Draft v7 (http://json-schema.org/) formatting with marshmallow
MIT License
209 stars 72 forks source link

Pass marshmallow context into nested schemas? #138

Closed ghostwheel42 closed 2 years ago

ghostwheel42 commented 3 years ago

Hi,

I'm using a marshmallow context to alter serialization and de-serialization of many schemas (see example below). Would it be possible to include the context of the parent schema when creating nested schemas?

https://github.com/fuhrysteve/marshmallow-jsonschema/blob/4a74842df9aff46e321d259d5129709bd1069c84/marshmallow_jsonschema/base.py#L292

Using nested_instance = nested(only=only, exclude=exclude, context=obj.context) would do just fine.

Alex

from pprint import pprint
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

class UserSchema(Schema):

    def __init__(self, *args, **kwargs):
        if kwargs.get('context', {}).get('hide', False):
            kwargs.setdefault('exclude', []).append('birthday')
        super().__init__(*args, **kwargs)

    username = fields.String()
    age = fields.Integer()
    birthday = fields.Date()

user_schema = UserSchema()
json_schema = JSONSchema()
pprint(json_schema.dump(user_schema))

context = {
    'hide': True,
}
user_schema = UserSchema(context=context)
pprint(json_schema.dump(user_schema))
ghostwheel42 commented 3 years ago

Hi @fuhrysteve. Would it be possible to include this small change or is there another way to achieve what I want to do? I can create a PR if you like.

Alex

fuhrysteve commented 3 years ago

Pull requests are welcome! Thanks!