Python 使用PyDrive将图像上载到Google Drive
我有一个关于PyDrive的愚蠢问题。 我尝试使用FastAPI创建一个RESTAPI,它将使用PyDrive将图像上传到Google Drive。这是我的密码:Python 使用PyDrive将图像上载到Google Drive,python,pydrive,fastapi,Python,Pydrive,Fastapi,我有一个关于PyDrive的愚蠢问题。 我尝试使用FastAPI创建一个RESTAPI,它将使用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.d
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
的参数,而不是字节
。以下是文件:
将此文件的内容设置为字符串
创建utf-8编码字符串的io.BytesIO实例。如果未指定,则将mimeType设置为“文本/普通”
因此,您应该在utf-8中解码img_文件
(类型字节
):
file_drive.SetContentString(img_file.decode('utf-8'))
使用
file\u驱动器.SetContentFile(img\u路径)
这解决了我的问题
Hello @ Stistelas MyBiu,谢谢你的回答,但是在尝试了你的代码之后,我得到了这个错误:<代码> UnoDoDebug错误:“UTF-8”编解码器不能在0位中解码字节0xFF:无效的开始字节< /C> >我忘记考虑这一点。我认为您不能使用SetContentString
SetContentFile
可能是唯一的选项:您可能必须将其保存到临时文件中,以便将文件名作为参数传递给SetContentFile
。谢谢,我也不知道这一点,我将发布更新的工作代码。非常感谢你的回答