當前位置: 首頁>>代碼示例>>Python>>正文


Python client.Client類代碼示例

本文整理匯總了Python中docker.client.Client的典型用法代碼示例。如果您正苦於以下問題:Python Client類的具體用法?Python Client怎麽用?Python Client使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Client類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_update_headers

    def test_update_headers(self):
        sample_headers = {
            'X-Docker-Locale': 'en-US',
        }

        def f(self, headers=None):
            return headers

        client = Client()
        client._auth_configs = {}

        g = update_headers(f)
        assert g(client, headers=None) is None
        assert g(client, headers={}) == {}
        assert g(client, headers={'Content-type': 'application/json'}) == {
            'Content-type': 'application/json',
        }

        client._auth_configs = {
            'HttpHeaders': sample_headers
        }

        assert g(client, headers=None) == sample_headers
        assert g(client, headers={}) == sample_headers
        assert g(client, headers={'Content-type': 'application/json'}) == {
            'Content-type': 'application/json',
            'X-Docker-Locale': 'en-US',
        }
開發者ID:vagouzhou,項目名稱:docker-py,代碼行數:28,代碼來源:utils_test.py

示例2: download_docker_image

def download_docker_image(docker_image, target_file, cache=None):
	try:
		from docker.client import Client
		from docker.utils import kwargs_from_env
		kwargs = kwargs_from_env()
		kwargs['tls'].assert_hostname = False
		docker_cli = Client(**kwargs)
		image = docker_cli.get_image(docker_image)
		image_tar = open(target_file,'w')
		image_tar.write(image.data)
		image_tar.close()
	except Exception as e:
		if cache is not None:
			cached_file = os.path.join(cache, docker_image.lower().replace('/','-').replace(':','-') + '.tgz')
			if os.path.isfile(cached_file):
				print 'using cached version of', docker_image
				urllib.urlretrieve(cached_file, target_file)
				return
			print >> sys.stderr, docker_image, 'not found in cache', cache
			sys.exit(1)
		if isinstance(e, KeyError):
			print >> sys.stderr, 'docker not configured on this machine (or environment variables are not properly set)'
		else:
			print >> sys.stderr, docker_image, 'not found on local machine'
			print >> sys.stderr, 'you must either pull the image, or download it and use the --docker-cache option'
		sys.exit(1)
開發者ID:pombredanne,項目名稱:tile-generator,代碼行數:26,代碼來源:build.py

示例3: docker_context

def docker_context():
    """Make a docker context"""
    host = os.environ.get('DOCKER_HOST')
    cert_path = os.environ.get('DOCKER_CERT_PATH')
    tls_verify = os.environ.get('DOCKER_TLS_VERIFY')

    options = {"timeout": 60}
    if host:
        options['base_url'] = (host.replace('tcp://', 'https://') if tls_verify else host)

    if tls_verify and cert_path:
        options['tls'] = docker.tls.TLSConfig(
              verify = True
            , ca_cert = os.path.join(cert_path, 'ca.pem')
            , client_cert = (os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem'))
            , ssl_version = ssl.PROTOCOL_TLSv1
            , assert_hostname = False
            )

    client = DockerClient(**options)
    try:
        info = client.info()
        log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
    except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
        raise BadDockerConnection(base_url=options['base_url'], error=error)
    return client
開發者ID:CaseyLeask,項目名稱:harpoon,代碼行數:26,代碼來源:executor.py

示例4: __init__

    def __init__(self):
        config = self._load_config()

        self.REDIS_HOST = config['redis_host']
        self.PYWB_HOST = config['pywb_host']
        self.C_EXPIRE_TIME = config['container_expire_secs']
        self.Q_EXPIRE_TIME = config['queue_expire_secs']
        self.REMOVE_EXP_TIME = config['remove_expired_secs']
        self.VERSION = config['api_version']

        self.VNC_PORT = config['vnc_port']
        self.CMD_PORT = config['cmd_port']

        self.image_prefix = config['image_prefix']
        self.browsers = config['browsers']

        self.redis = redis.StrictRedis(host=self.REDIS_HOST)

        self.redis.setnx('next_client', '1')

        if os.path.exists('/var/run/docker.sock'):
            self.cli = Client(base_url='unix://var/run/docker.sock',
                              version=self.VERSION)
        else:
            kwargs = kwargs_from_env()
            kwargs['tls'].assert_hostname = False
            kwargs['version'] = self.VERSION
            self.cli = Client(**kwargs)
開發者ID:pombredanne,項目名稱:netcapsule,代碼行數:28,代碼來源:main.py

示例5: run

    def run(self,
            ssl_env_name='STUNNEL_SSL'):
        """
           Run a container scan for a variable containing a certificate env dictionary

            Args:
                ssl_env_name(string): The string containing the certificate env
        """
        cli = Client(base_url='unix://var/run/docker.sock')
        for container in cli.containers():
          container_details = cli.inspect_container(container.get('Id'))
          container_envs = container_details.get('Config').get('Env')
          env_ssl = [ env for env in container_envs if ssl_env_name in env]
          if len(env_ssl) > 0:
            env_cert = env_ssl[0].split('=', 1)[1]
            env_json = json.loads(env_cert)
            raw_ssl = env_json.get('cert')
            cert = c.load_certificate(c.FILETYPE_PEM, raw_ssl)
            not_after = cert.get_notAfter()
            not_after_date = self.get_cert_time(not_after)
            has_expired = cert.has_expired()
            signature_algorithm = cert.get_signature_algorithm()
            self.logger.info("Found stunnel container envs", 
                             extra={'notAfter': '{}'.format(not_after),
                                    'notAfterDate': '{}'.format(not_after_date),
                                    'hasExpired': '{}'.format(has_expired),
                                    'containerId': '{}'.format(container.get('Id')),
                                    'signatureAlgorithm': '{}'.format(signature_algorithm)})
開發者ID:ministryofjustice,項目名稱:logstash-formula,代碼行數:28,代碼來源:stunnel_scanner.py

示例6: __init__

    def __init__(self):
        config = self._load_config()

        self.LOCAL_REDIS_HOST = "netcapsule_redis_1"
        self.REDIS_HOST = os.environ.get("REDIS_HOST", self.LOCAL_REDIS_HOST)
        self.PYWB_HOST = os.environ.get("PYWB_HOST", "netcapsule_pywb_1")
        self.C_EXPIRE_TIME = config["init_container_expire_secs"]
        self.Q_EXPIRE_TIME = config["queue_expire_secs"]
        self.REMOVE_EXP_TIME = config["remove_expired_secs"]
        self.VERSION = config["api_version"]

        self.VNC_PORT = config["vnc_port"]
        self.CMD_PORT = config["cmd_port"]

        self.MAX_CONT = config["max_containers"]

        self.image_prefix = config["image_prefix"]

        self.browser_list = config["browsers"]
        self.browser_paths = {}

        for browser in self.browser_list:
            path = browser["path"]
            if path in self.browser_paths:
                raise Exception("Already a browser for path {0}".format(path))

            self.browser_paths[path] = browser

        self.default_browser = config["default_browser"]
        self.redirect_paths = config["redirect_paths"]

        self.randompages = []
        try:
            with open(config["random_page_file"]) as fh:
                self.randompages = list([line.rstrip() for line in fh])
        except Exception as e:
            print(e)

        self.redis = redis.StrictRedis(host=self.REDIS_HOST)

        self.redis.setnx("next_client", "1")
        self.redis.setnx("max_containers", self.MAX_CONT)

        throttle_samples = config["throttle_samples"]
        self.redis.setnx("throttle_samples", throttle_samples)

        throttle_max_avg = config["throttle_max_avg"]
        self.redis.setnx("throttle_max_avg", throttle_max_avg)

        self.redis.setnx("container_expire_secs", config["full_container_expire_secs"])

        self.T_EXPIRE_TIME = config["throttle_expire_secs"]

        if os.path.exists("/var/run/docker.sock"):
            self.cli = Client(base_url="unix://var/run/docker.sock", version=self.VERSION)
        else:
            kwargs = kwargs_from_env(assert_hostname=False)
            kwargs["version"] = self.VERSION
            self.cli = Client(**kwargs)
開發者ID:sunfun,項目名稱:netcapsule,代碼行數:59,代碼來源:main.py

示例7: download_docker_image

def download_docker_image(docker_image, target_file):
	from docker.client import Client
	from docker.utils import kwargs_from_env
	kwargs = kwargs_from_env()
	kwargs['tls'].assert_hostname = False
	docker_cli = Client(**kwargs)
	image = docker_cli.get_image(docker_image)
	image_tar = open(target_file,'w')
	image_tar.write(image.data)
	image_tar.close()
開發者ID:frodenas,項目名稱:tile-generator,代碼行數:10,代碼來源:build.py

示例8: __init__

    def __init__(self):
        config = self._load_config()

        self.LOCAL_REDIS_HOST = 'netcapsule_redis_1'
        self.REDIS_HOST = os.environ.get('REDIS_HOST', self.LOCAL_REDIS_HOST)
        self.PYWB_HOST = os.environ.get('PYWB_HOST', 'netcapsule_pywb_1')
        self.C_EXPIRE_TIME = config['init_container_expire_secs']
        self.Q_EXPIRE_TIME = config['queue_expire_secs']
        self.REMOVE_EXP_TIME = config['remove_expired_secs']
        self.VERSION = config['api_version']

        self.VNC_PORT = config['vnc_port']
        self.CMD_PORT = config['cmd_port']

        self.MAX_CONT = config['max_containers']

        self.image_prefix = config['image_prefix']

        self.browser_list = config['browsers']
        self.browser_paths = {}

        for browser in self.browser_list:
            path = browser['path']
            if path in self.browser_paths:
                raise Exception('Already a browser for path {0}'.format(path))

            self.browser_paths[path] = browser

        self.default_browser = config['default_browser']
        self.redirect_paths = config['redirect_paths']

        self.redis = redis.StrictRedis(host=self.REDIS_HOST)

        self.redis.setnx('next_client', '1')
        self.redis.setnx('max_containers', self.MAX_CONT)

        throttle_samples = config['throttle_samples']
        self.redis.setnx('throttle_samples', throttle_samples)

        throttle_max_avg = config['throttle_max_avg']
        self.redis.setnx('throttle_max_avg', throttle_max_avg)

        self.redis.setnx('container_expire_secs',
                         config['full_container_expire_secs'])

        self.T_EXPIRE_TIME = config['throttle_expire_secs']

        if os.path.exists('/var/run/docker.sock'):
            self.cli = Client(base_url='unix://var/run/docker.sock',
                              version=self.VERSION)
        else:
            kwargs = kwargs_from_env(assert_hostname=False)
            kwargs['version'] = self.VERSION
            self.cli = Client(**kwargs)
開發者ID:GovanifY,項目名稱:netcapsule,代碼行數:54,代碼來源:main.py

示例9: docker_context

def docker_context():
    """Make a docker context"""
    base_url = None
    if "DOCKER_HOST" in os.environ:
        base_url = os.environ["DOCKER_HOST"]
    client = DockerClient(base_url=base_url, timeout=5)
    try:
        info = client.info()
        log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
    except requests.exceptions.ConnectionError as error:
        raise BadDockerConnection(base_url=base_url, error=error)
    return client
開發者ID:Iron-Bound,項目名稱:harpoon,代碼行數:12,代碼來源:executor.py

示例10: download_docker_image

def download_docker_image(docker_image, target_file):
	from docker.client import Client
	try: # First attempt boot2docker, because it is fail-fast
		from docker.utils import kwargs_from_env
		kwargs = kwargs_from_env()
		kwargs['tls'].assert_hostname = False
		docker_cli = Client(**kwargs)
	except KeyError as e: # Assume this means we are not using boot2docker
		docker_cli = Client(base_url='unix://var/run/docker.sock', tls=False)
	image = docker_cli.get_image(docker_image)
	image_tar = open(target_file,'w')
	image_tar.write(image.data)
	image_tar.close()
開發者ID:Dwaligon,項目名稱:tile-generator,代碼行數:13,代碼來源:build.py

示例11: docker_context

def docker_context():
    """Make a docker context"""
    options = kwargs_from_env(assert_hostname=False)
    options["version"] = "auto"
    options["timeout"] = int(os.environ.get("DOCKER_CLIENT_TIMEOUT", 180))

    client = DockerClient(**options)
    try:
        info = client.info()
        log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
    except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
        raise BadDockerConnection(base_url=options.get('base_url'), error=error)
    return client
開發者ID:Atry,項目名稱:harpoon,代碼行數:13,代碼來源:executor.py

示例12: handle

 def handle(self, *args, **kwargs):
     hosts = Host.objects.filter(use_for_building_images=True).order_by('?')
     if hosts:
         c = DockerClient(base_url=hosts[0].docker_api_endpoint)
         for plugin_dict in pool.get_all_plugin_dicts():
             result, log = c.build(
                 tag="docker-service-provisioner/%s:v%s" % (plugin_dict['service'], plugin_dict['version']),
                 path=urljoin(settings.DOCKER_PROVISION_URL, "dockerfile/%s/%s/" % (plugin_dict['service'], plugin_dict['version']))
             )
             if result:
                 print "Converted", plugin_dict['service'], plugin_dict['version'], 'to', result
             else:
                 print "Failed converting", plugin_dict['service'], plugin_dict['version'], 'to', result
     else:
         raise Exception("No hosts available for building images!")
開發者ID:KristianOellegaard,項目名稱:docker-service-provisioner,代碼行數:15,代碼來源:build_docker_images.py

示例13: _init_docker

def _init_docker():
    kwargs = kwargs_from_env()

    if 'tls' in kwargs:
        # see http://docker-py.readthedocs.org/en/latest/boot2docker/
        import requests.packages.urllib3 as urllib3

        urllib3.disable_warnings()
        kwargs['tls'].assert_hostname = False

    docker = Client(**kwargs)
    try:
        docker.version()
    except:
        raise UserMessageException("Please set up 'docker' correctly")
    return docker
開發者ID:ebd2,項目名稱:docker-release,代碼行數:16,代碼來源:main.py

示例14: __init__

 def __init__(self, remote, username=None, password=None, email=None):
     super(DockerPyClient,self).__init__()
     self.client = Client(base_url=remote, version='1.15')
     self.log = logging.getLogger(__name__)
     self.log.debug('password %s, remote = %s, username=%s', password, remote, username)
     if username:
         self.client.login(username=username, password=password, email=email)
開發者ID:mvberg,項目名稱:dockerup,代碼行數:7,代碼來源:dockerpy.py

示例15: __init__

    def __init__(self, cfg):
        from docker.client import Client
        from docker.utils import kwargs_from_env

        self.config = cfg
        docker_kwargs = kwargs_from_env()
        docker_kwargs['tls'].assert_hostname = False
        self.docker = Client(**docker_kwargs)
開發者ID:quanta-computing,項目名稱:quanta-php-module,代碼行數:8,代碼來源:runner.py


注:本文中的docker.client.Client類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。