我被要求上传一个包含学生详细信息的 CSV 文件,并要求用户输入学生 ID(在本例中为索引)并打印显示该特定学生详细信息的相应行。 输出在编译器内打印得很好,无论是字典还是 JSON 格式。但是,当定义自定义路由(即 /student/{data_id})并请求路由返回输入中学生 ID 的 JSON 或字典格式时。我在 URL 中收到此消息:
{"detail":[{"loc":["query","data_json_output"],"msg":"field required","type":"value_error.missing"}]}
这是代码。
import requests
import json
import pandas as pd
from fastapi import FastAPI
import uvicorn
#Reading the CSV file
df_data_csv = pd.read_csv("data.csv")
data_dict = df_data_csv.to_dict(orient='index')
#Input the student ID
data_id =int(input("Enter the id of the student: "))
#Converting to Dictionary (Just trying)
data_dict_output = (data_dict[data_id])
#Converting to JSON
data_json_output = json.dumps(data_dict_output)
print(f"The JSON format is {data_json_output}")
app = FastAPI()
#The Root. Please ignore this line
@app.get("/")
def read_root():
return {"Test"}
#Custom route (Which is where I am facing the issue)
@app.get("/student/{data_id}")
def read_item(data_json_output:str):
#Returning the input data in JSON format
return data_json_output
uvicorn.run(app,host="0.0.0.0",port="8080")
当输入自定义路线时,我需要获取我在代码中请求的数据。例如,如果输入为 0,则输出应为
{"Name": "A", "Height": 4, "Weight": 60, "Grade": "J"}
你能做这样的事吗?
import pandas as pd
from fastapi import FastAPI
import uvicorn
# Reading the CSV file
df_data_csv = pd.read_csv('data.csv')
data_dict = df_data_csv.to_dict(orient='index')
app = FastAPI()
@app.get("/")
def read_root():
return {"Test"}
@app.get("/student/{data_id}")
def read_item(data_id: int):
return data_dict[data_id]
uvicorn.run(app, host="0.0.0.0", port="8080")