我正在使用kuberentes-python client将查询发送到Kubernetes集群。
我仅使用不带证书的承载令牌来发送API请求。因此,无法验证连接-连接不安全,并且我收到警告:
/usr/local/lib/python3.5/dist-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
我知道如何隐藏这些消息,并且有way to do it。
我在代码中添加了以下几行:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
成功了!我在PyCharm中不再收到警告。
但是,当我从shell python3 myapp.py
运行python代码时,警告仍然存在。
我对此有一种解决方法:export PYTHONWARNINGS="ignore:Unverified HTTPS request"
,但只有在运行脚本之前从外壳程序运行它并且我更喜欢从代码中运行它时,它才有效。
我的问题是为什么PyCharm禁止了警告,而不是从外壳中禁止了警告?
这是我的代码,如果您想对其进行测试(只需更改主机和令牌):
from kubernetes import client
import os
from kubernetes.client import Configuration
SERVICE_TOKEN_FILENAME = "/home/ubuntu/root-token"
class InClusterConfigLoader(object):
def __init__(self, token_filename):
self._token_filename = token_filename
def load_and_set(self):
self._load_config()
self._set_config()
def _load_config(self):
self.host = "https://10.0.62.0:8443"
if not os.path.isfile(self._token_filename):
print("Service token file does not exists.")
with open(self._token_filename) as f:
self.token = f.read().rstrip('\n')
if not self.token:
print("Token file exists but empty.")
def _set_config(self):
configuration = Configuration()
configuration.host = self.host
configuration.ssl_ca_cert = None
configuration.verify_ssl = False
configuration.api_key['authorization'] = "bearer " + self.token
Configuration.set_default(configuration)
def load_incluster_config():
InClusterConfigLoader(token_filename=SERVICE_TOKEN_FILENAME).load_and_set()
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
load_incluster_config()
api = client.CoreV1Api()
service_accounts = api.list_service_account_for_all_namespaces()
print(len(service_accounts.items))