繁体   English   中英

使用文本内容google drive api创建一个新文件?

[英]Creating a new file with text contents google drive api?

我正在尝试使用 Google Drive API 创建一个 python 函数来创建一个包含内容的新 Google Drive 文件。

我有点困惑(在查看文档后)要使用哪个 URI,以及我需要在响应正文中放入什么来创建此文件。 到目前为止,这是创建新文件的函数以及进行 API 调用的函数(正在运行):

def make_request(self, method, url, url_params=dict(),
                     headers=dict(), body=None):
        # add Authorization header
        headers["Authorization"] = "Bearer " + self.token  # bearer authentication

        # make the request
        try:
            r = requests.request(method, url, headers=headers, params=url_params, data=body)
        except Exception as e:
            return 9999, str(e)

        # get the body of the response as text
        body = r.text

        # return value contains the error message or the body
        if r.status_code > 299:
            res_dict = json.loads(body)
            ret_val = res_dict["error"]["message"]
        else:
            ret_val = body

        return r.status_code, ret_val
def gd_create_text_file(self, name, parent_id, contents):
        request_body = {
            "name": name,
            "parents": "[" + parent_id + "]",
            "mimeType": "application/vnd.google-apps.document"
        }
        request_body_json = json.dumps(request_body)
        header = {
            "Content-Type": "application/json"
        }
        
        create_json = self.make_request("POST", "https://www.googleapis.com/upload/drive/v3/files/", headers=header, body=request_body_json)

        if(create_json[0] != 200):
            # an error code was thrown, return None
            print("Error" + str(create_json[0]))
            return None
        else:
            #no error, create and return dictionary
            dictionary = {
                "id": json.loads(create_json[1])["id"],
                "name": json.loads(create_json[1])["name"]
            }
            print("dict: " + str(dictionary))
            return dictionary

目前,这不会创建文件,并且它没有文件的任何内容。 我可以做些什么来修复我目前拥有的内容并将内容添加到文件中?

谢谢!

我相信你的目标如下。

  • 您想通过使用 Drive API 转换为 Google Document 将文本数据上传到 Google Drive。
    • 从您的问题和评论中,我了解到您脚本中的contents是文本数据。
  • 您的访问令牌可用于使用 Drive API 上传文件。
  • 您想使用 python requests来实现您的目标。

为了实现您的目标,我想提出以下示例脚本。 为了上传包含文件元数据的文件,需要使用分段上传进行上传。

示例脚本:

import io
import json
import requests

token = '###' # Please set your access token.
name = 'sample' # Please set the filename on Google Drive.
parent_id = 'root' # Please set the folder ID. If you use 'root', the file is created to the root folder.
contents = 'sample text 1' # This is a sample text value for including the created Google Document.

para = {
    "name": name,
    "parents": [parent_id],
    "mimeType": "application/vnd.google-apps.document"
}
res = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers={"Authorization": "Bearer " + token},
    files={
        'metadata': ('metadata', json.dumps(para), 'application/json'),
        'file': ('file', io.BytesIO(contents.encode('utf-8')), 'text/plain')
    }
)
print(res.text)
  • 当我测试上述脚本时,我可以确认包含sample text 1文本的新 Google 文档已认证到 Google 云端硬盘。

笔记:

  • 这是一个简单的示例脚本,用于将文本值作为 Google 文档上传到 Google Drive。 所以请根据您的实际情况进行修改。

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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