![](/img/trans.png)
[英]How to upload csv files to google drive using python drive api
[英]How to upload and delete files with google drive API using python requests
我正在嘗試使用請求將圖像上傳到谷歌驅動器,但它不起作用,因為請求不斷給我一個狀態 401(錯誤的憑據)。 我正在使用給我的訪問令牌,所以我不知道發生了什么。
這是我的代碼:
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)
我相信你的目標和你目前的情況如下。
request
模塊來實現此目的。Token
修改為Bearer
。 我認為您的錯誤的原因可能是由於這個。parents
的屬性是"parents": [myid]
。 在當前階段,請在此處使用一個文件夾 ID。name
代替title
。 title
用於驅動器 API v2。當以上幾點反映到您的腳本時,它變成如下。
此修改后的腳本將文件上傳到 Google Drive。 在您使用此腳本之前,請再次確認您要使用的變量。
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)
在此腳本中,將返回以下值。
{ "kind": "drive#file", "id": "###", "name": "image_url.jpg", "mimeType": "image/jpeg" }
在這個修改后的腳本中,上傳的最大文件大小為 5 MB。 當您要上傳超過 5 MB 的文件時,請使用可恢復上傳。 在那種情況下,我認為這個線程可能有用。 參考
此示例腳本刪除 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)
在這種情況下,不返回任何值。 這是當前的規范。
重要提示:此腳本完全刪除fileId
的文件。 所以請注意這一點。 我想建議使用示例文件進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.