如何解决使用GraphQL在Python中过滤JSON数据
我在python项目中使用的是官方graphene
软件包。我有一个巨大的嵌套JSON数据,这些数据来自运行中的Docker容器检查命令,我想从中获取一些字段。我可以分别选择所有这些字段,然后将它们添加到字典中,如下所示:
def ContainerConfigs(configs):
data = {}
data['Command'] = configs['Args'][-1]
data['Hostname'] = configs['Config']['Hostname']
data['Image'] = configs['Config']['Image']
data['distro'] = configs['Config']['Labels']['org.label-schema.name']
data['workdir'] = configs['Config']['WorkingDir']
data['IPAddress'] = configs['NetworkSettings']['Networks']['bridge']['IPAddress']
return data
但这是一个很弱的解决方案。我认为可以使用GraphQL对其进行优化。没有服务器,请求和响应。我想创建其Schema
类并发送参数(JSON和Query),然后让该函数执行该查询并返回结果。像这样:
import graphene
# I need to find this part of the code
# class Schema(..):
# ...
# class Query(...):
# ...
def ContainerConfigs(configs,query):
schema = graphene.Schema(query=Query)
# I need to find a way to pass the configs (Json data) to the Query class to
# execute the query_string on the data
query_string = """
query {
Args
Config {
Hostname
Image
WorkingDir
Label{
org.label-schema.name
}
}
NetworkSettings{
Networks{
bridge{
IPAddress
}
}
}
}
"""
result = schema.execute(query_string)
return result
解决方法
这不是一个很好的技术匹配:您将以GraphQL语法重新创建很多Docker API,并且在查询后仍具有相同的嵌套字典布局。
原则上,您可以编写具有与Docker API相同布局的GraphQL模式。该架构为必需;没有它,您将无法执行GraphQL查询,但这基本上涉及在源代码中复制整个Docker API对象模型。这里要注意的另一件事是,对GraphQL查询的响应具有与查询相同的“形状”(例如,请参见graphql.org上的Execution页)。
如果您完成了所有这些工作,并且运行了所显示的GraphQL查询,则会收到类似“嵌套字典”的响应
result = schema.execute(query_string)
hostname = result.data['Config']['Hostname']
这并没有比您现有的更好。 (同样,请参见石墨烯Execution文档页面上的示例。)
如果您要提取这些数据并将其封装在某种对象中,则可以创建一个类来为您执行此操作。我可能会这样写:
from collections import namedtuple
class ContainerConfigs(namedtuple('ContainerConfigs',['command','hostname',...])):
@classmethod
def from_docker_inspect(cls,configs):
return cls(
command=configs['Args'][-1],hostname=configs['Config']['Hostname'],...
)
info = ContainerConfigs.from_docker_inspect(configs)
print(f"container hostname (not generally useful): {info.hostname}")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。