Search code examples
regexflaskpeeweemarshmallowflask-peewee

How could double validation be added in marshmallow "fields"?(PeeWee)


I send requests to a RESTful API. Also I have a PeeWee model to keep the responses. I check the validations with Marshmallow.

In the response body, there is a variable that is not certain data type(Integer or String). I want my PeeWee model have multiple validation.

Here is the example:

class Example(Schema):
    availableLimit = fields.Str(
        required=False, allow_none=True, validate=validate.Regexp(REGEX.NUMBER_LARGE)
    )

In the API response, availableLimit have exactly 2 possibilities: the string "UNLIMITED" or any Integer. How can I validate it with the Marshmallow fields validation like validate=validate.Regexp(REGEX.NUMBER_LARGE && REGEX.UNLIMITED_STRING)?

Additionally REGEX.NUMBER_LARGE and REGEX.UNLIMITED_STRING are my patterns.


Solution

  • I think you can import post_dump from marshmallow. You can then use post_dump as a decorator method in your schema class.

    eg

    from marshmallow import ValidationError, post_dump
    class Example(Schema):
        availableLimit = fields.Str(required=False, allow_none=True,validate=validate.Regexp(REGEX.NUMBER_LARGE))
        @post_dump('availableLimit')
        def multiple_validation(self, value):
            ....
    

    I hope this is clear