python - 使用 PyDrive 将图片上传到 Google Drive

标签 python pydrive fastapi

我有一个关于 PyDrive 的愚蠢问题。 我尝试使用 FastAPI 创建一个 REST API,它将使用 PyDrive 将图像上传到 Google Drive。这是我的代码:

from fastapi import FastAPI, File
from starlette.requests import Request
from starlette.responses import JSONResponse
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

app = FastAPI()


@app.post('/upload')
def upload_drive(img_file: bytes=File(...)):
    g_login = GoogleAuth()
    g_login.LoadCredentialsFile("google-drive-credentials.txt")

    if g_login.credentials is None:
        g_login.LocalWebserverAuth()
    elif g_login.access_token_expired:
        g_login.Refresh()
    else:
        g_login.Authorize()
    g_login.SaveCredentialsFile("google-drive-credentials.txt")
    drive = GoogleDrive(g_login)

    file_drive = drive.CreateFile({'title':'test.jpg'})
    file_drive.SetContentString(img_file) 
    file_drive.Upload()

尝试访问我的端点后,出现此错误:

file_drive.SetContentString(img_file)
  File "c:\users\aldho\anaconda3\envs\fastai\lib\site-packages\pydrive\files.py", line 155, in SetContentString
    self.content = io.BytesIO(content.encode(encoding))
AttributeError: 'bytes' object has no attribute 'encode'

我应该怎么做才能完成这个非常简单的任务?

感谢您的帮助!

**

已更新

**

感谢 Stanislas Morbieu 的回答和评论,这是我更新后的工作代码:

from fastapi import FastAPI, File
from starlette.requests import Request
from starlette.responses import JSONResponse
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from PIL import Image
import os

app = FastAPI()


@app.post('/upload')
def upload_drive(filename, img_file: bytes=File(...)):
    try:
        g_login = GoogleAuth()
        g_login.LocalWebserverAuth()
        drive = GoogleDrive(g_login)

        file_drive = drive.CreateFile({'title':filename, 'mimeType':'image/jpeg'})

        if not os.path.exists('temp/' + filename):
            image = Image.open(io.BytesIO(img_file))
            image.save('temp/' + filename)
            image.close()

        file_drive.SetContentFile('temp/' + filename)
        file_drive.Upload()

        return {"success": True}
    except Exception as e:
        print('ERROR:', str(e))
        return {"success": False}

谢谢大家

最佳答案

SetContentString 需要类型为 str 而非 bytes 的参数。这是文档:

Set content of this file to be a string.

Creates io.BytesIO instance of utf-8 encoded string. Sets mimeType to be ‘text/plain’ if not specified.

因此,您应该以 utf-8 解码 img_file(bytes 类型):

file_drive.SetContentString(img_file.decode('utf-8'))

关于python - 使用 PyDrive 将图片上传到 Google Drive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579158/

相关文章:

python - 在 Django 中存储 5 分制的最有效方法

python - 跨应用程序可用的全局变量

python - 如何避免使用带有pydrive的google drive api的授权页面

python - 错误,“[错误] 33#33 : *92500 connect() failed (111: Connection refused) while connecting to upstream, 客户端 : 216. 58.212.244,服务器:#1906

python - 如何修复 Python Nose : Coverage not available: unable to import coverage module

python - Pytessaract image_to_pdf_or_hocr 函数在 AWS lambda 中不起作用

python - 通过 Pydrive 将 Google 电子表格转换为 Pandas 数据框,无需下载

python - PyDrive 在 Google Drive 中创建文件夹 - 错误为 AttributeError : 'GoogleDrive' object has no attribute 'files

json - Ingress-Nginx 外部身份验证的自定义响应

gunicorn - 我在生产中需要多少个 uvicorn worker ?