[英]Kubernetes REST API call using python
我正在尋找一種通過名稱查找pod並使用python運行REST調用的方法。 我想到了使用端口轉發和kubernetes客戶端
有人可以共享代碼示例或其他任何方式嗎?
這是我開始做的事情:
from kubernetes import client, config
config.load_kube_config(config_file="my file") client = client.CoreV1Api()
pods = client.list_namespaced_pod(namespace="my namespace") # loop pods to
#find my pod
接下來,我想到了使用:
stream(client.connect_get_namespaced_pod_portforward_with_http_info ...
在kubectl命令行工具中,我執行以下操作:1.列出容器2.打開端口轉發3.使用curl執行REST調用
我想在python中做同樣的事情
列出所有豆莢:
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
然后在上面的for循環中,您可以檢查您的廣告連播名稱,如果匹配則返回。
使用kubernetes API調用pod的方式與Kubernetes或Like容器非常不同。 您正在將微服務(或服務)與部署技術結合在一起。 您應該配置服務,並使用標准的Python調用Rest API來調用它。
如果你是從集群內部呼叫使用的服務名稱為URL域名如果你是從外面群集使用群集IP例如使用泊塢窗調用的http://本地主機:8000 /代碼相同的不同ARG,請確保配置該服務可正確將端口暴露在外部。
像這樣:
#!/usr/bin/env python
import sys
import json
import requests
def call_service(outside_call=True, protocol='http', domain='localhost', service_name='whisperer', service_port='8002', index='hello', payload=None, headers=None):
if outside_call:
url = f'{protocol}://{domain}:{service_port}/{index}'
else:
url = f'{protocol}://{service_name}:{service_port}/{index}'
try:
g = requests.get(url=url)
print(f'a is: {g}')
r = requests.post(f'{url}', data=json.dumps(payload), headers=headers)
print(f'The text returned from the server: {r.text}')
return r.text
# return json.loads(r.content)
except Exception as e:
raise Exception(f"Error occurred while trying to call service: {e}")
if __name__ == "__main__":
args = sys.argv
l = len(args)
if l > 1:
outside_call = True if args[1] == 'true' else False
else:
outside_call = False
a = call_service(payload={'key': 'value'}, outside_call=outside_call)
print(f'a is: {a}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.