python - 将 csv 文件发送到 fastAPI 并取回新文件

标签 python pandas api fastapi

我有这个非常简单的代码,它获取一个字典作为输入并返回一个字典:

app = FastAPI()

class User(BaseModel):
    user_name: dict


@app.post("/")
def main(user: User):
   ## some processing
   return user
我用以下 python 代码调用它:
import requests
import json 
import pandas as pd

df = pd.read_csv("myfile.csv")
data = {}
data["user_name"] = df.to_dict()
headers = {'content-type': 'application/json'}
url = 'http://localhost:8000/'
resp = requests.post(url,data=json.dumps(data), headers=headers )
resp
现在,我想做类似的事情,但不是通过来自 python 的请求发送数据
我想上传一个本地文件,将它发送到 API 并获取一个处理过的 .csv 文件。
现在我有以下代码来上传文件:
from typing import Optional
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel
from typing import List
from fastapi.responses import HTMLResponse


app = FastAPI()

class User(BaseModel):
    user_name: dict

@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}


@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}


@app.get("/")
async def main():
    content = """
<body>
<form action="/files/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
</body>
    """
    return HTMLResponse(content=content)
enter image description here
这允许我选择和加载文件:
enter image description here
但是当我点击发送时,我被重定向到:http://localhost:8000/uploadfiles/并收到以下错误:
{"detail":"Method Not Allowed"}
如何将要处理的文件发送到 API 并返回文件作为响应?

最佳答案

我复制了您的代码,但遇到了同样的错误。经过FastAPI documentation for requesting files , 提到

To receive uploaded files, first install python-multipart.

E.g. pip install python-multipart.

This is because uploaded files are sent as "form data".


安装库后python-multipart ,代码完美运行。
引用文献:
  • https://andrew-d.github.io/python-multipart/
  • 关于python - 将 csv 文件发送到 fastAPI 并取回新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62749365/

    相关文章:

    python - 在python中获取非字符串值作为json键

    Python dask_ml 线性回归 多个常量列检测到错误

    python - 为什么 pandas bool 过滤会产生 float ?

    Python:仅使用原始字符串发送 POST 请求

    python - 使用 `query().join()` 填充 SQLAlchemy 中的关系

    python - 具有 3 列的 DataFrame 到字典的字典

    java - 微软翻译API问题

    node.js - 测试 API 包装器

    java - 何时重新编译 JNI 绑定(bind)和客户端代码?

    python zlib如何解压多个对象