Google Sheet API在本地工作,但从AWS Lambda运行时连接超时 [英] Google Sheets API works locally but timeout on connection when running from AWS Lambda

查看:27
本文介绍了Google Sheet API在本地工作,但从AWS Lambda运行时连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码在本地可以很好地工作,但在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错误。

推荐答案

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

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

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

这篇关于Google Sheet API在本地工作,但从AWS Lambda运行时连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆