python - Google Sheets API 在本地工作,但从 AWS Lambda 运行时连接超时

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

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

我可以“在网上”访问其他内容,因此这不是一般路由问题,我从 AWS 运行中收到套接字超时错误。

我尝试了几个不同的库,包括旧版本的主库。他们每个人都在本地工作,而不是在 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 错误。

最佳答案

我今天遇到了完全相同的问题,一段时间后我发现对我来说问题是 lambda 的内存大小不足。

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

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

关于python - Google Sheets API 在本地工作,但从 AWS Lambda 运行时连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406792/

相关文章:

django - apache2 python 3.4.3 ubuntu 错误 wsgi no module named

python - 无法从用 Python C API 构建的模块中调用方法

aws-lambda - AWS自动化文档不更新Lambda别名

python - 如何在 python pandas 的同一列上进行分组并计算唯一值和某些值的计数作为聚合?

Python:按键、值比较两个相同的字典

python - 为什么 reversed(mylist) 这么慢?

python - 正则表达式获取数据后 |

python - 从接口(interface)的IP和网络掩码获取网络IP

amazon-web-services - 从 AWS lambda 设置 http 响应 header

amazon-web-services - 允许 AWS Lambda 访问 RDS 数据库