Skip to content

Instantly share code, notes, and snippets.

@necaris
Created April 24, 2022 21:35
Show Gist options
  • Save necaris/73c5d8bc47b304cdcd97f17c5c729412 to your computer and use it in GitHub Desktop.
Save necaris/73c5d8bc47b304cdcd97f17c5c729412 to your computer and use it in GitHub Desktop.
import typing as T
import json
import uuid
import datetime
import decimal
import pydantic
import graphene
from graphene_pydantic import PydanticInputObjectType, PydanticObjectType
class PersonModel(pydantic.BaseModel):
id: uuid.UUID
first_name: str
last_name: str
age: T.Optional[int]
class Person(PydanticObjectType):
class Meta:
model = PersonModel
# exclude specified fields
exclude_fields = ("id",)
class PersonInput(PydanticInputObjectType):
class Meta:
model = PersonModel
# exclude specified fields
exclude_fields = ("id",)
class CreatePerson(graphene.Mutation):
class Arguments:
person = PersonInput()
Output = Person
@staticmethod
def mutate(parent, info, person):
personModel = PersonModel(
id=uuid.uuid4(),
first_name=person.first_name,
last_name=person.last_name,
age=person.age,
)
# save PersonModel here
return person
class Query(graphene.ObjectType):
people = graphene.List(Person)
@staticmethod
def resolve_people(parent, info):
# fetch actual PersonModels here
return [
PersonModel(id=uuid.uuid4(), first_name="Beth", last_name="Smith", age=99)
]
class Mutation(graphene.ObjectType):
createPerson = CreatePerson.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
mutation = """
mutation {
createPerson(person: {
firstName: "Jerry",
lastName: "Smith",
age: null
}) {
firstName
}
}
"""
result = schema.execute(mutation)
print(result)
print(result.data)
print(result.data["createPerson"])
print(result.data["createPerson"]["firstName"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment