如何过滤/后处理Python-Graphene结果

时间:2019-05-10 09:43:02

标签: python graphql graphene-python

我目前正在使用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()))

0 个答案:

没有答案
相关问题