docker-py 文件傳輸put_archive

http://docker-py.readthedocs.io/en/stable/api/#put_archive
docker-py doc中對文件傳輸的操作定義爲

put_archive

Insert a file or folder in an existing container using a tar archive as source.

Params:

container (str): The container where the file(s) will be extracted
path (str): Path inside the container where the file(s) will be extracted. Must exist.
data (bytes): tar data to be extracted

其中,data字段的類型爲bytes,期初認爲是python3中支持的bytes類型,但經過參考一片外文文章發現並不是這樣,只是需要data是二進制文件流即可,
同時還要保證
1.上傳文件是.tar格式,不然會發生錯誤
2.容器內目錄必須存在,所以需要先使用mkdir -p建立目錄

def uploadFile(name,source,dest,file):
    #check path exist or create dir
    id=d.exec_create(container=name, cmd='mkdir -p ' + dest)
    d.exec_start(exec_id=id)
    f = open(file, 'rb')#二進制讀
    filedata = f.read()
    d.put_archive(container=name, path=source, data=filedata)

附上外文代碼,

import sys
import docker

def start ( cli, event ):
   """ handle 'start' events """
   dest = '/tmp/monitoring'
   source = 'monitor.tar'
   command = dest+'/register.sh'
   # read tar file into memory
   f = open(source, 'rb')
   filedata = f.read()
   # execute (1) : "mkdir -p /tmp/monitoring"
   exe = cli.exec_create( container=event['id'], cmd='mkdir -p '+dest )
   cli.exec_start( exec_id=exe )
   # copy and extract tar file into container
   cli.put_archive( container=event['id'], path=dest, data=filedata )
   # execute (2) : "/tmp/monitoring/register.sh"
   exe = cli.exec_create( container=event['id'], cmd=command, stdout=False, stderr=False )
   cli.exec_start( exec_id=exe, detach=True )

thismodule = sys.modules[__name__]
# create a docker client object that talks to the local docker daemon
cli = docker.Client(base_url='unix://var/run/docker.sock')
# start listening for new events
events = cli.events(decode=True)
# possible events are:
# attach, commit, copy, create, destroy, die, exec_create, exec_start, export,
# kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update
for event in events:
   # if a handler for this event is defined, call it
   if (hasattr( thismodule , event['Action'])):
      getattr( thismodule , event['Action'])( cli, event )
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章