如何使用邮递员将文件发送到fastapi端点

编程入门 行业动态 更新时间:2024-10-28 18:30:26
本文介绍了如何使用邮递员将文件发送到fastapi端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我面临使用邮递员测试api的困难.通过大幅度的文件上传功能可以正常工作,我在硬盘上保存了一个文件.我想了解如何与邮递员一起进行此操作.我使用标准方式来处理在使用django,flask时使用的文件.

I faced the difficulty of testing api using postman. Through swagger file upload functionality works correctly, I get a saved file on my hard disk. I would like to understand how to do this with postman. I use the standard way to work with files which I use when working with django, flask.

Body -> form-data: key=file, value=image.jpeg

但是使用fastapi时,我会得到一个错误

But with fastapi, I get an error

127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity

main.py

@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}

我也尝试过 body->二进制文件:image.jpeg .但是得到了相同的结果

I also tried body -> binary: image.jpeg . But got the same result

推荐答案

我的代码:

from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post("/file/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename}

邮递员中的设置

如 github/tiangolo/fastapi/issues/1653 所述a>,文件的参数名称是您必须使用的键值.在使用key = file和value = image.png(或任何其他值)之前.相反,FastAPI接受file = image.png.因此,由于文件是必需的但不存在该错误(至少,不存在具有该名称的密钥),因此导致错误.

As stated in github/tiangolo/fastapi/issues/1653, the parameter name for the file is the key value that you have to use. Before you were using key=file and value=image.png (or whatever). Instead, FastAPI accepts file=image.png. Thus the error, since the file is necessary, but it is not present (at least, the key with that name is not present).

我用Postman v7.16.1进行了测试

I tested it with Postman v7.16.1

让我知道您是否仍然有问题.

Let me know if you still have problems.

更多推荐

如何使用邮递员将文件发送到fastapi端点

本文发布于:2023-10-29 06:08:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:邮递员   发送到   如何使用   文件   fastapi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!