使用RESTfull API作为数据源的石墨烯关系

时间:2018-01-31 11:35:02

标签: django graphql graphene-python

我正在使用django graphene构建graphql服务器,它使用RESTfull API来获取数据,遵循以下模式:

class DeviceType(graphene.ObjectType):
    id = graphene.ID()
    reference = graphene.String()
    serial = graphene.Float()

class InstallationType(graphene.ObjectType):
    id = graphene.ID()
    company = graphene.Int()
    device = graphene.ID()

class AllDataType(graphene.ObjectType):
    device = graphene.Field(DeviceType)
    installation = graphene.Field(InstallationType)

class Query(graphene.ObjectType):
    installation = graphene.Field(
        InstallationType,
        device_id=graphene.Int(required=True)
    )
    all = graphene.Field(
        AllDataType,
        serial=graphene.Float(required=True)
    )

    def resolve_installation(self, info, device_id):
        response = api_call('installations/?device=%s' % device_id)['results'][0]
        return json2obj(json.dumps(response))

    def resolve_all(self, info, serial):
        response = api_call('devices/?serial=%s' % serial)['results'][0]
        return json2obj(json.dumps(response))

我需要做的查询是这样的:

query {
    all(serial:201002000856){
        device{
            id
            serial
            reference
        }
        installation{
            company
            device
        }
    }
}

所以,我的问题是如何与这两种类型建立关系,如AllDataType中所述,resolve_installation需要device idresolve_all需要序列号设备。

要解决安装问题,我需要device id解析器返回的resolve_all

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

resolve_中的Query方法需要返回正确的数据类型,如Query中所定义。例如,resolve_all应返回AllDataType个对象。因此,您需要获取api_call方法的结果来构建AllDataTypeInstallationType个对象。下面是一个示例,其中包含一些从REST获取的数据中获取设备和安装的方法:

def resolve_all(self, info, serial):
    response = api_call('devices/?serial=%s' % serial)['results'][0]
    # need to process the response to get the values you need
    device = get_device_from_response(response)
    installation = get_installation_from_response(response)
    return AllDataType(device=device, installation=installation)

您可能还需要将解析方法添加到Type类中。有一个例子here