Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String field should support case transform #1724

Closed
b0urb0n opened this issue Jan 21, 2021 · 1 comment
Closed

String field should support case transform #1724

b0urb0n opened this issue Jan 21, 2021 · 1 comment

Comments

@b0urb0n
Copy link

b0urb0n commented Jan 21, 2021

I would like the ability to define a marshmallow.fields.String that supports case transformation during (de)serialization.

Sometimes I've found it necessary to convert input/output to uppercase and lowercase. Most commonly, I convert all hash digests to lowercase regardless of the case I get from a user.

I generally solve this with something simple:

class StringLower(fields.String):
    """
    A ``marshmallow.field.String`` that is converted to lowercase
    """
    case = 'lower'

    def _deserialize(self, value, attr, data, **kwargs) -> AnyStr:
        try:
            return getattr(value, self.case)()
        except AttributeError as e:
            raise fields.ValidationError("Input must be a string") from e

    def _serialize(self, value, attr, obj, **kwargs) -> AnyStr:
        try:
            return getattr(value, self.case)()
        except AttributeError as e:
            raise fields.ValidationError("Input must be a string") from e


class StringUpper(StringLower):
    """
    A ``marshmallow.field.String`` that is converted to uppercase
    """
    case = 'upper'

It would be nice to be able to define a String field that did this automatically:

class SomeSchema(Schema):
    upper_str = fields.String(transform='upper')
    lower_str = fields.String(transform='lower')
@sloria
Copy link
Member

sloria commented Mar 2, 2021

I don't think this needs to be added to core. You can use custom fields or even write wrapper fields. See here for an example.

@sloria sloria closed this as completed Mar 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants