问题
I have a google sheet which I set so that anyone can edit.
I noticed that in the gspread
package, you can get a spreadsheet from the link alone. Example:
sht1 = gc.open_by_key('1wj9L7Hn779GKP0s4MblkU1wHcqaVcG_E2YKAo1vdof0')
Since anyone can edit, providing an auth code for access is not necessary. However, it seems that you always need to initialize it using an auth code.
Is there a way to edit a google sheet without any auth code?
This may get confused as a duplicate of this post Using gspread to read from a Google Drive Spreadsheet without logging in however, the solutions are to either have a client provide their auth code, or download the file directly, but no option to edit the file.
回答1:
- You want to edit Google Spreadsheet without logging in the Google for retrieving the authorization code.
- You want to achieve this using gspread with python.
- You have already been able to get and put values for Google Spreadsheet with Sheets API.
If my understanding is correct, how about this workaround? Please think of this as just one of several workarounds.
Workaround:
In this workaround, the service account is used. When the service account is used, you can get and put values for Google Spreadsheet without logging in Google account using the gspread.
In order to access to Google Spreadsheet with the service account, please do the following flow.
- Create the service account and download the JSON file for using the service account.
- Share the email address of the service account to the Google Spreadsheet you want to use.
- You can see the email address at the downloaded JSON file.
Sample script:
The sample script for using the script of sht1 = gc.open_by_key('1wj9L7Hn779GKP0s4MblkU1wHcqaVcG_E2YKAo1vdof0')
with the service account is as follows.
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')
- Please set
### downloaded JSON file ###
.
References:
- Using OAuth 2.0 for Server to Server Applications
- Create a G Suite service account
回答2:
Unfortunately you can't what you want without authentication. Is a mandatory thing.
In the end if you take a look at Gspread you could see that is actually using the Google Sheets API. And through the API you need to authenticate even when accessing (like in your case) public data.
There are other ways to authenticate with the API but sincerely I don't know if they are supported by Gspread
(I believe that they are not).
So you could use some workaround proposed in the question that you mentioned.
来源:https://stackoverflow.com/questions/59562037/in-python-is-it-possible-to-edit-a-publicy-shared-google-sheet-without-an-auth