Google Sheets API works locally but timeout on connection when running from AWS Lambda

老子叫甜甜 提交于 2020-01-24 19:53:27

问题


I have some code that works perfectly locally and doesn't work at all from AWS Lambda. It's almost like the API is blocked and I'm not sure what to look for next.

I can hit other things "out on the net" so it's not a generic routing issue and I get a socket timeout error from the AWS Run.

I've tried a few different libraries including an older version of the main library. Everyone of them works locally, doesn't work from 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)

Locally I get the results of the sheet (just some smample data) in the cloud though it hangs on this call

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

And then times out with a socket.timeout error.

来源:https://stackoverflow.com/questions/57406792/google-sheets-api-works-locally-but-timeout-on-connection-when-running-from-aws

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!