使用REST API在Google驱动器中创建新文件夹 [英] create new folder in google drive with rest api

查看:123
本文介绍了使用REST API在Google驱动器中创建新文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在不存在python的情况下,如何才能在Google驱动器中使用python创建新文件夹? 我对这个Google API和python完全陌生.

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.)

创建文件夹

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?

推荐答案



    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在内部创建文件夹(如果不存在).

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

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

这篇关于使用REST API在Google驱动器中创建新文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆