create new folder in google drive with rest api

喜你入骨 提交于 2021-01-28 02:52:36

问题


How can I create a new folder in google drive using python only if it doesn't exists? I am completely new to this google APIs and python.

(I have an access token for my account and I want to create folder using that.)

create folder

import json
import requests
headers = {"Authorization": "Bearer Token"}

data = {
    "name": "name",
    "mimeType": "application/vnd.google-apps.folder"
}

r = requests.post("https://www.googleapis.com/drive/v3/files",
    headers=headers,data = data)
print(r.text)

Only file is getting created, not folder. How can I rectify the problem?


回答1:




    def get_folder_id(self, folder, parent):
        _r = None
        try:
            url = 'https://www.googleapis.com/drive/v3/files?q={0}'. \
                format(quote(
                    "mimeType='application/vnd.google-apps.folder'"
                    " and name ='{0}'"
                    " and trashed != true"
                    " and '{1}' in parents".format(folder, parent),
                    safe='~()*!.\''
                    )
                )
            _r = requests.get(url, headers={
                "Authorization": "Bearer {0}".format(self.get_access_token()),
                "Content-Type": self.file_bean.get_content_type(),
            })
            _r.raise_for_status()
            _dict = _r.json()
            if 'files' in _dict and len(_dict['files']):
                return _dict['files'][0]['id']
            else:
                _f = self.create_folder(folder, parent)
                if _f:
                    return _f
                status, status_message = self.get_invalid_folder()
        except requests.exceptions.HTTPError:
            status, status_message = self.get_http_error(_r)
        except Exception as e:
            logger.exception(e)
            status, status_message = self.get_unknown_error()


    def create_folder(self, folder_name, parent_folder_id):
        url = 'https://www.googleapis.com/drive/v3/files'
        headers = {
            'Authorization': 'Bearer {}'.format(self.get_access_token()), # get your access token
            'Content-Type': 'application/json'
        }
        metadata = {
            'name': folder_name, #folder_name as a string
            'parents': [parent_folder_id], # parent folder id (="root" if you want to create a folder in root)
            'mimeType': 'application/vnd.google-apps.folder'
        }
        response = requests.post(url, headers=headers, data=json.dumps(metadata))
        response = response.json()
        if 'error' not in response:
            return response['id']  # finally return folder id

use get_folder_id which internally creates a folder if doesn't exists.

PS: This code is blindly copied from my work, if you have any difficulty in understanding, I can elaborate the answer.




回答2:


Your first step is to define what you mean by "only if it doesn't exists". In Google Drive, files (and a folder is just a file with a special mime type) are identified by their ID, not by their name. So I can have many folders, all with the same name.

I'll assume that "only if it doesn't exists" really means "only if a folder with a given name doesn't already exist". The steps are :-

  1. Do a files/list with a query name=foldername, trashed=false, mime-type=application/vnd.google-apps.folder. Make sure your files.list deals with nextPageToken correctly
  2. If the count of results == 0, files.create foldername


来源:https://stackoverflow.com/questions/54176209/create-new-folder-in-google-drive-with-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!