我正在使用以下代码使用 Python 中的
googleapiclient
模块将我的文件上传到 Google 驱动器中。
from __future__ import print_function
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from httplib2 import Http
from oauth2client import file, client, tools
import argparse
class Drive:
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive.file'
extensions = {"csv":"text/csv","mpeg":"video/mpeg","mpg":"video/mpeg","tiff":"image/tiff","tif":"image/tiff","bmp":"image/bmp","gif":"image/gif","wav":"audio/wav","avi":"video/x-msvideo","bmp":"image/bmp","doc":"application/msword","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","jpg":"image/jpeg","jpeg":"image/jpeg","mp4":"video/mp4","mpg":"video/mpeg","pdf":"application/pdf","png":"image/png","ppt":"application/vnd.ms-powerpoint","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","rar":"application/octet-stream","tar":"application/x-tar","txt":"text/plain","wmv":"video/x-ms-wmv","xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","zip":"application/x-zip-compressed"}
def __init__(self):
try:
flags = tools.argparser.parse_args([])
except ImportError:
flags = None
store = file.Storage('token.json')
self.creds = store.get()
if not self.creds or self.creds.invalid:
flow = client.flow_from_clientsecrets(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES)
if flags:
self.creds = tools.run_flow(flow, store, flags)
self.service = build('drive', 'v3', http=self.creds.authorize(Http()))
def create_folder(self,folder_name):
folder_id = None
query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'"
results = self.service.files().list(
pageSize=1, q=query, fields="files(id, name)").execute()
folders = results.get('files', [])
if folders:
folder_id = folders[0]['id']
# If folder not found, then create it.
else:
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
folder_file = self.service.files().create(body=file_metadata,
fields='id').execute()
folder_id = folder_file.get('id')
return folder_id
def upload_file(self, folder_id, file_name):
file_metadata = {
'name': file_name.temporary_file_path(),
'parents': [folder_id]
}
media = MediaFileUpload(file_name.temporary_file_path(),
mimetype= self.extensions[file_name.name.split(".")[1]],resumable=True)
print(media)
_file = self.service.files().create(body=file_metadata,
media_body=media,fields='id').execute()
file_id = _file.get('id')
return file_id
上面的代码工作文件,但上传到 Google Drive 的文件使用受限选项保存。 我正在寻找的是我可以使用默认的“知道链接的任何人”选项上传我的文件的任何方式。意味着向所有人开放。 谢谢。