Python Google Drive API file-delete()方法损坏 [英] Python Google Drive API file-delete() method broken
问题描述
我无法通过Python API使google-drive file-delete()方法正常工作.
I cannot get google-drive file-delete() method to work via the Python API.
它坏了.
我提供一些有关设置的信息:
I offer some info about my setup:
- Ubuntu 16.04
- Python 3.5.2(默认,2018年11月12日,13:43:14)
- google-api-python-client(1.7.9)
- google-auth(1.6.3)
- google-auth-httplib2(0.0.3)
- google-auth-oauthlib(0.3.0)
下面,我列出了可以重现该错误的Python脚本:
Below, I list a Python script which can reproduce the bug:
"""
googdrive17.py
This script should delete files named 'hello.txt'
Ref:
https://developers.google.com/drive/api/v3/quickstart/python
https://developers.google.com/drive/api/v3/reference/files
Demo (Ubuntu):
sudo apt install python3-pip
sudo pip3 install --upgrade google-api-python-client
sudo pip3 install --upgrade google-auth-httplib2
sudo pip3 install --upgrade google-auth-oauthlib
python3 googdrive17.py
"""
import pickle
import os.path
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# I s.declare a very permissive scope (for training only):
SCOPES = ['https://www.googleapis.com/auth/drive']
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as fh:
creds = pickle.load(fh)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
# I s.create a file so I can upload it:
with open('/tmp/hello.txt','w') as fh:
fh.write("hello world\n")
# From my laptop, I s.upload a file named hello.txt:
drive_service = build('drive', 'v3', credentials=creds)
file_metadata = {'name': 'hello.txt'}
media = MediaFileUpload('/tmp/hello.txt', mimetype='text/plain')
create_response = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
file_id = create_response.get('id')
print('new /tmp/hello.txt file_id:')
print(file_id)
# Q: With googleapiclient, how to filter files list()-response?
# A1: https://developers.google.com/drive/api/v3/reference/files/list
# A2: https://developers.google.com/drive/api/v3/search-files
list_response = drive_service.files().list(
orderBy = "createdTime desc",
q = "name='hello.txt'",
pageSize = 22,
fields = "files(id, name)"
).execute()
items = list_response.get('files', [])
if items:
for item in items:
print('I will try to delete this file:')
print(u'{0} ({1})'.format(item['name'], item['id']))
del_response = drive_service.files().delete(fileId=item['id'])
print('del_response.body:')
print( del_response.body)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash()
print('trash_response.body:')
print( trash_response.body)
else:
print('hello.txt not found in your google-drive account.')
运行脚本时,我看到的输出类似于下面列出的内容:
When I run the script I see output similar to that listed below:
$ python3 googdrive17.py
new /tmp/hello.txt file_id:
1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY
I will try to delete this file:
hello.txt (1m8nKOfIeB0E5t60F_-9bKwIJds8PSvYY)
del_response.body:
None
I will try to delete this file:
hello.txt (1Ow4fcUBgEYUy3ezYScDKlLSMbp-hyOLT)
del_response.body:
None
I will try to delete this file:
hello.txt (1TiUrLgQdY1Cb9w0UWHjnmj7HZBaFsKcp)
del_response.body:
None
I will try to emptyTrash:
trash_response.body:
None
$
我看到其中两个API调用工作良好:
I see that two of the API calls work well:
- files.list()
- files.create()
两个呼叫显示为中断:
- files.delete()
- files.emptyTrash()
不过,也许我打错了吗?
Perhaps, though, I call them incorrectly?
推荐答案
此修改如何?
首先,文件:删除方法的正式文档和文件:emptyTrash方法如下.
At first, the official document of Files: delete method and Files: emptyTrash method says as follows.
如果成功,此方法将返回一个空的响应正文.
If successful, this method returns an empty response body.
这样,当删除文件并清除垃圾箱时,返回的 del_response
和 trash_response
为空.
By this, when the file was deleted and the trash was cleared, the returned del_response
and trash_response
are empty.
从您的问题中,我可以理解 files.list()
和 files.create()
可以正常工作.因此,我想提出 files.delete()
和 files.emptyTrash()
的修改点.请按如下所示修改脚本.
From your question, I could understand that files.list()
and files.create()
works. So I would like to propose the modification points for files.delete()
and files.emptyTrash()
. Please modify your script as follows.
for item in items:
print('I will try to delete this file:')
print(u'{0} ({1})'.format(item['name'], item['id']))
del_response = drive_service.files().delete(fileId=item['id'])
print('del_response.body:')
print( del_response.body)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash()
print('trash_response.body:')
print( trash_response.body)
至:
for item in items:
print('I will try to delete this file:')
print(u'{0} ({1})'.format(item['name'], item['id']))
del_response = drive_service.files().delete(fileId=item['id']).execute() # Modified
print('del_response.body:')
print(del_response)
print('I will try to emptyTrash:')
trash_response = drive_service.files().emptyTrash().execute() # Modified
print('trash_response.body:')
print(trash_response)
- 为
-
execute()
.
drive_service.files().delete()
和 drive_service.files().emptyTrash()
添加了如果这不是您想要的结果,我表示歉意.
If this was not the result you want, I apologize.
这篇关于Python Google Drive API file-delete()方法损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!