Kanaries / pygwalker

PyGWalker: Turn your pandas dataframe into an interactive UI for visual analysis
https://kanaries.net/pygwalker
Apache License 2.0
10.7k stars 545 forks source link

How to use pygwalker in fastapi? #589

Open soundmemories opened 6 days ago

soundmemories commented 6 days ago

I used the following code to read the file and send it to pygwalker, but the returned result rendering has no effect and cannot produce dynamic rendering results like flask.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <h2>PyGwalker Flask App</h2>
    </div>
    <div>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="datafile">
            <input type="submit" value="Submit">
        </form>
    </div>
    <div>
        {{ html_str | safe}}
    </div>
</body>
</html>
from fastapi import Request, APIRouter, HTTPException, Form, File, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
import pandas as pd
import shutil
import pygwalker as pyg

router = APIRouter()
router.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

@router.get("/",  response_class=HTMLResponse)
async def index(request:Request):
    return templates.TemplateResponse('index.html',{"request":request})
    # return HTMLResponse(content='index.html', status_code=200)

@router.post("/upload", response_class=HTMLResponse)
def upload_csv(request: Request, datafile: UploadFile = File(...)):
    with open(f"static/{datafile.filename}", "wb") as buffer:
        shutil.copyfileobj(datafile.file, buffer)
    df = pd.read_csv(f"static/{datafile.filename}", encoding="utf-8")
    html_str = pyg.walk(df, html_string=True)
    return templates.TemplateResponse('index.html',{"request":request,"html_str":html_str})
longxiaofei commented 2 days ago

html_str = pyg.walk(df, html_string=True) replace to html_str = pyg.to_html(df).

or

You can refer to https://github.com/Kanaries/pygwalker/blob/main/examples/web_server_demo.py