sys:1:运行时警告:从未等待协程"FOO"



我使用FastAPI使用以下代码,当我尝试为该函数提供图像时,它给了我API结果上的traceback:

Traceback (most recent call last):  
File "/home/shady/Desktop/BTS/Segmentation/server/fast_app.py", line 32, in remove_background"
return Response(content=data, media_type="image/png")
File "/home/shady/anaconda3/envs/py37/lib/python3.7/site-packages/starlette/responses.py", line 49, in __init__
self.body = self.render(content)n
File "/home/shady/anaconda3/envs/py37/lib/python3.7/site-packages/starlette/responses.py", line 57, in render
return content.encode(self.charset)n
AttributeError: 'coroutine' object has no attribute 'encode'"
下面是我使用的代码:
from io import BytesIO
import uvicorn
from fastapi import FastAPI, HTTPException, UploadFile, Form
from fastapi.responses import Response
import traceback
from remove_bg import remove as remove_background
from PIL import Image
app = FastAPI(title='BG Remove')
@app.post('/remove-bg')
async def remove_background(image: UploadFile, post_process:float = Form(default = False)):
"""
Remove Background from an image
"""
try:
image = await image.read()
buffer = BytesIO(image)
except Exception as e:
e = traceback.format_exc()
raise HTTPException(status_code=420, detail=f"Image loading error :: {e}")
try:
data = remove_background(Image.open(buffer), bool(post_process))
return Response(content=data, media_type="image/png")
except Exception as e:
e = traceback.format_exc()
raise HTTPException(status_code=420, detail=f"Segmentation Error:: {e}")
if __name__ == "__main__":
uvicorn.run("fast_app:app", reload=True, debug = True, host = '0.0.0.0', port = 5678)

代码保存在文件fast_app.py中,我将代码运行为:python fast_app.py

有人能帮我解决这个问题吗?

您的端点函数名称remove_background与导入的函数冲突。

from io import BytesIO
import uvicorn
from fastapi import FastAPI, HTTPException, UploadFile, Form
from fastapi.responses import Response
import traceback
from remove_bg import remove as remove_background
from PIL import Image
app = FastAPI(title='BG Remove')
@app.post('/remove-bg')
async def remove_background_endpoint(image: UploadFile, post_process:float = Form(default = False)):
"""
Remove Background from an image
"""
try:
image = await image.read()
buffer = BytesIO(image)
except Exception as e:
e = traceback.format_exc()
raise HTTPException(status_code=420, detail=f"Image loading error :: {e}")
try:
data = remove_background(Image.open(buffer), bool(post_process))
return Response(content=data, media_type="image/png")
except Exception as e:
e = traceback.format_exc()
raise HTTPException(status_code=420, detail=f"Segmentation Error:: {e}")
if __name__ == "__main__":
uvicorn.run("fast_app:app", reload=True, debug = True, host = '0.0.0.0', port = 5678)