I believe your goal as follows.
- You want to upload an image data from URL to Google Drive using PyDrive.
- From
f.SetContentFile(requests.get(p[:-1]).content), I understood that you want to download the image data from the URL and upload it to Google Drive.
Modification points:
- When I saw the document of PyDrive, it seems that
filename of SetContentFile(filename) is the filename (string value) of the local PC. As other method, it seems that content of SetContentString(content) is the string value.
So in order to upload the downloaded image data, I would like to propose to use requests module. In this case, the access token for uploading is retrieved from the authorization of PyDrive.
When above points are reflected to the script, it becomes as follows.
Sample script:
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)
- In this script, the downloaded image file is directly uploaded to the Google Drive without creating a temporal file.
Result:
When above script is run, the following result is returned.
{
"kind": "drive#file",
"id": "###",
"name": "sample file",
"mimeType": "image/###"
}
References:
Added:
About your 2nd question, when you want to create the file to the shared Drive, please modify above script as follows.
Sample script:
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)