【问题标题】:Upload Image to Google Drive using PyDrive使用 PyDrive 将图像上传到 Google Drive
【发布时间】:2019-10-27 11:52:20
【问题描述】:

我有一个关于 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}

谢谢大家

【问题讨论】:

    标签: python pydrive fastapi


    【解决方案1】:

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

    将此文件的内容设置为字符串。

    创建 utf-8 编码字符串的 io.BytesIO 实例。如果未指定,则将 mimeType 设置为“text/plain”。

    因此,您应该在 utf-8 中解码 img_filebytes 类型):

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

    【讨论】:

    • 您好@stanislas-morbieu,感谢您的回答,但是在尝试您的代码后,我收到此错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
    • 我忘了考虑这个。我认为你不能使用SetContentStringSetContentFile 可能是唯一的选择:您可能必须将其保存到临时文件中,以便将文件名作为参数传递给 SetContentFile
    • 谢谢,我也不知道这个,我会发布我的更新和工作代码。非常感谢您的回答
    【解决方案2】:

    使用file_drive.SetContentFile(img_path)

    这解决了我的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      相关资源
      最近更新 更多