我正在創建一個簡單的Web應用程序,該應用程序使用Auth2.0身份驗證將一些文件保存在我的Google Drive中。當我使用下面的代碼時,一切正常,但我在這裏遇到了一些問題。第一個是將內容保存在不同的指定文件夾中。下面的代碼將文件保存在根文件夾中,我找不到原因。upload_folder_id顯然具有良好的價值,我在此省略。使用python將文件上傳到特定的Google Drive文件夾
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store, flags) \
if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))
upload_folder_id = <my_folder_id>
FILES = (('hello.txt', None)) # More files will be added after
for filename, mimeType in FILES:
metadata = {'name': filename}
if mimeType:
metadata['mimeType'] = mimeType
''' I tried all this possibilities too
metadata['parentId'] = upload_folder_id
metadata['folderId'] = upload_folder_id
'''
metadata['parents'] = [{'id': upload_folder_id}]
res = DRIVE.files().create(body=metadata, media_body=filename).execute()
if res:
print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
第二個是驗證步驟。我第一次連接應用程序時,我被重定向到了一個我授權API訪問的Google網頁。有沒有辦法做到這一點,而不通過網頁瀏覽器來驗證訪問? (這對我的本地測試來說很好,但我無法在生產服務器上這樣做)。