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 = "ya29.A0AfH6SMDn1ti-5u8gjLQhHf3ffILkR2_8mSRBoap7hY8ZuIGoFomPhZJAi_hVgORZkBJtBeTDhlPnOeksNZvwrUPgBcuHle5BMqULMBY7Y97fIaMGuOqSAQIrSyXnqLbtDLEwrnCAXfHHSVxtWAbX80pHkarG"
url = "https://www.reddit.com/r/LiminalSpace/comments/lwoipa/i_guess_nobody_woke_me_up/"
myid = "1QoepljKHkjSarx0kCcwEnHjRA5fBP4sU"
subid = lwoipa
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.