marshmallow-code / webargs

A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp.
https://webargs.readthedocs.io/
MIT License
1.38k stars 158 forks source link

[Question] How to set up the Schema that will validate against a list of allowed enum values? #748

Closed simkimsia closed 2 years ago

simkimsia commented 2 years ago
class ConvertCPOPToVQPSchema(Schema):
    """
    Schema for Convert CPOP to VQP Schema
    """
    currency = fields.Str(required=True) # how do i validate this against a list of allowed enum values?

# https://webargs.readthedocs.io/en/latest/framework_support.html#django
@parser.use_args(ConvertCPOPToVQPSchema(unknown=EXCLUDE), location="form")
@ensure_csrf_cookie
@require_http_methods(["POST"])
def convert_post(request, pk, request_args):
     .....

So I want the currency to only allow values of ['USD', 'GBP', 'EUR'] and disallow everything else.

How do I do that?

sirosen commented 2 years ago

You probably want a OneOf validator: https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html#marshmallow.validate.OneOf

e.g.

import marshmallow as ma

class FooSchema(ma.Schema):
    bar = ma.fields.String(validate=ma.validate.OneOf(["fizz", "buzz"]))

print(FooSchema().load({"bar": "fizz"}))
print(FooSchema().load({"bar": "uhoh"}))

I think this is a pretty straightforward "yes, marshmallow supports that" case, so I'm going to close it. 🙂