首页 > 解决方案 > Google Cloud Python 函数如何访问私有 Python 包

问题描述

  1. 我正在使用 Python 使用 Google Cloud Function。其他几个功能正在生产中。
  2. 但是,为此,我另外创建了一个自定义 Python 包,可在 github 上作为私有repo 使用。
  3. 我需要在 Google Function 中安装包

我做了什么

  1. 我使用在本地运行 Google 函数functions-framework
  2. 我有一个 requirements.txt,其中有一个包的链接。这是通过将以下行添加到requirements.txt
    -e git+https://github.com/<repo>/<project>#egg=<project>
  1. 我跑pip install -r requirements.txt。并且该软件包已成功安装。
  2. 现在在函数的python代码中使用import <pkg-name>works,我可以访问所有函数。

将功能推送到云端时的挑战

  1. 根据文档,要将 Cloud 功能推送到 Google Cloud,我发出以下命令:
gcloud functions \
  deploy <function-name> \
  --trigger-http  \
  --entry-point <entry-function> \
  --runtime python37 \
  --project=<my-project>

正如预期的那样,这会产生错误,因为它无权访问 git 中的私有仓库。

  1. 我创建了一个谷歌云存储库并将其链接到 git 存储库,希望以某种方式我可以在 requirements.txt 中指定它。只是不知道如何。

  2. 我尝试在 Google Cloud Function 中为用户名和密码设置环境变量(这不是一个好主意,我同意),并将它们指定requirements.txt为:

    -e git+https://${AUTH_USER}:${AUTH_PASSWORD}@github.com/<repo>/<project>#egg=<project>

这也给出了一个错误。

任何帮助或指导将不胜感激。

标签: pythonpipgoogle-cloud-functions

解决方案


虽然@marian.viadoi 在上述评论中是正确的,即。Google Cloud Function 无法访问私有 git 存储库,我已经实施了一种解决方法并共享以防万一。以下是已完成的工作:

  1. Python 包是根据(https://packaging.python.org/tutorials/packaging-projects/)中的文档准备的
  2. 使用创建二进制分发“whl”文件python3 setup.py bdist_wheel
  3. 这个 whl 文件被放在了 google 函数文件夹中。我选择把它放在它的一个dist文件夹下。
  4. requirements.txt我添加了行:./dist/xxxx.whl到云功能所需的其他依赖项
  5. 通过gcloud deploy ..
  6. 成功安装后,包及其依赖项会自动安装在云功能的虚拟环境中

没有回答如何在 Google Functions 中使用私有 repo(这是不可能的),但上述步骤确保私有包可以在不同的云功能之间轻松共享和更新。


推荐阅读