|
| 1 | +from fasthtml.common import * |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +plot_js = """ |
| 5 | +function createPlot(data) { |
| 6 | + const plot = Plot.rectY(data, Plot.binX({y: "count"},{x: d => d.value,fill:"steelblue"})).plot(); |
| 7 | + const div = document.querySelector("#plot"); |
| 8 | + div.replaceChildren(plot); |
| 9 | +} |
| 10 | +
|
| 11 | +// Set up initial load via HTMX |
| 12 | +htmx.on('htmx:afterSettle', evt => { |
| 13 | + if (evt.detail.target.id === 'data-store') { |
| 14 | + // The data is now properly JSON-encoded |
| 15 | + const data = JSON.parse(evt.detail.target.textContent); |
| 16 | + createPlot(data); |
| 17 | + } |
| 18 | +}); |
| 19 | +""" |
| 20 | + |
| 21 | +app, rt = fast_app( |
| 22 | + hdrs=(Script(src="https://cdn.jsdelivr.net/npm/d3@7"), |
| 23 | + Script( src="https://cdn.jsdelivr.net/npm/@observablehq/[email protected]"))) |
| 24 | + |
| 25 | +@rt |
| 26 | +def index(): |
| 27 | + return Div( |
| 28 | + H1(A("Observable", href="https://observablehq.com/@observablehq/plot", target="_blank"), " Plot Demo"), |
| 29 | + P("The data is randomly generated on the server and is fetched on initial page load."), |
| 30 | + P("Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request."), |
| 31 | + # On bytton click it sends a get request to the `get_data` route and puts the response in the `data-store` div |
| 32 | + Button("Fetch New Data", get=get_data, hx_target="#data-store", cls='btn btn-primary'), |
| 33 | + # Store for the JSON chart data |
| 34 | + Div(id="data-store", get=get_data, hx_trigger="load", hidden=True), |
| 35 | + # Plot container |
| 36 | + Div(id="plot"), |
| 37 | + # Include the JavaScript for the plot |
| 38 | + Script(plot_js) |
| 39 | + ) |
| 40 | + |
| 41 | +@rt |
| 42 | +def get_data(): |
| 43 | + # Generate sample data |
| 44 | + data = [{"value": float(x)} for x in np.random.randn(100)] |
| 45 | + # Return as proper JSON response |
| 46 | + return JSONResponse(data) |
| 47 | + |
| 48 | +serve() |
0 commit comments