Why it is possible to suppress InsecureRequestWarning from within the code with PyCharm and not from a shell

3/27/2019

I am using kuberentes-python client to send queries to Kubernetes cluster.

I am using only a bearer token without certificate to send the API requests. Therefore, the connection cannot be verified - insecure connection and I am getting warnings:

/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)

I know how to suppress these messages and there is a way to do it.

I added in the code the following lines:

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

It worked ! I don't get the warnings anymore in PyCharm.
But when I ran the python code from the shell python3 myapp.py, the warning were still exist.

I have a workaround for that: export PYTHONWARNINGS="ignore:Unverified HTTPS request" but it works only if you run it from the shell before running the script and I preferred it to be from the code.
My questions is why the warnings were suppressed with PyCharm but not from the shell ?

This is my code if you want to test it (just change the host and token):

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))
-- E235
kubernetes
pycharm
python
suppress-warnings
urllib3

0 Answers