Чтобы ответить на свой вопрос, я неправильно развертывал облачную функцию. Чтобы он работал правильно, мне пришлось поместить свои функции 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