简体   繁体   中英

How to make drive folder "public to the web" using Google API v3 in Python?

I can make a folder using:

from Google import Create_Service

CLIENT_SECRET_FILE = "credentials_gsuite.json"
API_NAME = "drive"
API_VERSION ="v3"
SCOPES = ["https://www.googleapis.com/auth/drive"]
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
folder_name = "Folder"

file_metadata = {"name" : folder_name, "mimeType" : "application/vnd.google-apps.folder"}
service.files().create(body=file_metadata,).execute()

And i need to make folder "public to the web" . In order to do that i need to specify permisions:

'role': 'reader

and a type to:

'type': 'anyone'

and to allow:

"allowFileDiscovery": True

judging by the documentation this should work:

    from Google import Create_Service
    
    CLIENT_SECRET_FILE = "credentials_gsuite.json"
    API_NAME = "drive"
    API_VERSION ="v3"
    SCOPES = ["https://www.googleapis.com/auth/drive"]
    service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
    folder_name = "Folder"
    
    file_metadata = {"name" : folder_name, "mimeType" : "application/vnd.google-apps.folder", 'role': 'reader', 'type': 'anyone',"allowFileDiscovery": True}
    service.files().create(body=file_metadata,).execute()

But im not getting it published on to the web. What am I missing?

Documentation: https://developers.google.com/drive/api/v3/reference/permissions

Modification points:

  • Unfortunately, at the method of service.files().create() , it seems that permissions is not writable. When {"mimeType":"application/vnd.google-apps.folder","name":"sample","permissions":[{"role":"reader","type":"anyone","allowFileDiscovery":true}]} is used as the request body of "Files: create", an error like The resource body includes fields which are not directly writable. occurs. So in this case, it is required to use the method of "Permissions: create" after the new folder was created.

When this is reflected to your script, it becomes as follows.

Modified script:

folder_name = "Folder"
file_metadata = {"name": folder_name, "mimeType": "application/vnd.google-apps.folder"}
folder = service.files().create(body=file_metadata,).execute()
folderId = folder.get('id')

permission = {
    'role': 'reader',
    'type': 'anyone',
    'allowFileDiscovery': True
}
res = service.permissions().create(fileId=folderId, body=permission).execute()
print(res)

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM