使用Graphene返回具有字符串值的枚举列表

2024-09-29 23:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这是使用Python和Graphene库

我想通过GraphQL向前端提供一个常量列表。我使用了inspection,但它只输出枚举的键。不是价值观。我了解到石墨烯枚举只包含名称/描述

    {
      __type(name: "FruitEnum") {
        enumValues {
          name
          description
        }
      }
    }

这是回报

{
  "data": {
    "__type": {
      "enumValues": [
        {
          "name": "APPLE",
          "description": null
        },
        {
          "name": "BANANA",
          "description": null
        },
        {
          "name": "ORANGE",
          "description": null
        }
      ]
    }
  },
  "errors": null
}

这就是实际枚举的样子

class FruitEnum(Enum):
    APPLE = "Apple -- but could also be other information for the front end"
    BANANA = "Banana"
    ORANGE = "Orange"

有没有更好的方法通过GraphQL公开这样的常量列表?可以用解析器修改内省以读取值吗?我正在使用enum.from_enum函数获取一个常规Python枚举并向Graphene注册它


Tags: nameapple列表typeenumdescriptiongraphqlnull
2条回答

我认为您不会从enumValues添加或删除字段,因为它是标准的

但是,您可以通过在enum类中指定descriptionproperty来添加描述

import graphene

from enum import Enum as PyEnum


class FruitEnum(PyEnum):
    APPLE = "Apple"
    BANANA = "Banana"
    ORANGE = "Orange"

    def get_field_description(self):
        mapper = {
            "default": "default description",
            "APPLE": "Apple description"
        }
        return mapper.get(self.name, mapper['default'])

    @property
    def description(self):
        return self.get_field_description()


class FruitType(graphene.ObjectType):
    foo = graphene.Enum.from_enum(FruitEnum)()

因此,您将得到如下响应:

{
  "data": {
    "__type": {
      "name": "FruitEnum",
      "enumValues": [
        {
          "name": "APPLE",
          "description": "Apple description"
        },
        {
          "name": "BANANA",
          "description": "default description"
        },
        {
          "name": "ORANGE",
          "description": "default description"
        }
      ]
    }
  }
}

使用Django,您可以简单地编写:

from django.db import models

from django.utils.translation import gettext_lazy as _   # Provides a convenient way to translate your descriptions

class FruitEnum(models.TextChoices):
    APPLE = "Apple", _('Apple description goes here')
    BANANA = "Banana", _('Banana description goes here')
    ORANGE = "Orange", _('Orange description goes here')

因此,您将得到如下响应:

{
  "data": {
    "__type": {
      "name": "FruitEnum",
      "enumValues": [
        {
          "name": "APPLE",
          "description": "Apple description goes here"
        },
        {
          "name": "BANANA",
          "description": "Banana description goes here"
        },
        {
          "name": "ORANGE",
          "description": "Orange description goes here"
        }
      ]
    }
  }
}

相关问题 更多 >

    热门问题