File "/home/zhouyunli/anaconda3/lib/python3.9/site-packages/docker/utils/decorators.py", line 19, in wrapped return f(self, resource_id, *args, **kwargs) TypeError: update_container() got an unexpected keyword argument 'command'
时间: 2023-12-17 15:04:04 浏览: 118
这个错误是由于您在调用 `container.update()` 方法时传递了一个不支持的关键字参数 `command`。根据 Docker SDK 的文档,`update()` 方法没有 `command` 这个参数。
要更新容器的命令,您可以使用 `container.exec_run()` 方法来执行新的命令。以下是修正后的代码:
```python
import docker
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
client = docker.DockerClient()
class UpdateContainerRequest(BaseModel):
new_command: str
@app.api_route("/containers/create/{image_name}", methods=("POST",))
async def create_container(image_name: str):
try:
container = client.containers.create(image_name)
return {"container_id": container.id}
except docker.errors.ImageNotFound:
raise HTTPException(status_code=404, detail=f"Image '{image_name}' not found.")
except docker.errors.APIError as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/containers/delete/{container_id}")
async def delete_container(container_id: str):
try:
container = client.containers.get(container_id)
container.remove(force=True)
return {"message": "Container deleted successfully."}
except docker.errors.NotFound:
raise HTTPException(status_code=404, detail=f"Container '{container_id}' not found.")
except docker.errors.APIError as e:
raise HTTPException(status_code=500, detail=str(e))
@app.api_route("/containers/{container_id}/update", methods=("PUT",))
async def update_container(container_id: str, request: UpdateContainerRequest):
try:
container = client.containers.get(container_id)
exec_command = f"sh -c '{request.new_command}'"
exec_response = container.exec_run(exec_command)
return {"message": "Container command updated successfully"}
except docker.errors.NotFound:
raise HTTPException(status_code=404, detail=f"Container '{container_id}' not found.")
except docker.errors.APIError as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/containers/info/{container_id}")
async def get_container_info(container_id: str):
try:
container = client.containers.get(container_id)
return {"container_info": container.attrs}
except docker.errors.NotFound:
raise HTTPException(status_code=404, detail=f"Container '{container_id}' not found.")
except docker.errors.APIError as e:
raise HTTPException(status_code=500, detail=str(e))
```
现在,`update_container` 函数会使用 `container.exec_run()` 方法来执行新的命令。我将 `request.new_command` 作为参数传递给 `sh -c` 命令,以便在容器内执行该命令。希望这次修正能解决问题。如果您还有其他问题,请随时提问。
阅读全文