【问题标题】:Google Sheets API works locally but timeout on connection when running from AWS LambdaGoogle Sheets API 在本地工作,但从 AWS Lambda 运行时连接超时
【发布时间】:2019-12-15 19:44:07
【问题描述】:

我有一些代码可以在本地完美运行,但在 AWS Lambda 中根本无法运行。这几乎就像 API 被阻止了,我不确定接下来要寻找什么。

我可以“在网上”解决其他问题,因此这不是一般的路由问题,并且我从 AWS Run 中收到了套接字超时错误。

我尝试了几个不同的库,包括旧版本的主库。他们每个人都在本地工作,不在 AWS 上工作。

#!/usr/bin/env python3

# replace
creds_file = "/path/to/creds.json"

import pickle
import os.path
from googleapiclient.discovery import build
from google.oauth2 import service_account

scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']

SAMPLE_SPREADSHEET_ID = "<spreadsheetid>"
# Sample Range
SAMPLE_RANGE_NAME = "Sheet1!A1:D"

creds = None

# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.

if os.path.exists('/tmp/token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        # Customized
        creds = service_account.Credentials.from_service_account_file(creds_file)
        creds_w_scopes = creds.with_scopes(SCOPES)

    # Save the credentials for the next run
    with open('/tmp/token.pickle', 'wb') as token:
        pickle.dump(creds_w_scopes, token)

# Timeout is Here in the Cloud
service = build('sheets', 'v4', credentials=creds_w_scopes)

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                            range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])

print(values)

在本地,我在云中获得了工作表的结果(只是一些示例数据),尽管它挂在这个调用上

service = build('sheets', 'v4', credentials=creds)

然后超时并出现 socket.timeout 错误。

【问题讨论】:

  • 我也有同样的问题。我认为这是关于安全组的,我给予了许可,但它不起作用。你能找到解决办法吗?
  • 我好像也有同样的问题

标签: python python-3.x aws-lambda google-oauth google-sheets-api


【解决方案1】:

我今天遇到了完全相同的问题,经过一段时间后,我发现问题在于 lambda 的内存大小不足。

如果您查看 CloudWatch,您可以看到您的 Lambda 有多少 RAM(内存)可用以及它正在使用多少。如果您看到使用量等于可用的最大 RAM,您可能应该增加可用 RAM(或使您的代码更高效)。

在我们的例子中,只需将 RAM 从 128MB 增加到 384MB 即可解决 60 秒的超时问题,并使 lambda 在几秒钟内运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2020-10-11
    • 2017-07-25
    • 1970-01-01
    • 2013-04-26
    • 2018-02-08
    • 2017-10-22
    相关资源
    最近更新 更多