我一直在浏览aiodocker图书馆。
文档表明他们关注 python-asyncio
标签。所以我想问一下如何异步我的 docker 代码,因为我无法从文档和源代码中弄清楚。这是我需要异步的代码(下面的 detach=True
不起作用,因为有时容器会以非零状态代码退出。让它们异步将帮助我更好地处理这个问题。) :
import docker
def synchronous_request(url):
client = docker.from_env()
local_dir = '/home/ubuntu/git/docker-scraper/data'
volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}
environment = {'URL': url}
client.containers.run('wgettor:latest', auto_remove=True, volumes=volumes, environment=environment)
我对aiodocker
的尝试是:
import aiodocker
async def make_historical_request(url):
docker = await aiodocker.Docker()
client = await aiodocker.DockerContainers(docker)
local_dir = '/home/ubuntu/git/docker-scraper/data'
volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}
environment = {'URL': url}
await client.run(config={"auto_remove": "True",
"volumes": volumes,
"environment": environment}, name="wgettor:latest")
如果您能向我展示如何正确执行此操作,我将不胜感激。
尝试实现类似的目标(以下内容无法同时工作):
import docker
import asyncio
from collections import namedtuple
URL = namedtuple('URL', 'val')
URLs = (
URL('https://www.google.com'),
URL('https://www.yahoo.com')
)
client = docker.from_env()
local_dir = '/home/ubuntu/git/docker-scraper/data-test'
volumes = {local_dir: {'bind': '/download/', 'mode': 'rw'}}
async def run_container(client, volumes, environment, *, pid):
print("Starting the container on pid: {}".format(pid))
return client.containers.run('wgettor:latest', auto_remove=True, detach=True,
volumes=volumes, environment=environment)
async def make_historical_request(url, *, pid):
print("Starting the retrieval of: {}, on pid: {}".format(url, pid))
environment = {'URL': url}
return await run_container(client, volumes, environment, pid=pid)
async def main():
tasks = [asyncio.ensure_future(make_historical_request(url.val, pid=ix)) for ix, url in enumerate(URLs)]
await asyncio.wait(tasks)
if __name__ == '__main__':
asyncio.run(main())
在 Freund Alleind 的帮助下,我相信应该是这样的:
async def run_container(docker, url):
config = {
'Env': ["URL="+url],
'HostConfig': {
'Binds': local_dir + ":" + "/download/"
}
}
try:
await asyncio.sleep(random.random() * 0.001)
container = await docker.containers.create_or_replace(
config=config,
name="wgettor:latest",
)
await container.start()
await container.kill()
return url
except DockerError as err:
print(f'Error starting wgettor:latest, container: {err}')
async def main():
start = time.time()
docker = Docker()
futures = [run_container(docker, url) for url in URLs]
# futures = [fetch_async(i) for i in range(1, MAX_CLIENTS + 1)]
for i, future in enumerate(asyncio.as_completed(futures)):
result = await future
print('{} {}'.format(">>" * (i + 1), result))
print("Process took: {:.2f} seconds".format(time.time() - start))
最佳答案
async def run_container(client, volumes, environment, *, pid):
print('Starting the container on pid: {}'.format(pid))
return client.containers.run(..)
这个函数肯定必须执行await。
(更新)尝试这样的事情:
import aiodocker
async def run_container(docker, name, config):
try:
container = await docker.containers.create_or_replace(
config=config,
name=name,
)
await container.start()
return container
except DockerError as err:
print(f'Error starting {name} container: {err}')
您应该将 docker 创建为
from aiodocker import Docker
docker = Docker()
config = {}
loop.run_until_complete(run_container(docker, ..., config)
经过对引擎 API 的一些研究,我可以说,如果你想挂载某些卷,你可以使用这样的配置:
config = {
'Image': 'imagename',
'HostConfig': {'Binds':['/local_path:/container_path']},
}
关于python-3.x - aiodocker 异步创建容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085421/