简体   繁体   English

如何使用 FastAPI 以 JSON 格式返回 a.csv 文件/Pandas DataFrame?

[英]How to return a .csv file/Pandas DataFrame in JSON format using FastAPI?

I have a .csv file that I want to render in a FastAPI app.我有一个要在 FastAPI 应用程序中呈现的.csv文件。 I only managed to render the .csv file in JSON format as follows:我只设法以 JSON 格式呈现.csv文件,如下所示:

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

When I tried returning directly pd.read_csv(csv_file_name,sep=",").to_json(json_file_name) , it works, as it returns a string.当我尝试直接返回pd.read_csv(csv_file_name,sep=",").to_json(json_file_name)时,它可以工作,因为它返回一个字符串。

How should I proceed?我应该如何进行? I believe this is not the good way to do it.我相信这不是这样做的好方法。

The below shows four different ways of returning the data from a .csv file/Pandas DataFrame.下面显示了从.csv文件/Pandas DataFrame 返回数据的四种不同方式。

Option 1 is to convert the file data into JSON and then parse it into a dict .选项 1是将文件数据转换为JSON ,然后将其解析为dict You can optionally change the orientation of the data using the orient parameter in the to_json() method.您可以选择使用to_json()方法中的orient参数更改数据的方向。

  • Update 1 : Using to_dict() method might be a better option, as there is no need for parsing the JSON string.更新 1 :使用to_dict()方法可能是更好的选择,因为不需要解析JSON字符串。
  • Update 2 : When using to_dict() method and returning the dict , FastAPI, behind the scenes, automatically converts that return value into JSON , using the jsonable_encoder .更新 2 :当使用to_dict()方法并返回dict时,FastAPI 在幕后使用jsonable_encoder自动将该返回值转换为JSON Thus, to avoid that extra processing, you could still use to_json() method, but instead of parsing the JSON string, put it in a Response and return it directly, as shown in the example below.因此,为了避免额外的处理,您仍然可以使用to_json()方法,但不是解析JSON字符串,而是将其放入Response并直接返回,如下例所示。

Option 2 is to return the data in string format, using to_string() method.选项 2是使用to_string()方法以string格式返回数据。

Option 3 is to return the data as an HTML table, using to_html() method.选项 3是使用 to_html to_html()方法将数据作为HTML表返回。

Option 4 is to return the file as is using FastAPI's FileResponse .选项 4是使用 FastAPI 的FileResponse返回file

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 directly
    #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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM