Python Flask RestPlus枚举类型

时间:2018-01-20 12:03:54

标签: python flask enums flask-restplus

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

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

我选择了这种方法:

select v.*, f.*,
       (f.w_coeff * v.w + f.h_coeff * v.h + f.d_coeff * v.d + f.constant)
from (values (1, 2, 3)) v(w, h, d) cross join
     formulas f;

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

在我的情况下具有这样的枚举:

from enum import Enum


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

我需要像这样的元帅定义:

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

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