如何使 Python Docker 图像成为 OpenWhisk 操作?

How do I make a Python Docker image an OpenWhisk action?

我有一个 Docker 图像,它 运行 是一个 Python 程序。我现在想 运行 这个容器作为 OpenWhisk 操作。我该怎么做呢?

我在其他编程语言中看到过几个示例,在 C 和 Node.js 中看到了出色的 black box 框架方法。但我想了解更多关于 OpenWhisk 如何与容器交互的信息,如果可能的话,我只使用 Python.

现在(2016 年 9 月)比我之前的回答简单多了。

在使用命令 $ wsk sdk install docker 创建了 dockerSkeleton 目录之后,您所要做的就是编辑 Dockerfile 并确保您的 Python(现在是 2.7 ) 正在接受参数并以适当的格式提供输出。

这是一个摘要。我已经写得更详细了 here on GitHub

程序

文件 test.py(或 whatever_name.py 您将在下面编辑的 Dockerfile 中使用。)

  • 确保它是可执行的 (chmod a+x test.py)。
  • 确保第一行有 shebang。
  • 确保它在本地运行。
    • 例如./test.py '{"tart":"tarty"}'
      生成 JSON 字典:
      {"allparams": {"tart": "tarty", "myparam": "myparam default"}}
 
    #!/usr/bin/env python

    import sys
    import json

    def main():
      # accept multiple '--param's
      params = json.loads(sys.argv[1])
      # find 'myparam' if supplied on invocation
      myparam = params.get('myparam', 'myparam default')

      # add or update 'myparam' with default or 
      # what we were invoked with as a quoted string
      params['myparam'] = '{}'.format(myparam)

      # output result of this action
      print(json.dumps({ 'allparams' : params}))

    if __name__ == "__main__":
      main()
 

Dockerfile

将以下内容与提供的 Dockerfile 进行比较,以获取 Python 脚本 test.py 并准备好构建 docker 图像。

希望评论能解释差异。当前目录中的任何资产(数据文件或模块)都将成为图像的一部分,requirements.txt

中列出的任何 Python 依赖项也将成为图像的一部分
# Dockerfile for Python whisk docker action
FROM openwhisk/dockerskeleton

ENV FLASK_PROXY_PORT 8080

# Install our action's Python dependencies
ADD requirements.txt /action/requirements.txt
RUN cd /action; pip install -r requirements.txt

# Ensure source assets are not drawn from the cache 
# after this date
ENV REFRESHED_AT 2016-09-05T13:59:39Z
# Add all source assets
ADD . /action
# Rename our executable Python action
ADD test.py /action/exec

# Leave CMD as is for Openwhisk
CMD ["/bin/bash", "-c", "cd actionProxy && python -u actionproxy.py"]

请注意 ENV REFRESHED_AT ...,我用它来确保更新的 test.py 图层是重新拾取的,而不是在构建图像时从缓存中绘制的。