Google Service Account Not able to edit / update a Google Sheet using gspread

大兔子大兔子 提交于 2020-01-25 08:26:24

问题


This is a follow up to this StackOverFlow question.

In python, is it possible to edit a publicy shared google sheet, without an auth code?

Which advices to use a g-suite service account to access google sheets.

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name('### downloaded JSON file ###', scope)
gc = gspread.authorize(credentials)

sht1 = gc.open_by_key('1wj9L7Hn779GKP0s4MblkU1wHcqaVcG_E2YKAo1vdof0')

I have done this and I am able to read values from the sheet just fine.

#Open by Gdrive ID
worksheet1 = gc.open_by_key('1qlIZAAK32fTb20KeOr9f-TAxYz7yQnvHUsdGP9Iakrc').sheet1
worksheet1.col_values(3)

>['value1', 'value2', 'value3']

But when I try to update a cell, I am getting a permission denied error.

query = 'insert this'
worksheet1.update_cell(len(values_list)+1, 3, query)

This is the output

---------------------------------------------------------------------------
APIError                                  Traceback (most recent call last)
<ipython-input-9-9e7f86cb0411> in <module>()
----> 1 worksheet1.update_cell(len(values_list)+1, 3, query)

2 frames
/usr/local/lib/python3.6/dist-packages/gspread/models.py in update_cell(self, row, col, value)
    737             },
    738             body={
--> 739                 'values': [[value]]
    740             }
    741         )

/usr/local/lib/python3.6/dist-packages/gspread/models.py in values_update(self, range, params, body)
    174         """
    175         url = SPREADSHEET_VALUES_URL % (self.id, quote(range))
--> 176         r = self.client.request('put', url, params=params, json=body)
    177         return r.json()
    178 

/usr/local/lib/python3.6/dist-packages/gspread/client.py in request(self, method, endpoint, params, data, json, files, headers)
     77             return response
     78         else:
---> 79             raise APIError(response)
     80 
     81     def list_spreadsheet_files(self):

APIError: {
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

Details and what I tried so far.

My service account uses the same email as the google drive account which I am using to host my google sheets. So I should be able to edit a sheet from my service account.

来源:https://stackoverflow.com/questions/59707697/google-service-account-not-able-to-edit-update-a-google-sheet-using-gspread

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