使用PyDrive将图像上传到Google Drive [英] Upload Image to Google Drive using PyDrive

查看:0
本文介绍了使用PyDrive将图像上传到Google Drive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于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:usersaldhoanaconda3envsfastailibsite-packagespydrivefiles.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类型的参数。以下是文档:

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

创建utf-8编码字符串的io.BytesIO实例。如果未指定,则将MimeType设置为"文本/纯文本"。

因此,您应该解码UTF-8中的img_file(类型为bytes):

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

这篇关于使用PyDrive将图像上传到Google Drive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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