Note that there are some explanatory texts on larger screens.

plurals
  1. POGoogle Drive Insert Permissions python 500 internal server error
    primarykey
    data
    text
    <p>this question is similar to:http://stackoverflow.com/questions/12471180/frequently-http-500-internal- error-with-google-drive-api-drive-files-get Though there is no answer for the 500 internal server error.</p> <p>I am using Google Drive (python) to iterate through all of my files and change permissions on each file. I get responses like: An error occurred: https://www.googleapis.com/drive/v2/files/12345CuV3wBsvZDM3ZmRjNWQtMWZkNC00NzQzLTg2MzMtM2IyY2Q0YWU1OTll/permissions?alt=json returned "Internal Error"></p> <p>My code is pretty cookie-cutter from google's examples, and is as follows:</p> <pre><code>#!/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 = '&lt;PATH/TO/CLIENT_SECRETS.JSON&gt;' 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) </code></pre> <p>Going with Claudio's advice to 'add permissions' instead of 'insert permissions' changes the code to the following:</p> <pre><code>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) </code></pre> <p>This sends PersonB an email saying that PersonA has shared a file with them. Does this mean that when I can run an App from PersonB that will let personB's app read person A's files?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload