首页 > 解决方案 > 使用rest api在谷歌驱动器中创建新文件夹

问题描述

仅当它不存在时,如何使用 python 在谷歌驱动器中创建一个新文件夹?我对这个谷歌 API 和 python 完全陌生。

(我的帐户有一个访问令牌,我想使用它创建文件夹。)

创建文件夹

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)

只创建文件,而不是文件夹。我该如何纠正这个问题?

标签: pythongoogle-apigoogle-drive-apigoogle-python-api

解决方案




    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

使用 get_folder_id 如果不存在则在内部创建一个文件夹。

PS:此代码是从我的工作中盲目复制的,如果您有任何理解困难,我可以详细说明答案。


推荐阅读