首页 > 解决方案 > 使用 python sdk 在 github 中使用远程 docker 文件构建 docker 映像

问题描述

我能够使用 python sdk 构建 docker 映像。如果 dockerfile 在我的本地机器上可用。

client = docker.from_env()
image, build_log = client.images.build(path = "./", tag=image_name,rm=True)   

现在,我的 docker 文件将保存在 github 存储库中,我应该提取它们并构建图像。python sdk doc 说 build 方法接受路径或文件对象。

我能够使用 pyGithub (API3) 存储库从 github 读取 docker 文件的内容

g = Github(base_url=url, login_or_token=accessToken, verify=False)
dmc = g.get_organization(org_name)
repo = dmc.get_repo(repoName)
contents = repo.get_contents(dockerfile_name, "master")

我不确定如何将上述内容对象(ContentFile.ContentFile)转换为 python 文件对象,以便我可以使用它来构建如下图像

client = docker.from_env()
image, build_log = client.images.build(fileobj = contents_file_obj, tag=image_name,rm=True)

标签: python-3.xdockerpygithubpython-docker

解决方案


下面的工作代码可用于从以下代码中提取 Python 文件 obj ContentFile.ContentFile

import io
from github import Github 
import docker

# docker client
client = docker.from_env()

# github repo
g = Github(base_url=url, login_or_token=accessToken, verify=False)
dmc = g.get_organization(org_name)
repo = dmc.get_repo(repoName)
contents = repo.get_contents(dockerfile_name, "master")

# decoding contents of file and creating file obj out of it
decoded_content_str = contents.decoded_content.decode('utf-8')
contents_file_obj = io.StringIO(decoded_content_str)

# building image out of contents file obj
client = docker.from_env()
image, build_log = client.images.build(
                       fileobj=contents_file_obj,
                       tag=image_name,
                       rm=True)

在上面的代码中,(obj of class )的
方法返回文件的字节串内容。解码为字符串。 then用于创建 IO 对象(与 python 中的文件对象相同)decoded_contentcontentsContentFile.ContentFile.decode('utf-8')
decoded_content_strio.StringIO


推荐阅读