Python FastAPI:上传文本文件会导致内部服务器错误

问题描述

我正在使用FastAPI编写API以上传文本文件并读取txt文件内容

@app.post('/read_txt_file',response_class=PlainTextResponse)
async def upload_file_and_read(file: UploadFile = File(...),fileExtension: str = Form(...)):
 
    if(fileExtension == 'txt'):
        raw_txt = readTxt(file)
        raw_txt = raw_txt.decode()

    return raw_txt


def readTxt(file):
    return file.read()

上面的这段代码引发内部服务器错误。我可以知道如何纠正它吗?

日志:

文件 “ /home/readerProject/.venv/lib/python3.7/site-packages/fastapi/routing.py”, 行183,在应用程序中 依赖=依赖,值=值,is_coroutine = is_coroutine文件 “ /home/readerProject/.venv/lib/python3.7/site-packages/fastapi/routing.py”, 第133行,在run_endpoint_function中 返回awaitDependant.call(**值)

upload_file_and_read中的文件“ /home/readerProject/api.py”,第28行 raw_txt = raw_txt.decode()

AttributeError:“协程”对象没有属性“ decode” /home/readerProject/.venv/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py:396: RuntimeWarning:从未等待协程'UploadFile.read'
self.transport.close()RuntimeWarning:启用tracemalloc以获取 对象分配回溯

解决方法

您必须使用 readTxt(...) 语法调用await函数

raw_txt = await readTxt(file)
         ^^^^^^^

最小的可验证示例

from fastapi import FastAPI,UploadFile,File

app = FastAPI()


@app.post('/read_txt_file')
async def upload_file_and_read(
        file: UploadFile = File(...),):
    if file.content_type.startswith("text"):
        text_binary = await readTxt(file) # call `await`
        response = text_binary.decode()
    else:
        # do something
        response = file.filename

    return response


def readTxt(file):
    return file.read()

作为旁注,您可以通过检查可用于识别文件扩展名的 file.content_type 来检索上下文类型