我相信你的目标如下。
- 您想使用 PyDrive 将图像数据从 URL 上传到 Google Drive。
- 来自
f.SetContentFile(requests.get(p[:-1]).content),我了解到您想从该网址下载图片数据并将其上传到 Google Drive。
修改点:
- 看到PyDrive的文档,好像
SetContentFile(filename)的filename是本地PC的文件名(字符串值)。作为其他方法,SetContentString(content) 的content 似乎是字符串值。
所以为了上传下载的图片数据,我想建议使用requests模块。在这种情况下,上传的访问令牌是从 PyDrive 的授权中检索的。
当以上几点反映到脚本中时,变成如下。
示例脚本:
from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive # In this script, this is not used.
import io
import json
import requests
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
url = "###" # Please set the URL of direct link of the image.
filename = 'sample file' # Please set the filename.
folder_id = 'root' # Please set the folder ID. If 'root' is used, the uploaded file is put to the root folder.
access_token = gauth.attr['credentials'].access_token
metadata = {
"name": filename,
"parents": [folder_id]
}
files = {
'data': ('metadata', json.dumps(metadata), 'application/json'),
'file': io.BytesIO(requests.get(url).content)
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers={"Authorization": "Bearer " + access_token},
files=files
)
print(r.text)
- 在此脚本中,下载的图像文件直接上传到 Google Drive,无需创建临时文件。
结果:
上述脚本运行时,返回如下结果。
{
"kind": "drive#file",
"id": "###",
"name": "sample file",
"mimeType": "image/###"
}
参考资料:
补充:
关于您的第二个问题,当您想将文件创建到共享云端硬盘时,请修改上述脚本如下。
示例脚本:
from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive # In this script, this is not used.
import io
import json
import requests
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
url = "###" # Please set the URL of direct link of the image.
filename = 'sample file' # Please set the filename.
folder_id = '###' # Please set the folder ID of the shared Drive. When you want to create the file to the root folder of the shared Drive, please set the Drive ID here.
access_token = gauth.attr['credentials'].access_token
metadata = {
"name": filename,
"parents": [folder_id]
}
files = {
'data': ('metadata', json.dumps(metadata), 'application/json'),
'file': io.BytesIO(requests.get(url).content)
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true",
headers={"Authorization": "Bearer " + access_token},
files=files
)
print(r.text)