docker-py 文件传输put_archive

来源:互联网 发布:推荐系统算法 编辑:程序博客网 时间:2024/04/30 13:53

http://docker-py.readthedocs.io/en/stable/api/#put_archive
docker-py doc中对文件传输的操作定义为

put_archiveInsert 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 extractedpath (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 sysimport dockerdef 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 daemoncli = docker.Client(base_url='unix://var/run/docker.sock')# start listening for new eventsevents = 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, updatefor event in events:   # if a handler for this event is defined, call it   if (hasattr( thismodule , event['Action'])):      getattr( thismodule , event['Action'])( cli, event )
0 0
原创粉丝点击