使用 gcsfs 的 Google 云函数 - “RuntimeError:此类不是 fork-safe”

Joh*_*n F 3 python google-cloud-platform google-cloud-functions

我已经gcsfs在我的云功能中使用了一段时间,没有出现任何问题。突然,它停止了新部署的功能,并抛出错误:( RuntimeError: This class is not fork-safe照片中附有完整的回溯)

我猜这是由于包的依赖项之一造成的gcsfs。无论如何,我已经更新gcsfs到当前版本,但这requirements.txt没有帮助。

可以通过如下定义云函数来重现该错误(Python 3.7):

主要.py:

import gcsfs

# Read in runners and races for end_date
fs = gcsfs.GCSFileSystem(project='project-name-1234')

def try_gcsfs(request):

    with fs.open(r'any_csv_file_in_cloud_bucket.csv', 'rb') as f:
      lines = []
        for line in f:
            lines.append(line.decode(errors='ignore'))

    print('success')
Run Code Online (Sandbox Code Playgroud)

要求.txt:

gcsfs==2021.10.0
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 8

此更改与 Python 3.7 buildpacks 的推出有关。由于迁移到gunicorn其工作模型,全局作用域和函数作用域可以在单独的进程中执行。GCSFileSystem可以通过将初始化移至函数体来解决此问题。

您需要放入fs = gcsfs.GCSFileSystem(project='project-name-1234')入口点内部try_gcsfs。您的代码应如下所示:

import gcsfs

def try_gcsfs(request):

  # Read in runners and races for end_date
  fs = gcsfs.GCSFileSystem(project='project-name-1234')
    
  with fs.open(r'any_csv_file_in_cloud_bucket.csv', 'rb') as f:
    lines = []
      for line in f:
        lines.append(line.decode(errors='ignore'))

    print('success')
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以参考此链接,使用 Pack CLI 进行构建。