Kubernetes Python客户端从代理动词以单引号而不是双引号的字符串形式返回pod的JSON HTTP响应

时间:2019-04-25 13:09:58

标签: json kubernetes proxy kubernetes-python-client

我正在通过Kubernetes API代理动词从pod的Web服务器请求一些JSON数据。那就是:

corev1 = kubernetes.client.CoreV1Api()
res = corev1.connect_get_namespaced_pod_proxy_with_path(
    'mypod:5000', 'default', path='somepath', path2='somepath')
print(type(res))
print(res)

调用成功,并返回一个str,其中包含来自pod的Web服务的序列化JSON数据。不幸的是,res现在看起来像这样……根本不是有效的JSON,因此json.loads(res)拒绝对其进行解析:

{'x': [{'xx': 'xxx', ...

如您所见,字符串化的响应看起来像Python字典,而不是有效的JSON。关于如何安全地转换回正确的JSON或正确的Python dict的任何建议?

2 个答案:

答案 0 :(得分:1)

在阅读了Kubernetes Python客户端的一些代码之后,现在很清楚connect_get_namespaced_pod_proxy()connect_get_namespaced_pod_proxy_with_path()通过调用将来自远程API调用的响应主体转换为str self.api_client.call_api(..., response_type='str', ...)core_v1_api.py)。因此,我们受困于Kubernetes API客户端,它仅向我们提供表示原始JSON响应正文的dict()的字符串表示形式。

要将字符串转换回dict()anwer to Convert a String representation of a Dictionary to a dictionary?建议使用ast.literal_eval()。想知道这是否是明智的选择,我发现answer to Is it a best practice to use python ast library for operations like converting string to dict说这是明智的选择。

import ast
corev1 = kubernetes.client.CoreV1Api()
res = corev1.connect_get_namespaced_pod_proxy_with_path(
    'mypod:5000', 'default', path='somepath', path2='somepath')
json_res = ast.literal_eval(res)

答案 1 :(得分:0)

我在Pod上执行时遇到了类似的问题,并找到了解决方案。 我想它也可能对您有用。

  1. 将参数_preload_content = False添加到流调用中->您将收到WSClient对象
  2. 对其调用run_forever(timeout = 10)
  3. 然后使用.read_stdout()获得正确且无格式的字符串

例如:

wsclient_obj = stream(v1.connect_get_namespaced_pod_exec, m
                    y_name,
                    'default',
                    command=['/bin/sh', '-c', 'echo $MY_VAR'],
                    stderr=True,
                    stdin=False,
                    stdout=True,
                    tty=False,
                    _preload_content=False
                )
wsclient_obj.run_forever(timeout=10)
response_str = wsclient_obj.read_stdout()

之后json.loads(response_str)将起作用:)