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'])

Jignasha Royala
  • 1,087
  • 10
  • 23
Ndurere David
  • 98
  • 1
  • 7

4 Answers4

10

You can assign the member names to it:

fields.String(description='The object type', enum=EnumGender._member_names_)
Kobi Dadon
  • 116
  • 1
  • 5
  • 1
    Is it possible to use a enum.IntEnum with fields.Integer? – hygorxaraujo Aug 24 '18 at 01:29
  • [Docs](https://docs.python.org/3/library/enum.html#iteration) 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. – tutuca Jan 30 '19 at 19:13
  • For me __members__items() throws unserializable error, although _member_names_ is protected but it works. – smishra Mar 21 '19 at 13:22
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?)

peterrus
  • 662
  • 2
  • 6
  • 16
0

Another possibility, Python 3.7.3 (circa Nov 2019):

fields.String(description="The object type",
              enum=[x.name for x in EnumGender])
Joe Marley
  • 129
  • 4
0

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"

andilabs
  • 18,598
  • 13
  • 98
  • 133