我根据官方文档使用fastapi上传文件,就像:
@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
file2store = await file.read()
# some code to store the BytesIO(file2store) to the other database
Run Code Online (Sandbox Code Playgroud)
当我使用 python requests lib 发送请求时:
f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)
Run Code Online (Sandbox Code Playgroud)
file2store 始终为空。有时(很少见),它可以获取文件字节,但几乎所有时间都是空的,所以我无法在另一个数据库上恢复文件。我还尝试了 'bytes' 而不是 'UploadFile',我得到了相同的结果。我的代码有什么地方不对,还是我使用fastapi上传文件的方式有问题?我google了很长时间,但没有成功。所以我在这里提出问题,希望知道答案的人可以帮助我。谢谢
我正在尝试将.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)