簡體   English   中英

使用 Python 將非標准文件上傳到 Google 雲端硬盤時出現問題

[英]Problem Using Python to Upload Non-Standard Files to Google Drive

我的組織正在將我們的 on-site.network 驅動器轉移到 Google 雲端硬盤,我希望自動化一些過程。 不是貿易開發人員,但我確實有編程經驗。 以前從未與 Python 或 Google API 合作過,但我喜歡挑戰。 雖然一路上有點卡住了 - 我讓它循環遍歷所有文件和目錄,我想我什至找到了一種方法來正確地將它帶到 map 整個文件系統。 奇怪的是,我認為這是一件很常見的事情,但我還沒有找到任何代碼可以做到這一點。 如果您知道將整個目錄復制到 Google 雲端硬盤以便保留所有子目錄的方法,請告訴我; 我自己做的,有點亂。 但是,當我運行它時,它適用於某些文件類型,但如果遇到不常見的文件類型(如 txt、docx 或 xlsx),則會因 UnknownFileType 錯誤而崩潰。 顯然,需要傳輸文件的人將擁有所有類型的文件,所以這根本行不通。 不知道如何解決它。 我認為如果我設置 mimeType 元數據我可以使單個文件工作但如果它在多個文件上運行我不能手動設置 mimeType。 也許有一種不同的方法可以上傳可以處理任何類型的文件而無需知道 mimeType? 由於這是我第一次使用 Python 或 Google API,我主要復制了他們網站上的代碼以及我在其他位置找到的一些代碼,然后對其進行編輯以循環瀏覽我需要的所有文件。 如果它是一個奇怪的擴展名,上傳甚至不會對一個文件起作用。 希望大家能找出問題所在。 這是相關的代碼塊。


for filename in filenames:
            print("Uploading file " + filename + " to " + folnames[i])
            file_metadata = {'name': filename,
                         'parents' : [folids[i]]}
            file = service.files().create(body=file_metadata,
                                        media_body=dirpath + "\\" + filename,
                                        fields='id').execute()
            print("Upload Complete")

任何幫助表示贊賞。 謝謝!

編輯:我發布了我為測試單個文件上傳而制作的小程序的完整代碼。 更改文件名以保護隱私

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
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.pickle 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('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)


    file_metadata = {'name': 'FILENAME'}
    file = service.files().create(body=file_metadata,
                                        media_body='FILEPATH',
                                        fields='id').execute()
    print ("File ID: %s" % file.get('id'))

if __name__ == '__main__':
    main()

通過使用 MimeTypes 猜測媒體主體的 mimetype 和 MediaFileUpload 使其工作。 感謝大家的幫助和建議。

---
from __future__ import print_function
import pickle
import mimetypes
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.pickle.
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.pickle 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('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)



    mime = mimetypes.MimeTypes().guess_type("FILE")[1]
    file_metadata = {'name': 'NAME',
                     'mimeType': mime}
    media = MediaFileUpload('FILE', mimetype = mime)
    file = service.files().create(body=file_metadata,
                                        media_body= media,
                                        fields='id').execute()
    print ("File ID: %s" % file.get('id'))

if __name__ == '__main__':
    main()
---

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM