udemy-graphql/main.py

90 lines
1.8 KiB
Python
Raw Normal View History

2023-12-18 21:42:29 +00:00
from graphene import Schema, ObjectType, String, Int, Field, List, Mutation
2023-12-18 20:36:42 +00:00
2023-12-18 21:42:29 +00:00
class UserType(ObjectType):
id = Int()
name = String()
age = Int()
class CreateUser(Mutation):
class Arguments:
name = String()
age = Int()
user = Field(UserType)
2024-01-11 15:35:32 +00:00
@staticmethod
def mutate(info, name, age):
2023-12-18 21:42:29 +00:00
user = {"id": len(Query.users) + 1, "name": name, "age": age}
Query.users.append(user)
return CreateUser(user=user)
2023-12-18 20:36:42 +00:00
class Query(ObjectType):
2023-12-18 21:42:29 +00:00
user = Field(UserType, user_id=Int())
users_by_min_age = List(UserType, min_age=Int())
users = [
{"id": 1, "name": "Tyrel Souza", "age": 35},
{"id": 2, "name": "Lauren Feldman", "age": 38},
{"id": 3, "name": "Astrid Feldman", "age": 0},
]
@staticmethod
def resolve_user(root, info, user_id):
matched_users = [user for user in Query.users if user["id"] == user_id]
return matched_users[0] if matched_users else None
@staticmethod
def resolve_users_by_min_age(root, info, min_age):
return [user for user in Query.users if user["age"] >= min_age]
2023-12-18 20:36:42 +00:00
2024-01-11 15:35:32 +00:00
class Mutation(ObjectType):
2023-12-18 21:42:29 +00:00
create_user = CreateUser.Field()
2023-12-18 20:36:42 +00:00
2024-01-11 15:35:32 +00:00
class UpdateUser(Mutation):
class Arguments:
name
2023-12-18 21:42:29 +00:00
2024-01-11 15:35:32 +00:00
schema = Schema(query=Query, mutation=Mutation)
2023-12-18 20:36:42 +00:00
gql = """
2023-12-18 21:42:29 +00:00
query {
user(userId: 4) {
id
name
age
}
}
"""
gql2 = """
mutation{
createUser(name: "Jill", age: 61) {
user {
id
name
age
}
}
2023-12-18 20:36:42 +00:00
}
"""
2024-01-11 15:35:32 +00:00
gql3 = """
query {
usersByMinAge(minAge: 0) {
id
name
age
}
}
"""
2023-12-18 20:36:42 +00:00
if __name__ == "__main__":
res = schema.execute(gql)
print(res)
2023-12-18 21:42:29 +00:00
res = schema.execute(gql2)
print(res)
2024-01-11 15:35:32 +00:00
res = schema.execute(gql3)
print(res)