我正在尝试将.csv
文件上传到 FastAPI 服务器,然后将其转换为 JSON 并将其返回给客户端。但是,当我尝试直接处理它(而不将其存储在某处)时,我收到此错误:
Error : FileNotFoundError: [Error 2] No such file or directory : "testdata.csv"
Run Code Online (Sandbox Code Playgroud)
这是我的 FastAPI 代码:
async def upload(file: UploadFile = File(...)):
data = {}
with open(file.filename,encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for rows in csvReader:
key = rows['No']
data[key] = rows
return {data}```
Run Code Online (Sandbox Code Playgroud) 我遇到了使用邮递员测试 api 的困难。通过 swagger 文件上传功能正常工作,我在硬盘上得到了一个保存的文件。我想了解如何用邮递员做到这一点。我使用标准方式来处理我在使用 django、flask 时使用的文件。
Body -> form-data: key=file, value=image.jpeg
Run Code Online (Sandbox Code Playgroud)
但是使用fastapi,我收到一个错误
127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity
Run Code Online (Sandbox Code Playgroud)
主文件
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
img = await file.read()
if file.content_type not in ['image/jpeg', 'image/png']:
raise HTTPException(status_code=406, detail="Please upload only .jpeg files")
async with aiofiles.open(f"{file.filename}", "wb") as f:
await f.write(img)
return {"filename": file.filename}
Run Code Online (Sandbox Code Playgroud)
我也试过了body -> binary: image.jpeg
。但得到了相同的结果
我想将文件上传到 FastAPI 后端并将其转换为 Pandas DataFrame。但是,我似乎不明白如何使用 FastAPI 的UploadFile
对象来做到这一点。更具体地说,我应该将什么传递给该pd.read_csv()
函数?
这是我的 FastAPI 端点:
@app.post("/upload")
async def upload_file(file: UploadFile):
df = pd.read_csv("")
print(df)
return {"filename": file.filename}
Run Code Online (Sandbox Code Playgroud)