Reputation: 363
I'm trying to upload a image to google drive using requests, but it's not working because the requests keep giving me a status 401 (wrong credentials). I am using the access token that was given to me, so I don't know what is going on.
There's my code:
tokendrive = TOKEN_DRIVE
url = "site_url"
myid = MY_ID
subid = MY_SUB_ID
r = requests.get(url)
headers = {'Authorization': 'Bearer ' + tokendrive}
para = {"name": submission.id + ".png",
"parents": [myid]}
files = {"data": ("metadata", json.dumps(para), "application/json; charset=UTF-8"),
"file": io.BytesIO(requests.get(url).content)}
response = requests.post("https://www.googleapis.com/upload/drive/v3/files",headers=headers,files=files)
print(response.text)
Upvotes: 5
Views: 1404
Reputation: 201713
I believe your goal and your current situation as follows.
request
module of python.Token
to Bearer
. I thought that the reason of your error might be due to this.parents
is "parents": [myid]
. And in the current stage, please use one folder ID here.name
instead of title
. title
is used for Drive API v2.When above points are reflected to your script, it becomes as follows.
This modified script uploads a file of to Google Drive. Before you use this script, please confirm the variables you want to use, again.
headers = {'Authorization': f'Bearer {tokendrive}'} # or 'Bearer ' + tokendrive
para = {
"name": "image_url.jpg",
"parents": [myid]
}
files = {
"data": ("metadata", json.dumps(para), "application/json; charset=UTF-8"),
"file": io.BytesIO(requests.get(submission.url).content)
}
response = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(response.text)
In this script, the following value is returned.
{
"kind": "drive#file",
"id": "###",
"name": "image_url.jpg",
"mimeType": "image/jpeg"
}
In this modified script, the maximum file size for uploading is 5 MB. When you want to upload a file over 5 MB, please use resumable upload. In that case, I think that this thread might be useful. Ref
This sample script deletes a file on Google Drive.
fileId = '###' # Please set the file ID you want to delete.
headers = {'Authorization': f'Bearer {tokendrive}'} # or 'Bearer ' + tokendrive
response = requests.delete(
"https://www.googleapis.com/drive/v3/files/" + fileId,
headers=headers,
)
print(response.text)
In this case, no value is returned. This is the current specification.
IMPORTANT: This script completely deletes the file of fileId
. So please be careful this. I would like to recommend to test using a sample file.
Upvotes: 8