如何在FastAPI中从数据帧呈现JSON数据、如何在、FastAPI、JSON

2023-09-03 11:25:44 作者:情毒

我有一个CSV文件,我希望在fast API应用程序中呈现该文件。我只设法将TE CSV呈现为json格式,如下所示:

def transform_question_format(csv_file_name):

    json_file_name = f"{csv_file_name[:-4]}.json"

    # transforms the csv file into json file
    pd.read_csv(csv_file_name ,sep=",").to_json(json_file_name)

    with open(json_file_name, "r") as f:
        json_data = json.load(f)

    return json_data

@app.get("/questions")
def load_questions():

    question_json = transform_question_format(question_csv_filename)

    return question_json

当我直接尝试pd.read_csv(csv_file_name ,sep=",").to_json(json_file_name)作为回报时,它确实工作,因为它返回一个字符串。 我应该如何继续呢?我认为这不是一个好办法。

推荐答案

ARP和RARP各用在什么场合

下面显示了从csv文件返回数据的四种不同方法。

选项1是以JSON的形式获取文件数据并将其解析为dict。您可以选择使用to_json()方法中的orient参数更改数据的方向。

更新1:使用to_dict()方法可能是更好的选择,因为不需要分析JSON字符串。 更新2:在使用to_dict()方法并在后台返回dictFastAPI时,使用jsonable_encoder将返回值返回到JSON中。因此,为了避免额外的工作,您仍然可以使用to_json()方法,但不是解析JSON字符串,而是将其放在Response中并直接返回,如下例所示。

选项2是使用to_string()方法以string形式返回数据。

选项3是使用to_html()方法以HTML表的形式返回数据。

选项4是使用FastAPI的FileResponse按原样返回文件。

from fastapi import FastAPI, Response
from fastapi.responses import FileResponse
from fastapi.responses import HTMLResponse
import pandas as pd
import json

df = pd.read_csv("file.csv")
app = FastAPI()

def parse_csv(df):
    res = df.to_json(orient="records")
    parsed = json.loads(res)
    return parsed
    
@app.get("/questions")
def load_questions():
    return Response(df.to_json(orient="records"), media_type="application/json")  # Option 1 (Updated 2): Return as `JSON`
    #return df.to_dict(orient="records")  # Option 1 (Updated 1): Return as dict (encoded to JSON behind the scenes)
    #return parse_csv(df)  # Option 1: Parse the JSON string and return as dict (encoded to JSON behind the scenes)
    #return df.to_string()  # Option 2: Return as string
    #return HTMLResponse(content=df.to_html(), status_code=200)  # Option 3: Return as HTML Table
    #return FileResponse(path="file.csv", filename="file.csv")   # Option 4: Return as File