6

Am using python 3.4. I have created an enum type as shown below:

import enum
class EnumGender(enum.Enum):
    blank = ' '
    female = 'Female'
    male = 'Male'
    other = 'Other'

my question is how do i assign it to flask-restplus field as the only examples i can see are:

fields.String(description='The object type', enum=['A', 'B'])

2
  • What's your intent here? Are you looking to use the enum field for validation, just for added typing or some other reason? Commented Jan 20, 2018 at 20:21
  • For those in need of enums, consider choices=... github.com/noirbizarre/flask-restplus/issues/124 Commented Jan 30, 2020 at 17:25

4 Answers 4

10

You can assign the member names to it:

fields.String(description='The object type', enum=EnumGender._member_names_)
Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to use a enum.IntEnum with fields.Integer?
Docs tell me that there is no Enum._member_names_ but there is Enum.__members__ which is a view. So you'll have to do fields.String(description='The object type', enum=EnumGender.__members__.items()). A little verbose.
For me _members__items() throws unserializable error, although _member_names is protected but it works.
4

I have opted for this approach:

fields.String(attribute=lambda x: str(EnumGender(x.FieldContainingEnum).name))

(Source: How to get back name of the enum element in python?)

Comments

1

in my case having enum like this:

from enum import Enum


class SubscriptionEvent(Enum):
    on_success = "ON_SUCCESS"
    on_error = "ON_ERROR"

I needed definition in marshal like this:

subscription_action_serializer = api.model('SubscriptionAction', {
    'event': fields.String(enum=[x.value for x in SubscriptionEvent], attribute='event.value'),
})

I needed just accept and present as valid enum values "ON_SUCCESS", "ON_SUCCESS"

Comments

0

Another possibility, Python 3.7.3 (circa Nov 2019):

fields.String(description="The object type",
              enum=[x.name for x in EnumGender])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.