[英]FastAPI - How to read an json file while using UploadFile
from typing import List, Optional
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
app = FastAPI(debug=True)
@app.post("/uploadfiles/")
def create_upload_files(upload_file: UploadFile = File(...)):
json_data = ?? upload_file ??
result = model().calculate(json_data)
return { "estimation": result}
@app.get("/")
async def main():
content = """
<body>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="upload_file" type="file" multiple>
<input type="submit">
</form>
</body>
"""
return HTMLResponse(content=content)
I have the above FastAPI app.我有上面的 FastAPI 应用程序。 I need to upload a json file.我需要上传一个json文件。 Thus the upload_file is a json file.因此,upload_file 是一个 json 文件。 Also the model() instance uses a method calculate that takes as input json data.此外,model() 实例使用了一种将 json 数据作为输入的方法。 I struggle on how to decode the upload_file from Fast_API to dictionairy format.我在如何将上传文件从 Fast_API 解码为字典格式方面苦苦挣扎。
I tried upload_file.read() but this returns a bytes array我试过 upload_file.read() 但这返回一个字节数组
Could you please help?能否请你帮忙?
You can use the standard json
module to parse the content by using json.load()
--(Doc) from an uploaded JSON file as您可以使用标准json
模块通过使用json.load()
--(Doc)从上传的 JSON 文件解析内容作为
from fastapi import FastAPI, File, UploadFile
import json
app = FastAPI(debug=True)
@app.post("/uploadfiles/")
def create_upload_files(upload_file: UploadFile = File(...)):
json_data = json.load(upload_file.file)
return {"data_in_file": json_data}
Thus, you will have the JSON contents in your json_data
variable.因此,您的json_data
变量中将包含 JSON 内容。
Alternatively, you can use json.loads()
--(Doc) function as或者,您可以使用json.loads()
--(Doc)函数作为
json_data = json.loads(upload_file.file.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.