python-3.xgoogle-drive-apigoogle-drive-realtime-api

google drive api v3 (python) update file premissions "role"


Im tryng to make an app in python 3.7 that list all the files in a drive account, and set the public files to private. I am using the google drive api v3. To do this i need to change the file permissions "type" to "user", this didint work, and now im tryng first to put the file permissions "role" to "owner", because on the public files it shows "reader" or "writer".

I tried a lot of things and it doesent works.

Here is the code (its in spanish, because its my language. the function that is not working is called "ActualizarPermisos")

    def actualizarPermisos(service, file_id, permission_id):

        try:
        # First retrieve the permission from the API.
            permission = service.permissions().get(
                fileId=file_id, permissionId=permission_id).execute()
            permission['role'] = 'writer'
            return service.permissions().update(
            fileId=file_id, permissionId=permission_id, body=permission, transferOwnership=False).execute()
        except errors.HttpError as error:
            print ('An error occurred: %s' % error)
            return None

The error that shows is: "An error occurred: https://www.googleapis.com/drive/v3/files/0B4SorsEEhamLfmVuQUtFUXpMS25RT2k2SkpOTzFhclRubk1VM3ZDUkw5b3o0Zm5kRWpHWjQ/permissions/anyone?transferOwnership=false&alt=json returned "The resource body includes fields which are not directly writable."> "


Solution

  • The problem with your code is that you’re using the permission body you get from the get method, which has the fields id, kind and type. These fields are not allowed to be changed when updating a permission, only the fields expirationTime and role are allowed to be changed, as you can check here [1].

    You can simply create the permission json like this:

    permission = {'role': 'writer'}
    

    And use it instead of the permission body you get from the get request. I tested it like that and worked successfully updating the permission of the user from reader to writer.

    If you need to change more fields than the ones allowed, I suggest you to delete the permission (first obtaining the needed data) and create a new permission for that file [2], here you can check the allowed values for each field [3].

    [1] https://developers.google.com/drive/api/v3/reference/permissions/update

    [2] https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.permissions.html#create

    [3] https://developers.google.com/drive/api/v3/reference/permissions