Google Cloud Functions 上没有名为 psycopg2._psycopg2 的模块

No module named psycopg2._psycopg2 on Google Cloud Functions

我有一个 Google Cloud Function,它通过 psycopg2 使用 Google Cloud SQL。我的 requirements.txt 中有 psycopg2,但是服务更新后我收到错误 No module named psycopg2._psycopg2.

这是 Cloud Function's environment 中 psycopg2 的 C 库 运行 的问题吗?我该如何解决?

main.py

import psycopg2

def postgres_demo(request):
    return "hi"

requirements.txt

psycopg2==2.8.2

serverless.yml

service: gcf-python-v2

provider:
    name: google
    stage: dev
    runtime: python37
    region: us-central1
    project: my-project
    credentials: ~/.gcloud/keyfile.json

plugins:
    - serverless-google-cloudfunctions
    - serverless-python-requirements

custom:
    pythonRequirements:
        pythonBin: python3

package:
    exclude:
        - node_modules/**
        - .gitignore
        - .git/**

functions:
    second:
        handler: postgres_demo
        events:
            - http: path

运行 serverless deploy 总是导致:

Deployment failed: RESOURCE_ERROR

 {"ResourceType":"cloudfunctions.v1beta2.function","ResourceErrorCode":"400","ResourceErrorMessage":"Function failed on loading user code. Error message: Code in file main.py can't be loaded.\nDid you list all required modules in requirements.txt?\nDetailed stack trace: Traceback (most recent call last):\n  File \"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py\", line 305, in check_or_load_user_function\n    _function_handler.load_user_function()\n  File \"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py\", line 184, in load_user_function\n    spec.loader.exec_module(main)\n  File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n  File \"/user_code/main.py\", line 1, in <module>\n    import psycopg2\n  File \"/user_code/psycopg2/__init__.py\", line 50, in <module>\n    from psycopg2._psycopg import (                     # noqa\nModuleNotFoundError: No module named 'psycopg2._psycopg'\n"}

我通过完全删除 python-serverless-requirements 并使用无服务器 package 选项来确保只有 main.pyrequirements.txt 包含在 zip 文件中来解决它。

Google 云在 requirements.txt 本身中安装软件包,因此您不需要无服务器插件。 Google cloud 也有 psycopg2 必要的 C 库。