我目前正在使用 Python-Graphene 编写 GraphQL API。
一个解析器提供了一个条目列表,我想在这里进行一些后处理/过滤。然而,子条目的属性此时尚未解析,当然稍后会解析。
我能做什么?尝试返回一个 Promise 并绑定到它的“then”方法,或者编写一个中间件。它全部给出了“未处理的”子条目,即没有解析的数据。做了一些研究,如果我可以在某些隐藏的数据结构中找到数据,但 pysnooper 证明此时根本没有计算数据。
请注意:我在这个项目中没有使用 Django。 这是我尝试做的一个最小示例,请注意 TODO 行。
""" Test some graphene features"""
import graphene
from collections import namedtuple
from datetime import date
from json import dumps
DBUser = namedtuple('DBUser', ('name', 'year_of_birth'))
# Our, ehm, professional database ;-)
DATABASE = [
DBUser('John', 1970),
DBUser('Mary', 1980),
DBUser('Sandra', 1990),
DBUser('Michael', 2000),
]
class User(graphene.ObjectType):
name = graphene.String()
age = graphene.Int()
def resolve_name(self, info):
return self.name
def resolve_age(self, info):
return date.today().year - self.year_of_birth
class Query(graphene.ObjectType):
users = graphene.List(
User,
min_age=graphene.Int())
def resolve_users(self, info, min_age):
for dbuser in DATABASE:
# TODO: Would like to use computed "age" of User here somehow
if dbuser.year_of_birth < 1989:
yield dbuser
schema = graphene.Schema(query=Query)
query = "query { users(minAge: 30) { name age } }"
result = schema.execute(request_string=query)
print(dumps(result.to_dict()))
这正是我写这篇文章的原因之一
pydantic-resolve
添加
post_field
方法
class Person(BaseModel):
name: str
age: int = 0
def resolve_age(self, loader=LD(batch_person_age_loader)):
return loader.load(self.name)
is_adult: bool = False
def post_is_adult(self):
return self.age > 18
这个
post_method
钩子在所有后代都被解析后被调用。