首页 > 解决方案 > 石墨烯:如何为不同的解析器共享 InputObjectType?

问题描述

当输入变量对所有解析器都等效时,我不想多次定义输入变量。我怎样才能做到这一点?

import graphene


class GeoInput(graphene.InputObjectType):
    lat = graphene.Float(required=True)
    lng = graphene.Float(required=True)

    @property
    def latlng(self):
        return "({},{})".format(self.lat, self.lng)


class Address(graphene.ObjectType):
    latlng = graphene.String()


class Test(graphene.ObjectType):
    test_string = graphene.String()


class Query(graphene.ObjectType):
    address = graphene.Field(Address, geo=GeoInput(required=True))
    test = graphene.Field(Test, geo=GeoInput(required=True))

    def resolve_address(self, info, geo):
        return Address(latlng=geo.latlng)

    def resolve_test(self, info, geo):
        return Test(test_string="({},{})".format(geo.lat, geo.lng))

schema = graphene.Schema(query=Query)
query = """
    query something{
      address(geo: {lat:32.2, lng:12}) {
        latlng
      }
      test(geo: {lat:32.2, lng:12}) {
        testString
      }
    }
"""

if __name__ == "__main__":
    result = schema.execute(query)
print(result.data["address"]["latlng"],
      result.data["test"]["testString"])

有没有办法为整个查询类做这件事,比如初始化变量?

标签: pythongraphqlgraphene-python

解决方案


推荐阅读