lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.36k stars 153 forks source link

[FEATURE] Use existing marshmallow schema #484

Open FrankC01 opened 1 year ago

FrankC01 commented 1 year ago

Description

I already have (flask) Schema classes defined:

class UserIn(Schema):
    """Fields for user when requesting a new account in admin."""

    username = fields.Str(
        required=True, validate=validate.Length(min=4, max=254)
    )
    password = fields.Str(
        required=True, validate=validate.Length(min=8, max=16)
    )

I also have a dataclasses_json equivalant:

@dataclass_json
@dataclass
class InUser:
    """New user account dataclass."""

    username: str
    password: str

I want to re-use the UserIn for loading InUser. but it appears InUser.schema() does not take the already defined one?

Am I missing some subtle aspect for this?

Possible solution

No response

Alternatives

To cache the whole thing

_in_user_setup = InUser.schema(UserIn)

And deserializing from dictionary (or json)

new_user:InUser = _in_user_setup.load({...})

Context

No response