|
| 1 | +import typing as T |
| 2 | +import uuid |
| 3 | +import datetime |
| 4 | +import decimal |
| 5 | +import enum |
| 6 | +import inspect |
| 7 | + |
| 8 | +from graphene import Field, Boolean, Dynamic, Enum, Float, Int, List, String, UUID, Union |
| 9 | +from graphene.types.base import BaseType |
| 10 | +try: |
| 11 | + from graphene.types.decimal import Decimal as GrapheneDecimal |
| 12 | + DECIMAL_SUPPORTED = True |
| 13 | +except ImportError: |
| 14 | + # graphene 2.1.5+ is required for Decimals |
| 15 | + DECIMAL_SUPPORTED = False |
| 16 | + |
| 17 | +from graphene.types.datetime import Date, Time, DateTime |
| 18 | +from pydantic import fields |
| 19 | + |
| 20 | +from .registry import Registry |
| 21 | + |
| 22 | + |
| 23 | +class ConversionError(TypeError): |
| 24 | + pass |
| 25 | + |
| 26 | + |
| 27 | +# Placeholder for NoneType, so that we can easily reference it later |
| 28 | +TYPE_NONE = type(None) |
| 29 | + |
| 30 | + |
| 31 | +def get_attr_resolver(attr_name: str) -> T.Callable: |
| 32 | + """ |
| 33 | + Return a helper function that resolves a field with the given name by |
| 34 | + looking it up as an attribute of the type we're trying to resolve it on. |
| 35 | + """ |
| 36 | + def _get_field(root, _info): |
| 37 | + return getattr(root, attr_name, None) |
| 38 | + return _get_field |
| 39 | + |
| 40 | + |
| 41 | +def convert_pydantic_field(field: fields.Field, registry: Registry, **field_kwargs) -> Field: |
| 42 | + """ |
| 43 | + Convert a Pydantic model field into a Graphene type field that we can add |
| 44 | + to the generated Graphene data model type. |
| 45 | + """ |
| 46 | + declared_type = getattr(field, "type_", None) |
| 47 | + field_kwargs.setdefault( |
| 48 | + "type", convert_pydantic_type(declared_type, field, registry) |
| 49 | + ) |
| 50 | + field_kwargs.setdefault("required", field.required) |
| 51 | + field_kwargs.setdefault("default_value", field.default) |
| 52 | + # TODO: find a better way to get a field's description. Some ideas include: |
| 53 | + # - hunt down the description from the field's schema, or the schema |
| 54 | + # from the field's base model |
| 55 | + # - maybe even (Sphinx-style) parse attribute documentation |
| 56 | + field_kwargs.setdefault("description", field.__doc__) |
| 57 | + |
| 58 | + return Field(resolver=get_attr_resolver(field.name), **field_kwargs) |
| 59 | + |
| 60 | + |
| 61 | +def to_graphene_type(type_: T.Type, field: fields.Field, registry: Registry = None) -> BaseType: # noqa: C901 |
| 62 | + """ |
| 63 | + Map a native Python type to a Graphene-supported Field type, where possible. |
| 64 | + """ |
| 65 | + if type_ == uuid.UUID: |
| 66 | + return UUID |
| 67 | + elif type_ in (str, bytes): |
| 68 | + return String |
| 69 | + elif type_ == datetime.datetime: |
| 70 | + return DateTime |
| 71 | + elif type_ == datetime.date: |
| 72 | + return Date |
| 73 | + elif type_ == datetime.time: |
| 74 | + return Time |
| 75 | + elif type_ == bool: |
| 76 | + return Boolean |
| 77 | + elif type_ == float: |
| 78 | + return Float |
| 79 | + elif type_ == decimal.Decimal: |
| 80 | + return GrapheneDecimal if DECIMAL_SUPPORTED else Float |
| 81 | + elif type_ == int: |
| 82 | + return Int |
| 83 | + elif type_ in (tuple, list, set): |
| 84 | + # TODO: do Sets really belong here? |
| 85 | + return List |
| 86 | + elif hasattr(type_, '__origin__'): |
| 87 | + return convert_generic_type(type_, field, registry) |
| 88 | + elif issubclass(type_, enum.Enum): |
| 89 | + return Enum.from_enum(type_) |
| 90 | + elif registry and registry.get_type_for_model(type_): |
| 91 | + return registry.get_type_for_model(type_) |
| 92 | + elif inspect.isfunction(type_): |
| 93 | + # TODO: this may result in false positives? |
| 94 | + return Dynamic(type_) |
| 95 | + else: |
| 96 | + raise Exception( |
| 97 | + f"Don't know how to convert the Pydantic field {field!r} ({field.type_})" |
| 98 | + ) |
| 99 | + |
| 100 | + |
| 101 | +def convert_pydantic_type(type_: T.Type, field: fields.Field, registry: Registry = None) -> BaseType: # noqa: C901 |
| 102 | + """ |
| 103 | + Convert a Pydantic type to a Graphene Field type, including not just the |
| 104 | + native Python type but any additional metadata (e.g. shape) that Pydantic |
| 105 | + knows about. |
| 106 | + """ |
| 107 | + graphene_type = to_graphene_type(type_, field, registry) |
| 108 | + if field.shape == fields.Shape.SINGLETON: |
| 109 | + return graphene_type |
| 110 | + elif field.shape in (fields.Shape.LIST, fields.Shape.TUPLE, fields.Shape.SEQUENCE, fields.Shape.SET): |
| 111 | + # TODO: _should_ Sets remain here? |
| 112 | + return List(graphene_type) |
| 113 | + elif field.shape == fields.Shape.MAPPING: |
| 114 | + raise ConversionError(f"Don't know how to handle mappings in Graphene.") |
| 115 | + |
| 116 | + |
| 117 | +def convert_generic_type(type_, field, registry=None): |
| 118 | + """ |
| 119 | + Convert annotated Python generic types into the most appropriate Graphene |
| 120 | + Field type -- e.g. turn `typing.Union` into a Graphene Union. |
| 121 | + """ |
| 122 | + origin = type_.__origin__ |
| 123 | + if not origin: |
| 124 | + raise ConversionError(f"Don't know how to convert type {type_!r} ({field})") |
| 125 | + # NOTE: This is a little clumsy, but working with generic types is; it's hard to |
| 126 | + # decide whether the origin type is a subtype of, say, T.Iterable since typical |
| 127 | + # Python functions like `isinstance()` don't work |
| 128 | + if origin == T.Union: |
| 129 | + return convert_union_type(type_, field, registry) |
| 130 | + elif origin in (T.Dict, T.OrderedDict, T.Mapping): |
| 131 | + raise ConversionError("Don't know how to handle mappings in Graphene") |
| 132 | + elif origin in (T.List, T.Set, T.Collection, T.Iterable): |
| 133 | + return List(to_graphene_type(type_, field, registry)) |
| 134 | + else: |
| 135 | + raise ConversionError(f"Don't know how to handle {type_} (generic: {origin})") |
| 136 | + |
| 137 | + |
| 138 | +def convert_union_type(type_, field, registry=None): |
| 139 | + """ |
| 140 | + Convert an annotated Python Union type into a Graphene Union. |
| 141 | + """ |
| 142 | + wrapped_types = type_.__args__ |
| 143 | + # NOTE: a typing.Optional decomposes to a Union[None, T], so we can return |
| 144 | + # the Graphene type for T; Pydantic will have already parsed it as optional |
| 145 | + if len(wrapped_types) == 2 and TYPE_NONE in wrapped_types: |
| 146 | + native_type = next(x for x in wrapped_types if x != TYPE_NONE) |
| 147 | + graphene_type = to_graphene_type(native_type, field, registry) |
| 148 | + return graphene_type |
| 149 | + else: |
| 150 | + # Otherwise, we use a little metaprogramming -- create our own unique |
| 151 | + # subclass of graphene.Union that knows its constituent Graphene types |
| 152 | + graphene_types = tuple(to_graphene_type(x, field, registry) for x in wrapped_types) |
| 153 | + internal_meta = type("Meta", (), {'types': graphene_types}) |
| 154 | + |
| 155 | + union_class_name = "".join(x.__name__ for x in wrapped_types) |
| 156 | + union_class = type(f"Union_{union_class_name}", (Union,), {'Meta': internal_meta}) |
| 157 | + return union_class |
0 commit comments