def to_enum(enum_cls, *, type_name=None, **options) -> graphene.Enum: """Create a Graphene enum from a class containing a set of options. :param enum_cls: The class to build the enum from. :param type_name: The name of the type. Default is the class name + 'Enum'. :param options: - description: Contains the type description (default is the class's docstring) - deprecation_reason: Contains the deprecation reason. The default is enum_cls.__deprecation_reason__ or None. :return: """ # note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) PermissionEnum = graphene.Enum("PermissionEnum", permissions.get_permissions_enum_list())
def resolve_get_customer(self, info, **kwargs): result = self.paystack_api.get_customer(**kwargs) return result def resolve_deactivate_card(self, info, **kwargs): return self.paystack_api.deactivate_card(kwargs['authorization_code']) SupportedCurrencyType = utils.createGrapheneInputClass( 'SupportedCurrencyInputType', [('usd', float), ('ngn', float)]) Interval = graphene.Enum('Interval', [ ('hourly', 'hourly'), ('daily', 'daily'), ('weekly', 'weekly'), ('monthly', 'monthly'), ('biannually', 'biannually'), ('annually', 'annually'), ]) SupportedCurrency = graphene.Enum('SupportedCurrency', [ ('ngn', 'ngn'), ('usd', 'usd'), ]) class PlanSubscriptionType(BaseKlass, graphene.ObjectType): create_plan = graphene.Field( PaystackPlanResult, name=graphene.String(required=True), interval=Interval(required=True),
An Enum is a special GraphQL type that represents a set of symbolic names (members) bound to unique, constant values """ import graphene # You can create an Enum using classes class Episode(graphene.Enum): NEWHOPE = 4 EMPIRE = 5 JEDI = 6 # But also using instances of Enum Episode = graphene.Enum('Episode', [('NEWHOPE', 4), ('EMPIRE', 5), ('JEDI', 6)]) # It’s possible to add a description to an enum value, # for that the enum value needs to have the description property on it class Episode(graphene.Enum): NEWHOPE = 4 EMPIRE = 5 JEDI = 6 @property def description(self): if self == Episode.NEWHOPE: return 'New Hope Episode' return 'Other episode'
WebhookEventAsyncType.VOUCHER_DELETED: "A voucher is deleted.", WebhookEventAsyncType.ANY: "All the events.", WebhookEventAsyncType.OBSERVABILITY: "An observability event is created.", } def description(enum): if enum: return WEBHOOK_EVENT_DESCRIPTION.get(enum.value) return "Enum determining type of webhook." WebhookEventTypeEnum = graphene.Enum( "WebhookEventTypeEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in (WebhookEventAsyncType.CHOICES + WebhookEventSyncType.CHOICES)], description=description, ) WebhookEventTypeAsyncEnum = graphene.Enum( "WebhookEventTypeAsyncEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventAsyncType.CHOICES], description=description, ) WebhookEventTypeSyncEnum = graphene.Enum( "WebhookEventTypeSyncEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventSyncType.CHOICES],
import graphene from ...site import AuthenticationBackends from ..core.utils import str_to_enum AuthorizationKeyType = graphene.Enum( 'AuthorizationKeyType', [(str_to_enum(auth_type[0]), auth_type[0]) for auth_type in AuthenticationBackends.BACKENDS])
Contains the deprecation reason. The default is enum_cls.__deprecation_reason__ or None. :return: """ # note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) TaxRateType = graphene.Enum("TaxRateType", [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES]) PermissionEnum = graphene.Enum( "PermissionEnum", [(str_to_enum(codename.split(".")[1]), codename) for codename in MODELS_PERMISSIONS], ) WeightUnitsEnum = graphene.Enum("WeightUnitsEnum", [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES])
def enum_converter(name, enum): content = [(e.name, e.value) for e in enum] return graphene.Enum(name, content)
Examples: * 'answer' == 'question-slug'|answer * 'answer' in 'list-question-slug'|answer * 'answer' in 'table-question-slug'|answer|mapby('column-question') * 'form-slug' == form """ pass serializer_converter.get_graphene_type_from_serializer_field.register( serializers.QuestionJexlField, lambda field: QuestionJexl) ButtonAction = graphene.Enum( "ButtonAction", [(key.upper(), key) for key in models.Question.ACTION_CHOICES], ) ButtonColor = graphene.Enum( "ButtonColor", [(key.upper(), key) for key in models.Question.COLOR_CHOICES], ) serializer_converter.get_graphene_type_from_serializer_field.register( serializers.ButtonActionField, lambda field: ButtonAction) serializer_converter.get_graphene_type_from_serializer_field.register( serializers.ButtonColorField, lambda field: ButtonColor) class Question(Node, graphene.Interface): id = graphene.ID(required=True)
from django.contrib.gis.measure import D import graphene from .geometry import Geometry __all__ = ['Distance'] DistanceUnitEnum = graphene.Enum('DistanceUnitEnum', [(value, value) for value in D.UNITS.keys()]) class Distance(graphene.InputObjectType): unit = DistanceUnitEnum(required=True) value = graphene.Float(required=True) geometry = Geometry(required=True) class Meta: description = """ Distance object type comprising: - The desired `unit` attribute name - Distance `value` - A `geometry` to base calculations from """
import graphene from django.conf import settings LanguageCodeEnum = graphene.Enum( "LanguageCodeEnum", [(lang[0].replace("-", "_").upper(), lang[0]) for lang in settings.LANGUAGES], )
class Meta: model = AdministrativeDivision fields = ("children", "origin_id", "ocd_id", "municipality") type = graphene.String() name = graphene.String() def resolve_children(self, info, **kwargs): return self.children.filter(type__type="sub_district") def resolve_type(self, info, **kwargs): return self.type.type with override("en"): Language = graphene.Enum("Language", [(l[1].upper(), l[0]) for l in settings.LANGUAGES]) ContactMethod = graphene.Enum("ContactMethod", [(cm[1].upper(), cm[0]) for cm in settings.CONTACT_METHODS]) class ProfilesConnection(graphene.Connection): class Meta: abstract = True count = graphene.Int(required=True) total_count = graphene.Int(required=True) def resolve_count(self, info): return self.length
import graphene from ...webhook.event_types import WebhookEventType from ..core.utils import str_to_enum WebhookEventTypeEnum = graphene.Enum( "WebhookEventTypeEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventType.CHOICES], ) WebhookSampleEventTypeEnum = graphene.Enum( "WebhookSampleEventTypeEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventType.CHOICES if e_type[0] != WebhookEventType.ANY], )
# note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) LanguageCodeEnum = graphene.Enum( "LanguageCodeEnum", [(lang[0].replace("-", "_").upper(), lang[0]) for lang in settings.LANGUAGES], ) TaxRateType = graphene.Enum("TaxRateType", [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES]) JobStatusEnum = to_enum(JobStatus) PermissionEnum = graphene.Enum("PermissionEnum", get_permissions_enum_list()) # unit enums MeasurementUnitsEnum = to_enum(MeasurementUnits) DistanceUnitsEnum = to_enum(DistanceUnits) AreaUnitsEnum = to_enum(AreaUnits) VolumeUnitsEnum = to_enum(VolumeUnits)
import graphene from graphene import relay from graphql import GraphQLError from graphql_relay import from_global_id from cars.models import Car, Trim from cars.types import CarNode from .validations import validate_mutation colorType = graphene.Enum('carcolor', Car.COLOR_CHOICES) class CarCreateData(graphene.InputObjectType): owner = graphene.String() color = graphene.InputField(colorType) year = graphene.Int() trim = graphene.ID(required=True) class CarUpdateData(graphene.InputObjectType): owner = graphene.String() color = graphene.InputField(colorType) year = graphene.Int() trim = graphene.ID() class CreateCar(relay.ClientIDMutation): class Input: data = CarCreateData()
from graphene import relay from payments import PaymentStatus from ...order import OrderEvents, OrderEventsEmails, models from ...product.templatetags.product_images import get_thumbnail from ...shipping import models as shipping_models from ..account.types import User from ..core.fields import PrefetchingConnectionField from ..core.types.common import CountableDjangoObjectType from ..core.types.money import Money, TaxedMoney from ..shipping.types import ShippingMethod OrderEventsEnum = graphene.Enum.from_enum(OrderEvents) OrderEventsEmailsEnum = graphene.Enum.from_enum(OrderEventsEmails) PaymentStatusEnum = graphene.Enum('PaymentStatusEnum', [(code.upper(), code) for code, name in PaymentStatus.CHOICES]) class OrderStatusFilter(graphene.Enum): READY_TO_FULFILL = 'READY_TO_FULFILL' READY_TO_CAPTURE = 'READY_TO_CAPTURE' class OrderEvent(CountableDjangoObjectType): date = graphene.types.datetime.DateTime( description='Date when event happened at in ISO 8601 format.') type = OrderEventsEnum(description='Order event type') user = graphene.Field(User, id=graphene.Argument(graphene.ID), description='User who performed the action.')
import graphene from ...checkout import AddressType AddressTypeEnum = graphene.Enum( 'AddressTypeEnum', [(code.upper(), code) for code, name in AddressType.CHOICES]) class StaffMemberStatus(graphene.Enum): ACTIVE = 'active' DEACTIVATED = 'deactivated'
reduced_rates = graphene.List(lambda: ReducedRate, description=dedent(''' Country\'s VAT rate exceptions for specific types of goods.''')) class Meta: description = 'Represents a VAT rate for a country.' def resolve_standard_rate(self, info): return self.data.get('standard_rate') def resolve_reduced_rates(self, info): reduced_rates = self.data.get('reduced_rates', {}) or {} return [ ReducedRate(rate=rate, rate_type=rate_type) for rate_type, rate in reduced_rates.items() ] class ReducedRate(graphene.ObjectType): rate = graphene.Float(description='Reduced VAT rate in percent.', required=True) rate_type = graphene.String(description='A type of goods.', required=True) class Meta: description = dedent(''' Represents a reduced VAT rate for a particular type of goods.''') TaxRateType = graphene.Enum('TaxRateType', [(str_to_enum(rate[0]), rate[0]) for rate in TaxRates.CHOICES])
# note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) LanguageCodeEnum = graphene.Enum( "LanguageCodeEnum", [(lang[0].replace("-", "_").upper(), lang[0]) for lang in settings.LANGUAGES], ) JobStatusEnum = to_enum(JobStatus) PermissionEnum = graphene.Enum("PermissionEnum", get_permissions_enum_list()) TimePeriodTypeEnum = to_enum(TimePeriodType) # unit enums MeasurementUnitsEnum = to_enum(MeasurementUnits) DistanceUnitsEnum = to_enum(DistanceUnits) AreaUnitsEnum = to_enum(AreaUnits) VolumeUnitsEnum = to_enum(VolumeUnits) WeightUnitsEnum = to_enum(WeightUnits) unit_enums = [ DistanceUnitsEnum, AreaUnitsEnum, VolumeUnitsEnum, WeightUnitsEnum
""" Blog GraphQL enums ================== This module defines GraphQL enums associated with models and entities of the blog application. """ import graphene from main.apps.blog.models import RecipePage from main.common.text import replace DISH_TYPES_ENUM_MAPPING = { replace(t[0], (('-', '_'), ('+', '_'))).upper(): t[0] for t in RecipePage.DISH_TYPE_CHOICES } DishType = graphene.Enum('DishType', list(DISH_TYPES_ENUM_MAPPING.items()))
import decimal import graphene import graphene_django_optimizer as gql_optimizer from graphene import relay from graphene.types import Scalar from measurement.measures import Weight from ...core.weight import convert_weight, get_default_weight_unit from ...shipping import ShippingMethodType, models from ..core.types.common import CountableDjangoObjectType, CountryDisplay from ..core.types.money import MoneyRange ShippingMethodTypeEnum = graphene.Enum( 'ShippingMethodTypeEnum', [(code.upper(), code) for code, name in ShippingMethodType.CHOICES]) class ShippingMethod(CountableDjangoObjectType): type = ShippingMethodTypeEnum(description='Type of the shipping method.') class Meta: description = """ Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers.""" model = models.ShippingMethod interfaces = [relay.Node] exclude_fields = ['shipping_zone', 'orders']
import graphene from ...webhook.event_types import WebhookEventType from ..core.utils import str_to_enum WebhookEventTypeEnum = graphene.Enum( "WebhookEventTypeEnum", [(str_to_enum(e_type[0]), e_type[0]) for e_type in WebhookEventType.CHOICES], )
:param enum_cls: The class to build the enum from. :param type_name: The name of the type. Default is the class name + 'Enum'. :param options: - description: Contains the type description (default is the class's docstring) - deprecation_reason: Contains the deprecation reason. The default is enum_cls.__deprecation_reason__ or None. :return: """ # note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) PermissionEnum = graphene.Enum( "PermissionEnum", [(str_to_enum(codename.split(".")[1]), codename) for codename in MODELS_PERMISSIONS], )
""" # note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) # TaxRateType = graphene.Enum( # "TaxRateType", [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES] # ) JobStatusEnum = to_enum(JobStatus) PermissionEnum = graphene.Enum("PermissionEnum", get_permissions_enum_list()) WeightUnitsEnum = graphene.Enum("WeightUnitsEnum", [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES]) AccountErrorCode = graphene.Enum.from_enum( account_error_codes.AccountErrorCode) MetadataErrorCode = graphene.Enum.from_enum(core_error_codes.MetadataErrorCode) OrderErrorCode = graphene.Enum.from_enum(order_error_codes.OrderErrorCode) PermissionGroupErrorCode = graphene.Enum.from_enum( account_error_codes.PermissionGroupErrorCode)
`null` indicates that the error isn't associated with a particular field.""", required=False) message = graphene.String(description='The error message.') class Meta: description = 'Represents an error in the input of a mutation.' class LanguageDisplay(graphene.ObjectType): code = graphene.String(description='Language code.', required=True) language = graphene.String(description='Language.', required=True) PermissionEnum = graphene.Enum('PermissionEnum', [(str_to_enum(codename.split('.')[1]), codename) for codename in MODELS_PERMISSIONS]) class PermissionDisplay(graphene.ObjectType): code = PermissionEnum(description='Internal code for permission.', required=True) name = graphene.String( description='Describe action(s) allowed to do by permission.', required=True) class Meta: description = 'Represents a permission object in a friendly form.' class SeoInput(graphene.InputObjectType):
import graphene from django_countries import countries from ...checkout import AddressType from ...graphql.core.enums import to_enum from ..core.utils import str_to_enum AddressTypeEnum = to_enum(AddressType, type_name="AddressTypeEnum") CountryCodeEnum = graphene.Enum( "CountryCode", [(str_to_enum(country[0]), country[0]) for country in countries] ) class StaffMemberStatus(graphene.Enum): ACTIVE = "active" DEACTIVATED = "deactivated"
import graphene from ...payment import GATEWAYS_ENUM, ChargeStatus from ..core.utils import str_to_enum PaymentChargeStatusEnum = graphene.Enum( 'PaymentChargeStatusEnum', [(str_to_enum(code.upper()), code) for code, name in ChargeStatus.CHOICES]) PaymentGatewayEnum = graphene.Enum.from_enum(GATEWAYS_ENUM) class TaskAction(graphene.Enum): CAPTURE = 'CAPTURE' MARK_AS_PAID = 'MARK_AS_PAID' REFUND = 'REFUND' VOID = 'VOID' @property def description(self): if self == TaskAction.CAPTURE: return 'Represents the capture action.' if self == TaskAction.MARK_AS_PAID: return 'Represents a mark-as-paid action.' if self == TaskAction.REFUND: return 'Represents a refund action.' if self == TaskAction.VOID: return 'Represents a void action.' raise ValueError('Unsupported enum value: %s' % self.value)
'child_node_class', ]) CustomSortOrder = namedtuple('CustomSortOrder', [ 'name', 'value', 'is_asc', ]) SORT_SELECTED_THEMES_SORT_ORDER = 'sort_order' SORT_SELECTED_THEMES_SELECTED_AT_ASC = 'selected_at_asc' SORT_SELECTED_THEMES_SELECTED_AT_DESC = 'selected_at_desc' SelectedThemesSortEnum = graphene.Enum('SelectedThemesSortEnum', [ (SORT_SELECTED_THEMES_SORT_ORDER, SORT_SELECTED_THEMES_SORT_ORDER), (SORT_SELECTED_THEMES_SELECTED_AT_ASC, SORT_SELECTED_THEMES_SELECTED_AT_ASC), (SORT_SELECTED_THEMES_SELECTED_AT_DESC, SORT_SELECTED_THEMES_SELECTED_AT_DESC), ]) class ProductReview(graphene.ObjectType): reviewer_name = graphene.String() review_score = graphene.Int() def build_product_reviews_cached(model_with_prof_reviews): if not hasattr(model_with_prof_reviews, '_product_reviews_cache'): if model_with_prof_reviews.prof_reviews: try: model_with_prof_reviews._product_reviews_cache = [
class Arguments: id = graphene.Int(required=True) status = graphene.Enum(PaymentStatus)
:return: """ # note this won't work until # https://github.com/graphql-python/graphene/issues/956 is fixed deprecation_reason = getattr(enum_cls, "__deprecation_reason__", None) if deprecation_reason: options.setdefault("deprecation_reason", deprecation_reason) type_name = type_name or (enum_cls.__name__ + "Enum") enum_data = [(str_to_enum(code.upper()), code) for code, name in enum_cls.CHOICES] return graphene.Enum(type_name, enum_data, **options) TaxRateType = graphene.Enum( "TaxRateType", [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES] ) PermissionEnum = graphene.Enum("PermissionEnum", get_permissions_enum_list()) WeightUnitsEnum = graphene.Enum( "WeightUnitsEnum", [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES] ) AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode) CheckoutErrorCode = graphene.Enum.from_enum(checkout_error_codes.CheckoutErrorCode) ExtensionsErrorCode = graphene.Enum.from_enum( extensions_error_codes.ExtensionsErrorCode
from enum import Enum class Episode(graphene.Enum): NEWHOPE = 4 EMPIRE = 5 JEDI = 6 @property def description(self): if self == Episode.NEWHOPE: return 'New Hope Episode' return 'Other episode' Season = graphene.Enum('Season', [('SPRING', 3), ('SUMMER', 5), ('FALL', 8), ('WINTER', 11)]) class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 def colordescription(value): return f'This is the color {value}.' graphene.Enum.from_enum(Color, colordescription) # Python style enum member access