Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use pygwalker in fastapi? #589

Closed
soundmemories opened this issue Jul 5, 2024 · 1 comment
Closed

How to use pygwalker in fastapi? #589

soundmemories opened this issue Jul 5, 2024 · 1 comment

Comments

@soundmemories
Copy link

soundmemories commented Jul 5, 2024

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
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants