How to create Google Sheets using Service Account Credential in Python?

后端 未结 1 1298
时光取名叫无心
时光取名叫无心 2021-01-28 07:19

I created Service Account Credentials here and got json key service.json.

Then I tried:

from google.oauth2 import service_accou         


        
相关标签:
1条回答
  • 2021-01-28 07:31
    • You want to create new Spreadsheet using Drive API v3 with the service account.
    • You want to create new Spreadsheet to the specific folder of Google Drive of your Google account.
    • You want to achieve this using googleapis with python.
    • You have already been able to use Drive API.

    If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    Modification point:

    • I think that in your script, the scope is required to be modified for creating the file with Drive API. In this case, how about using https://www.googleapis.com/auth/drive?
    • In order to create the new Spreadsheet to the specific folder of Google Drive of your Google account, at first, it is required to share the folder in your Google Drive with the email of the service account. By this, new Spreadsheet is created with the service account to the specific folder of your Google Drive. Please be careful this.

    Modified script:

    When your script is modified, please modify it as follows.

    from googleapiclient.discovery import build  # Added
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/drive']  # Modified
    credentials = service_account.Credentials.from_service_account_file('service.json', scopes=SCOPES)
    
    drive = build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': 'sampleName',
        'parents': ['#### folderId ###'],
        'mimeType': 'application/vnd.google-apps.spreadsheet',
    }
    res = drive.files().create(body=file_metadata).execute()
    print(res)
    
    • About #### folderId ###, please set the folder ID shared with the email of the service account.

    Note:

    • If you want to use both Sheets API and Drive API, please use SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"].
    • In this case, the new Spreadsheet is directly created to the folder in your Google Drive. So you can see it by the browser.
      • If new Spreadsheet is created to the folder in Drive of the service account, it is required to create a permission for your Google account. Please be careful this. In this case, I think that this thread is useful.

    References:

    • Files: create
    • Google API file permissions using python

    If I misunderstood your question and this was not the direction you want, I apologize.

    0 讨论(0)
提交回复
热议问题