问题描述
我正在尝试通过一些方式将一些 json 内容从客户端传递到服务器
使用 FastAPI 构建的简单 REST API(使用 uvicorn)。
如果我将文件内容包装成 pydantic.BaseModel
像这样
app = FastAPI()
class ConfigContents(BaseModel):
str_contents: str
@app.post("/writeFile/{fn}")
async def write_file(fn: str,contents: ConfigContents):
filepath = "/some_server_dir/" + fn
with open(filepath,"w") as f:
f.write(contents.str_contents)
return contents
我基本上得到了我想要的,即在客户端(使用请求库),我可以执行
response = requests.post("http://127.0.0.1:8000/writeFile/my_file.json",data=json.dumps({"str_contents": contents}))
并最终将文件内容分配给 response
并写入“服务器”上的文件。
我的问题是:是否有更简单的方法来实现相同的目标,例如刚刚路过
json 内容作为字符串发送给服务器,无需将其包装到模型中?
解决方法
如果不想使用 Pydantic 模型,也可以使用 Body 参数。请参阅 Body - Multiple Parameters: Singular values in body 的文档。
The doc for Body 说明您可以使用 Body(...)
默认值声明任何参数,使其成为要从请求正文中检索的值。
这意味着您可以简单地删除您的 pydantic 模型并将您的 write_file
函数声明更改为:
async def write_file(fn: str,contents=Body(...)):
...
但是,在我看来,这将是一个(非常)糟糕的主意。 FastApi 使用 pydantic
模型来验证提供的数据并生成方便的 API 文档。
我宁愿建议改进和开发您用来获得更好的自动验证和文档的 pydantic
模型。