FastAPI 上传大于 100kb 的文件时出错

问题描述 投票:0回答:1

我正在尝试创建一个用于上传文件的端点。但是,如果文件大于 100Kb,我会收到 400 Bad Request 错误。我的猜测是它没有足够的时间来上传文件。

我的函数代码是这样的:

import uvicorn
from fastapi import FastAPI, File, UploadFile
import pathlib

app = FastAPI(title='Tool', description='Tool descr', version='0.0.1')

uploads = 'uploads'
uploads_dir = pathlib.Path(os.getcwd(), uploads)

@app.post('/api/upload/')
async def upload_file(file: UploadFile=File(...)):
    """
    Upload the file to be processed.
    """
    print(file)
    async with aiofiles.open(file.file, 'rb') as fin:
        exfile = fin.read() 
    file_name = pathlib.Path(uploads_dir, file.filename)
    async with aiofiles.open(f'{file_name}', 'wb') as f:
        await f.write(exfile)
    return {'filename': file.filename, 
                'content-type': file.content_type}

if __name__ == '__main__':
    uvicorn.run('main:app', host='127.0.0.1', port=5003, log_level='info')   

因此,例如,如果是文本文件或二进制文件

did not find CR at end of boundary
,服务器会向我提供错误请求答案,其中包含
Did not find boundary character 198 at index 2

邮递员错误:

{
    "detail": "There was an error parsing the body"
}

服务器返回的错误基本上是这样的:

Did not find boundary character 145 at index 2
INFO:     127.0.0.1:58032 - "POST /api/upload/ HTTP/1.1" 400 Bad Request
WARNING:  Invalid HTTP request received.
INFO:     127.0.0.1:58033 - "POST /api/upload HTTP/1.1" 307 Temporary Redirect
<starlette.datastructures.UploadFile object at 0x000001CCCF62AE80>
INFO:     127.0.0.1:58033 - "POST /api/upload/ HTTP/1.1" 200 OK
INFO:     127.0.0.1:58156 - "POST /api/upload HTTP/1.1" 307 Temporary Redirect
<starlette.datastructures.UploadFile object at 0x000001CCCF62E7F0>
INFO:     127.0.0.1:58156 - "POST /api/upload/ HTTP/1.1" 200 OK
INFO:     127.0.0.1:58190 - "POST /api/upload HTTP/1.1" 307 Temporary Redirect
Did not find CR at end of boundary (54)
INFO:     127.0.0.1:58191 - "POST /api/upload/ HTTP/1.1" 400 Bad Request

这些是一些请求,其中一些请求成功(文件大小约为 50k),其他请求未作为“错误请求”处理。

python-3.x asynchronous fastapi
1个回答
0
投票

这似乎是 Postman 中的错误,而不是 Fast API 中的错误。 为了仔细检查情况是否如此,我使用 pytest 创建了一个测试,如下所示,它没有运行任何问题:

def test_create_large_file(client: TestClient):
test_file = "test_file.txt"
with open(test_file, "w+b") as f:
    // 30MBs file
    f.write(("x" * (30 * 1024 * 1024)).encode(encoding="utf-8"))
    files = {"file": (test_file, f, "text/plain")}
    response = client.post(
        "/api/v1/files",
        files=files,
    )
    assert response.status_code == 200
© www.soinside.com 2019 - 2024. All rights reserved.