Python FastAPI:上传文本文件时出现内部服务器错误

Python FastAPI: Uploading Text file gives internal server error

我正在使用 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()

以上代码引发内部服务器错误。我可以知道如何更正吗?

日志:

File "/home/readerProject/.venv/lib/python3.7/site-packages/fastapi/routing.py", line 183, in app dependant=dependant, values=values, is_coroutine=is_coroutine File "/home/readerProject/.venv/lib/python3.7/site-packages/fastapi/routing.py", line 133, in run_endpoint_function return await dependant.call(**values)

File "/home/readerProject/api.py", line 28, in upload_file_and_read raw_txt = raw_txt.decode()

AttributeError: 'coroutine' object has no attribute 'decode' /home/readerProject/.venv/lib/python3.7/site-packages/uvicorn/protocols/http/h11_impl.py:396: RuntimeWarning: coroutine 'UploadFile.read' was never awaited
self.transport.close() RuntimeWarning: Enable tracemalloc to get the object allocation traceback

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

raw_txt = <b>await</b> 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"):
        <b>text_binary = await readTxt(file) # call `await`</b>
        response = text_binary.decode()
    else:
        # do something
        response = file.filename

    return response


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

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