Python 简单的API图像上传到谷歌硬盘
我已经编写了下面的代码,使用 我的代码正在成功返回,给了我一个Python 简单的API图像上传到谷歌硬盘,python,file-upload,google-drive-api,google-api-python-client,service-accounts,Python,File Upload,Google Drive Api,Google Api Python Client,Service Accounts,我已经编写了下面的代码,使用 我的代码正在成功返回,给了我一个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
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()
我确实从setup\u upload()
的最后一行返回了一个长ID
字符串。但在我的谷歌硬盘上什么也没有出现。我希望看到apple.png
文件在我的主目录中弹出
我错过了什么 引用您链接到的内容:
“您可以获取服务帐户电子邮件地址,并授予其访问Google drive上某个目录的权限。然后,它将被允许上载到该目录,但您将无权访问这些文件。您需要完成第二步,并通过更新或修补文件权限,授予自己访问这些文件的个人权限。”
您是否已授予服务帐户访问您要写入文件的位置的权限?如果您尚未指定将文件上载到何处,则服务帐户可能只是将文件上载到其自己的驱动器中。除了@user2705223的回答之外,如果您希望能够访问它上载的文件,则必须通过服务帐户授予自己访问这些文件的权限。检查您是否具有成功的登录凭据,并授权具有正确作用域的服务帐户。您可以尝试以下操作,以帮助您进行API请求授权。感谢您的回复。你能澄清一下我怎样才能让服务帐户访问我想写信的地方吗?我认为
scope
变量就足够了,它会自动放在根googledrive文件夹中。