【问题标题】:How to upload csv files to google drive using python drive api如何使用 python drive api 将 csv 文件上传到 google drive
【发布时间】:2022-12-20 04:46:27
【问题描述】:

我有一个 python 脚本,它从 csv myFile.csv 文件获取数据并将其推送到 google drive 文件夹中。

当我运行我的代码时,出现错误

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/upload/drive/v3/files?fields=id&alt=json&uploadType=multipart returned “Insufficient Permission: Request had insufficient authentication scopes.”。详细信息:“[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}]">

我错过了什么?

下面是我的代码

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import google.auth

scope = [
  'https://www.googleapis.com/auth/drive.file',
  'https://www.googleapis.com/auth/drive.resource',
  'https://spreadsheets.google.com/feeds',
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/drive.readonly']

creds, _ = google.auth.default(scopes=scope)

def push_csv_to_google_drive(creds):

  service = build('drive', 'v3', credentials=creds)
  file_metadata = {"name": 'myFile.csv', "parents": [gdrive_destination_folder_id]}
  media = MediaFileUpload(
      source_csv_file_path, 
      mimetype="file/csv")
        
  file = service.files().create(
          body=file_metadata, 
          media_body=media, 
          fields="id").execute()

if __name__ == '__main__':
    push_csv_to_google_drive(creds=creds)

【问题讨论】:

  • 这是你所有的代码吗?您没有将令牌存储在任何地方?
  • 这是所有代码,没有使用服务帐户。 @DaImTo
  • 是的,但是你的授权在哪里?

标签: python api permissions google-drive-api


【解决方案1】:

据我所知,您根本没有授权用户。

这是我的驱动器上传示例。

#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib


from __future__ import print_function

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json 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('tokenDriveUpload.json'):
        creds = Credentials.from_authorized_user_file('tokenDriveUpload.json', SCOPES)
    # 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:
            flow = InstalledAppFlow.from_client_secrets_file(
                'C:YouTubedevcredentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('tokenDriveUpload.json', 'w') as token:
            token.write(creds.to_json())

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)

        file_metadata = {'name': 'Upload.csv'}
        media = MediaFileUpload('Upload.csv',
                                mimetype='text/plain')
        # pylint: disable=maybe-no-member
        file = service.files().create(body=file_metadata, media_body=media,
                                      fields='id').execute()
        print(F'File ID: {file.get("id")}')

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(F'An error occurred: {error}')



if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2016-10-06
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多