|
| 1 | +""" |
| 2 | +pygwalker>=0.4.8.6 |
| 3 | +
|
| 4 | +This is poc for PygWalker integration with FastAPI. |
| 5 | +
|
| 6 | +If you want to use Graphic-Walker in your web application, the best practice is to use Graphic-Walker as a separate front-end component for development, rather than using pygwalker. |
| 7 | +
|
| 8 | +run it: uvicorn web_server_demo:app --reload --port 8000 |
| 9 | +view it: http://127.0.0.1:8000/pyg_html/test0 |
| 10 | +""" |
| 11 | +from typing import Dict, Any |
| 12 | +import json |
| 13 | + |
| 14 | +from fastapi import FastAPI, Body |
| 15 | +from fastapi.responses import HTMLResponse, JSONResponse |
| 16 | +from pygwalker.api.pygwalker import PygWalker |
| 17 | +from pygwalker.communications.base import BaseCommunication |
| 18 | +from pygwalker.utils.encode import DataFrameEncoder |
| 19 | +from pygwalker import GlobalVarManager |
| 20 | +import pandas as pd |
| 21 | + |
| 22 | +app = FastAPI() |
| 23 | + |
| 24 | + |
| 25 | +def init_pygwalker_entity_map() -> Dict[str, PygWalker]: |
| 26 | + """Register PygWalker entity""" |
| 27 | + GlobalVarManager.set_privacy("offline") |
| 28 | + df = pd.read_csv("https://kanaries-app.s3.ap-northeast-1.amazonaws.com/public-datasets/bike_sharing_dc.csv") |
| 29 | + walker = PygWalker( |
| 30 | + gid="test0", |
| 31 | + dataset=df, |
| 32 | + field_specs=None, |
| 33 | + spec="", |
| 34 | + source_invoke_code="", |
| 35 | + theme_key="vega", |
| 36 | + appearance="light", |
| 37 | + show_cloud_tool=False, |
| 38 | + use_preview=False, |
| 39 | + kernel_computation=True, |
| 40 | + use_save_tool=False, |
| 41 | + is_export_dataframe=False, |
| 42 | + kanaries_api_key="", |
| 43 | + default_tab="vis", |
| 44 | + cloud_computation=False, |
| 45 | + gw_mode="explore", |
| 46 | + ) |
| 47 | + comm = BaseCommunication(walker.gid) |
| 48 | + walker._init_callback(comm) |
| 49 | + return { |
| 50 | + walker.gid: walker |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +pygwalker_entity_map = init_pygwalker_entity_map() |
| 55 | + |
| 56 | + |
| 57 | +@app.post("/_pygwalker/comm/{gid}") |
| 58 | +def pygwalker_comm(gid: str, payload: Dict[str, Any] = Body(...)): |
| 59 | + if gid not in pygwalker_entity_map: |
| 60 | + return {"success": False, "message": f"Unknown gid: {gid}"} |
| 61 | + |
| 62 | + comm_obj = pygwalker_entity_map[gid].comm |
| 63 | + result = comm_obj._receive_msg(payload["action"], payload["data"]) |
| 64 | + return JSONResponse(content=json.loads(json.dumps(result, cls=DataFrameEncoder))) |
| 65 | + |
| 66 | + |
| 67 | +@app.get("/pyg_html/{gid}") |
| 68 | +def pyg_html(gid: str): |
| 69 | + walker = pygwalker_entity_map[gid] |
| 70 | + props = walker._get_props("web_server") |
| 71 | + props["communicationUrl"] = "_pygwalker/comm" |
| 72 | + html = walker._get_render_iframe(props, True) |
| 73 | + return HTMLResponse(content=html) |
0 commit comments