【问题标题】:Unable to read/write to Google Sheets from a deployed Cloud Function using google.auth.default credentials无法使用 google.auth.default 凭据从已部署的 Cloud Function 读取/写入 Google 表格
【发布时间】:2020-05-05 11:43:47
【问题描述】:

我想通过 Google Drive API 使用 Google Cloud Function 读取/写入 Google Sheet。我尝试将以下代码部署为 Cloud Function(由 Pub/Sub 触发):

def hello_pubsub(event, context):
    from googleapiclient.discovery import build
    import google.auth

    credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])

    service = build('sheets', 'v4', credentials=credentials)
    spreadsheet_id = 'my_spreadsheet_id_goes_here'

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=spreadsheet_id,range="A1:B4").execute()
    values = result.get('values', [])
    for value in values:
        print(value)

    range_ = 'A7'
    request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption='RAW', insertDataOption='OVERWRITE', body={"values":[['test cell input']]})
    response = request.execute()
    print(response)

if __name__ == '__main__':
    hello_pubsub('a', 'b')

我在 Google Cloud Platform > 日志记录中遇到了几个错误: 使用 oauth2client >= 4.0.0 时,file_cache 不可用 自动检测中的文件“/env/local/lib/python3.7/site-packages/google_api_python_client-1.8.0-py3.7.egg/googleapiclient/discovery_cache/init.py”,第 36 行 from google.appengine.api import memcache ModuleNotFoundError: No module named 'google.appengine'

我可以从终端本地运行相同的脚本,并且运行良好。

感谢任何帮助或想法。同样,我想从 Cloud Function 读取/写入 Google Sheet。这是我自己的 Google 表格,通过同一个 Google Cloud 帐户运行。

【问题讨论】:

  • 你的requirements.txt文件是什么?
  • @guillaumeblaquiere 为空,我不确定它应该包含什么,因为我在 pip freeze 中看不到“googleapiclient”或“google”
  • 我的回答是用良好的文本格式更清晰。让我知道它是否有效。

标签: python google-sheets google-cloud-platform google-cloud-functions


【解决方案1】:

我认为您已经全局安装了依赖项并使用它们。但是,当您在 Cloud Function 上部署时,您的本地上下文会丢失,并且缺少所需的库。

在你的函数根目录下添加一个requirements.txt文件,里面有这个内容

google-api-python-client==1.8.2
google-auth==1.14.1

然后再次部署。

【讨论】:

  • 我已更新 Cloud Console 网页界面中的 requirements.txt 并重新部署。我的云功能仍然崩溃,但我不知道为什么。我只是看到它在 GCP Logging 中崩溃了。我得到:1)“ImportError:使用 oauth2client >= 4.0.0 或 google-auth 时 file_cache 不可用”2)回溯文件“/env/local/lib/python3.7/site-packages/googleapiclient/discovery_cache/ __init__.py",第 36 行,在许多其他错误中自动检测
  • 现在,你没有库问题,这是另一个问题!
  • 太好了,现在我看到一个 HttpError 403 - 调用者没有权限。我的默认服务帐户具有“所有者”角色,所以我不确定是什么原因造成的。
  • 您是否添加了默认服务帐户电子邮件作为 gsheet 的编辑器?
  • 修复了它,我添加了错误的服务帐户,我会回答我自己的问题以备将来使用,因为我发现了更多细节。谢谢纪尧姆。
【解决方案2】:

为了回答我自己的问题,我错误地部署了云功能。 为了让它正常工作,我必须将我的函数 main.py、requirements.txt 和我的 service_account.json 放在同一个文件夹中,然后从终端部署它。

我发现有两种方法可以读取/写入工作表:

# METHOD 1 -- using googleapiclient.discovery.build
def hello_pubsub(event, context):
    from googleapiclient.discovery import build
    import google.auth

    credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
    service = build('sheets', 'v4', credentials=None)
    spreadsheet_id = 'redacted'
    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=spreadsheet_id,range="A1:B4").execute()
    values = result.get('values', [])
    # Print the values in the sheet in range A1:B4
    for value in values:
        print(value)

    # Insert values into the sheet in cell A7
    range_ = 'A7'
    request = service.spreadsheets().values().append(
        spreadsheetId=spreadsheet_id, 
        range=range_, 
        valueInputOption='RAW', 
        insertDataOption='OVERWRITE', 
        body={"values":[['This value gets inserted into the cell A7']]})
    response = request.execute()
    print(response)

# METHOD 2 -- using gspread (I prefer this because it's cleaner & does all I need)
import gspread
def hello_pubsub(event, context):
    credentials_filepath = 'default_app_engine_service_account_key.json'
    gc = gspread.service_account(filename=credentials_filepath)
    sh = gc.open("the-title-of-your-sheet-goes-here")
    # Print all values in the sheet
    print(sh.sheet1.get_all_records())
    sh.sheet1.append_row(['This value gets appended to the last row in the sheet'], 
                        value_input_option='RAW', 
                        insert_data_option=None, 
                        table_range=None)

注意: 部署 main.py:

gcloud functions deploy hello_pubsub --runtime python37 --trigger-topic test-topic

别忘了你的 requirements.txt 文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-15
    • 2017-08-04
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多