Python Flask RestPlus 枚举类型

Python Flask RestPlus Enum Type

我正在使用 python 3.4. 我创建了一个 enum 类型,如下所示:

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

我的问题是如何将它分配给 flask-restplus 字段,因为我能看到的唯一示例是:

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

您可以为其分配成员名称:

fields.String(description='The object type', enum=EnumGender._member_names_)

我选择了这种方法:

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

(来源:How to get back name of the enum element in python?

另一种可能性,Python 3.7.3(大约 2019 年 11 月):

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

在我的例子中有这样的枚举:

from enum import Enum


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

我需要像这样在 marshal 中定义:

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

我只需要接受并呈现为有效的枚举值 "ON_SUCCESS", "ON_SUCCESS"