I'm using Docker-py API to handle and manipulate Docker
containers. In the API
, the put_archive()
function expects the data
field to be in bytes.
So, using the tarfile
library I have:
import tarfile
import io
container = client.create_container(image="myimage", command="/bin/bash")
source = "~/.ssh/id_rsa.pub"
tarfile = create_tar_file(path=source, name="keys.tar")
# tarfile = "keys.tar"
# How can I read the tar file was a BytesIO() object?
data = io.BytesIO()
client.put_archive(container=container, path="/tmp", data=data)
The API says:
put_archive
(container
,path
,data
)Insert a file or folder in an existing container using a tar archive as source.
Parameters:
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 extractedReturns:
True
if the call succeeds.Return type: (bool)
Raises:
docker.errors.APIError
– If the server returns an error.
My question is:
How can I read the tar file as a BytesIO()
so it can be passed to the put_archive()
function?
You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write . zip files, or the higher-level functions in shutil.
You could do this way (untested because I don't haveDocker-py
installed):
with open('keys.tar', 'rb') as fin:
data = io.BytesIO(fin.read())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With