如何在Google Drive API v3

时间:2016-04-29 23:15:19

标签: python excel google-api google-drive-api google-api-python-client

当我将我的代码上传到Google云端硬盘时,我想将xlsx文件自动转换为Google电子表格。但是,虽然转换对csv文件成功运行,但我得到:

<HttpError 400 when requesting https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&alt=json returned "Bad Request">

尝试上传xlsx时。

这是我的代码:

def upload_service(filepath, name="", description="", fileID="", parentID=""):
    """ Uses a Resource (service) object to upload a file to drive. """

    if service == "": authenticate_service()

    if name == "":
        name = str(os.path.basename(filepath).split(os.extsep)[0])   # Get from filepath

    extension = str(os.path.basename(filepath).split(os.extsep)[1]).lower()

    if extension == "csv":                  # CSV
        mime_type = "text/csv"
    elif extension in ["xls", "xlsx"]:      # EXCEL
        mime_type = "application/ms-excel"
    else:
        return

    media_body = MediaFileUpload(filepath, mimetype=mime_type, resumable=True)

    if parentID == "":
        meta = dict(name=name, mimeType="application/vnd.google-apps.spreadsheet", description=description)
    else:
        meta = dict(name=name, mimeType="application/vnd.google-apps.spreadsheet", description=description, parents=[parentID])

    if fileID == "":   # CREATE 
        upload = service.files().create(
                                    body=meta,
                                    media_body=media_body).execute()
    else:   # REPLACE
        upload = service.files().update(
                                body=meta,
                                media_body=media_body,
                                fileId=fileID).execute()

    print ("\nFINISHED UPLOADING")

我怎样才能在v3中这样做?很清楚如何在v2中完成它,但不是在更新的API中。

4 个答案:

答案 0 :(得分:4)

在APIv3中,您需要指定非常具体的 MIME类型才能进行转换。

https://developers.google.com/drive/v3/web/manage-uploads#importing_to_google_docs_types_wzxhzdk8wzxhzdk9,您会注意到该声明&#34;支持的转化在关于资源的importFormats数组&#34;中动态提供。使用

获取importFormats列表

GET https://www.googleapis.com/drive/v3/about?fields=importFormats&key={YOUR_API_KEY}

或转到https://developers.google.com/drive/v3/reference/about/get#try-it并输入importFormats

你会在回复中注意到:

"application/vnd.ms-excel": [
   "application/vnd.google-apps.spreadsheet"
]

在您的代码中,使用:

elif extension in ["xls", "xlsx"]:      # EXCEL
    mime_type = "application/vnd.ms-excel"

(注意额外的vnd.),它应该运作良好!

答案 1 :(得分:0)

根据Official Google Documentation,您收到400: Bad Request,表示尚未提供必填字段或参数,提供的值无效或提供的字段组合无效。尝试添加将在目录图中创建循环的父级时,可能会抛出此错误。

遇到此错误时,建议的操作是使用exponential backoff。它是网络应用程序的标准错误处理策略,其中客户端会在不断增加的时间内定期重试失败的请求。

您可以使用官方Google Docs作为参考,有一个参数convert convert=true,可将文件转换为相应的Google文档格式(默认值:false)。

您还需要使用Python client library,您可以使用该库来支持上传文件。

找到此Stack Overflow票证,检查社区提供的解决方案:python + google drive: upload xlsx, convert to google sheet, get sharable link

答案 2 :(得分:0)

def uploadExcel(excelFileName):
   file_metadata = {'name': excelFileName, 'parents': [folderId], 'mimeType': 'application/vnd.google-apps.spreadsheet'}
   media = MediaFileUpload(excelFileName, mimetype='application/vnd.ms-excel', resumable=True)
   file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()

答案 3 :(得分:0)

具有的逻辑是:我们希望以 excel 格式创建电子表格

因此,我们完全使用此逻辑进行编码(C#示例):

Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File();
            fileMetadata.Name = System.IO.Path.GetFileName(file_being_uploaded);
            fileMetadata.Description = "File created via Google Drive API C#";
            fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet";
            fileMetadata.Parents = new List<string> { _parent };    // if you want to organize in some folder       

            // File content.
            byte[] byteArray = System.IO.File.ReadAllBytes(file_being_uploaded);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            try
            {
                FilesResource.CreateMediaUpload request = _service.Item1.Files.Create(fileMetadata, stream, GetMimeType(file_being_uploaded));
(...)

    // gets us the Excel Mime
    private static string GetMimeType(string fileName)
    {
        string mimeType = "application/unknown";
        string ext = System.IO.Path.GetExtension(fileName).ToLower();
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (regKey != null && regKey.GetValue("Content Type") != null)
            mimeType = regKey.GetValue("Content Type").ToString();
        return mimeType;
    }