我已經寫了下面的代碼使用service account上傳圖片到自己的谷歌驅動器。簡單API圖片上傳到谷歌驅動器
我的代碼成功返回,給我一個ID
回來,但沒有什麼出現在我的實際谷歌驅動器。
from django.conf import settings
import os
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.service_account import ServiceAccountCredentials
def get_service(api_name, api_version, scope, key_file_location):
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location, scopes=scope)
service = build(api_name, api_version, credentials=credentials)
return service
def setup_upload():
scope = ['https://www.googleapis.com/auth/drive']
key_file_location = os.path.join(os.path.dirname(settings.BASE_DIR), 'common/my-json-file.json')
service = get_service('drive', 'v3', scope, key_file_location)
file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'common/apple.png')
file_metadata = {'name': 'apple.png'}
media = MediaFileUpload(file_path, mimetype="image/png")
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(file.get('id')) #this returns an actual ID
setup_upload()
我得到一個長串ID
從setup_upload()
最後一行後面。但是我的實際Google雲端硬盤上沒有顯示任何內容。我期待看到我的主目錄中彈出apple.png
文件。
缺少什麼我在這裏?
謝謝你的答覆。你能否澄清我可以如何將服務帳戶訪問到我想要寫入的地方?我認爲'範圍'變量就足夠了,它會自動進入根谷歌驅動器文件夾。 – qarthandso