How to parse enums by value from query parameters using webargs?

1.3k views Asked by At

I have the next enum:

class EStatus(enum.IntEnum):
    NEW = 0
    MODIFIED = 1

And schema:

ARGS = {
    'status': EnumField(EStatus, by_value=True, required=False)
}

After in Flask I declared GET-method with webargs:

@use_args(ARGS, location='query')
def get(self, args: Dict[str, any]):
    return []

And it fails with error:

{'messages': {'query': {'status': ['Invalid enum value 1']}}, 'schema': <GeneratedSchema(many=False)>, 'headers': None}

I've checked it in debugger and found that EnumField calls EStatus(value). The problem is that my value is str type because of it's from query parameters.

How to make to EnumField cast it to int before call EStatus(value)?

1

There are 1 answers

0
Riyas On BEST ANSWER
class EStatus(enum.IntEnum):
    NEW = 0
    MODIFIED = 1

  @staticmethod
    def from_str(e_status: str):
        e_status = e_status.upper()
        if e_status in EStatus.__members__:
            return EStatus[e_status]
        else:
            raise ValueError(f'{e_status} is not a valid EStatus.')

#You can use above from_str like below,
EStatus e_status = EStatus.from_str('NEW')
print(e_status.name)
print(e_status.value)

Hopefully for your problem you should be able to convert str to Enum type using from_str staticmethod.