-2

How could I convert a file into a dataframe using the following code?

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    df = pd.read_csv("")
    print(df)
    return {"filename": file.filename}
Chris
  • 4,940
  • 2
  • 7
  • 28

1 Answers1

0

Option 1

Convert the bytes into a string and then load it into an in-memory text buffer (i.e., StringIO), which can be converted into a dataframe:

from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import StringIO

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    s = str(contents,'utf-8')
    data = StringIO(s) 
    df = pd.read_csv(data)
    data.close()
    return {"filename": file.filename}

Option 2

Use an in-memory bytes buffer instead (i.e., BytesIO), thus saving you the step of converting the bytes into a string:

from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import BytesIO

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    data = BytesIO(contents)
    df = pd.read_csv(data)
    data.close()
    return {"filename": file.filename}
Chris
  • 4,940
  • 2
  • 7
  • 28
  • chris could you tell me one more thing how can i use this df variable in other functions too. – Abhishek Vashishth Mar 16 '22 at 16:24
  • If you need read-only access to that variable, and you never expect it to be changed by some other process/request before reading it, as well you don't plan having [several workers](https://fastapi.tiangolo.com/deployment/server-workers/) at the same time (which would have their own memory), you could either declare it as `global`, as described [here](https://stackoverflow.com/a/71383736/17865804), or [store it on the app instance](https://www.starlette.io/applications/#accessing-the-app-instance). Otherwise, please have a look at [this](https://stackoverflow.com/q/65686318/17865804). – Chris Mar 19 '22 at 09:46