这个问题类似于:http://stackoverflow.com/questions/12471180/frequently-http-500-internal- error-with-google-drive-api-drive-files-get 虽然500内部服务器错误没有答案。
我正在使用Google Drive(python)来遍历我的所有文件并更改每个文件的权限。我收到如下回复: 发生错误: https://www.googleapis.com/drive/v2/files/12345CuV3wBsvZDM3ZmRjNWQtMWZkNC00NzQzLTg2MzMtM2IyY2Q0YWU1OTll/permissions?alt=json返回"内部错误">
我的代码非常适合谷歌的例子,如下:
#!/usr/bin/python
from apiclient import errors
import httplib2
import pprint
import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
# Path to client_secrets.json which should contain a JSON document such as:
# {
# "web": {
# "client_id": "[[YOUR_CLIENT_ID]]",
# "client_secret": "[[YOUR_CLIENT_SECRET]]",
# "redirect_uris": [],
# "auth_uri": "https://accounts.google.com/o/oauth2/auth",
# "token_uri": "https://accounts.google.com/o/oauth2/token"
# }
# }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]
class GetCredentialsException(Exception):
"""Error raised when an error occurred while retrieving credentials.
Attributes:
authorization_url: Authorization URL to redirect the user to in order to
request offline access.
"""
def __init__(self, authorization_url):
"""Construct a GetCredentialsException."""
self.authorization_url = authorization_url
class CodeExchangeException(GetCredentialsException):
"""Error raised when a code exchange has failed."""
class NoRefreshTokenException(GetCredentialsException):
"""Error raised when no refresh token has been found."""
class NoUserIdException(Exception):
"""Error raised when no user ID could be retrieved."""
def update_permission(service, file_id, permission_id, new_role):
"""Update a permission's role.
Args:
service: Drive API service instance.
file_id: ID of the file to update permission for.
permission_id: ID of the permission to update.
new_role: The value 'owner', 'writer' or 'reader'.
Returns:
The updated permission if successful, None otherwise.
"""
try:
# First retrieve the permission from the API.
permission = service.permissions().get(
fileId=file_id, permissionId=permission_id).execute()
permission['role'] = new_role
return service.permissions().update(
fileId=file_id, permissionId=permission_id, body=permission).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
def retrieve_all_files(service):
"""Retrieve a list of File resources.
Args:
service: Drive API service instance.
Returns:
List of File resources.
"""
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = service.files().list(**param).execute()
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
return result
def retrieve_permissions(service, file_id):
"""Retrieve a list of permissions.
Args:
service: Drive API service instance.
file_id: ID of the file to retrieve permissions for.
Returns:
List of permissions.
"""
try:
permissions = service.permissions().list(fileId=file_id).execute()
return permissions.get('items', [])
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
def insert_permission(service, file_id, value, perm_type, role):
"""Insert a new permission.
Args:
service: Drive API service instance.
file_id: ID of the file to insert permission for.
value: User or group e-mail address, domain name or None for 'default'
type.
perm_type: The value 'user', 'group', 'domain' or 'default'.
role: The value 'owner', 'writer' or 'reader'.
Returns:
The inserted permission if successful, None otherwise.
"""
new_permission = {
'value': value,
'type': perm_type,
'role': role
}
try:
return service.permissions().insert(
fileId=file_id, body=new_permission).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
def login(clientID, clientSecret, clientCode=0):
# Copy your credentials from the APIs Console
CLIENT_ID = clientID
CLIENT_SECRET = clientSecret
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
#REDIRECT_URI = 'http://localhost'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
if not clientCode:
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
else:
print 'Client code supplied'
code = clientCode
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
allFilesDictionary = retrieve_all_files(drive_service)
file = open('file3.txt', 'a')
for f in allFilesDictionary:
fileID = f['id']
permissionsIDList = retrieve_permissions(drive_service, fileID)
pidl = permissionsIDList[0]
#for pidl in permissionsIDList:
#It is a list of dictionaries.....
#for p in pidl:
# file.write(fileID + '\t\t' + p + ' value is' + p['id'] + '\n')
#Change permissions of ID...
####"owner"
####permissionsIDList["userPermission"]["id"]
####"me" gives 500 "Http 500 Internal server error" ... empty oauth_callback value while request_token ... give webaddress
#permissionsResource = update_permission(drive_service, fileID, "me", "reader")
insert_permission(drive_service, fileID, "me", "user", "reader")
file.close()
clientid ='1234567872174.apps.googleusercontent.com'
clientsecret='abcdefgh3VXUu5EaJvO9BExc'
login(clientid, clientsecret)
根据克劳迪娅的建议,添加权限&#39;而不是&#39;插入权限&#39;将代码更改为以下内容:
import gdata.docs
import gdata.docs.service
userNameAtGmailCom = 'PersonAEmailAddress@gmail.com'
password = 'PersonAPassword'
personToShareWith = "PersonB@gmail.com"
def login(userNameAtGmailCom, password, personToShareWith):
client = gdata.docs.service.DocsService()
client.ClientLogin(userNameAtGmailCom, password)
documents_feed = client.GetDocumentListFeed()
for document_entry in documents_feed.entry:
print document_entry.title.text
scope = gdata.docs.Scope(value=personToShareWith, type='user')
role = gdata.docs.Role(value='reader')
acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role)
created_acl_entry = client.Post(acl_entry, document_entry.GetAclLink().href, converter=gdata.docs.DocumentListAclEntryFromString)
login(userNameAtGmailCom, password, personToShareWith)
这会向PersonB发送一封电子邮件,说明PersonA与他们共享了一个文件。这是否意味着当我可以从PersonB运行一个App,让appB的应用程序读取人A的文件?