Reputation: 1239
From this example. Can I use MediafileUpload with creating folder? How can I get the parent_id from?
From https://developers.google.com/drive/folder
I just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial to programming in Python?
Thank you for your suggestions.
Upvotes: 9
Views: 21540
Reputation: 26
def create_folder(header, folder_name, folder_id, drive_id=None):
url = 'https://www.googleapis.com/upload/drive/v3/files'
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [folder_id]
}
file_withmetadata = {"data": ("metadata", json.dumps(file_metadata), "application/json; charset=UTF-8")}
param = {"q":"'%s' in parents" %folder_id, "supportsAllDrives":"true"}
if drive_id is not None:
param['driveId'] = drive_id
r = requests.post(
url,
headers=header,
params=param,
files=file_withmetadata
)
return json.loads(r.text)
Upvotes: 0
Reputation: 1629
To create a folder on Drive, try:
def createRemoteFolder(self, folderName, parentID = None):
# Create a folder on Drive, returns the newely created folders ID
body = {
'title': folderName,
'mimeType': "application/vnd.google-apps.folder"
}
if parentID:
body['parents'] = [{'id': parentID}]
root_folder = drive_service.files().insert(body = body).execute()
return root_folder['id']
You only need a parent ID here if you want to create folder within another folder, otherwise just don't pass any value for that.
If you want the parent ID, you'll need to write a method to search Drive for folders with that parent name in that location (do a list() call) and then get the ID of that folder.
Edit: Note that v3 of the API uses a list for the 'parents' field, instead of a dictionary. Also, the 'title'
field changed to 'name'
, and the insert()
method changed to create()
. The code from above would change to the following for v3:
def createRemoteFolder(self, folderName, parentID = None):
# Create a folder on Drive, returns the newely created folders ID
body = {
'name': folderName,
'mimeType': "application/vnd.google-apps.folder"
}
if parentID:
body['parents'] = [parentID]
root_folder = drive_service.files().create(body = body).execute()
return root_folder['id']
Upvotes: 22
Reputation: 2184
The mediafile uplaod is needed only if you want to insert content. Since you want only to insert metadata (folders are only metadata), you don't need it. A regular POST with the JSON representing the foder is enough.
You can get the parent ID in several ways :
https://drive.google.com/#folders/0B8VrsrGIcVbrRDVxMXFWVkdfejQ
0B8VrsrGIcVbrRDVxMXFWVkdfejQ
How to get an FileID programatically :
root
for the root folder of your Drive.Using 3. and 1., you can get all the fileIds of your Drive.
I dont know how I can be clearer
Upvotes: 1