-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi_example.py
More file actions
96 lines (79 loc) · 2.57 KB
/
Copy pathfastapi_example.py
File metadata and controls
96 lines (79 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""FastAPI example application with Counter component."""
import sys
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from jinjax import Catalog
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from component_framework.adapters.fastapi import create_component_routes
from component_framework.adapters.jinjax_renderer import JinjaxRenderer
from component_framework.components.counter import Counter
from component_framework.core import Component
# Initialize FastAPI
app = FastAPI(title="Component Framework Demo")
# Setup Jinjax
templates_dir = Path(__file__).parent.parent / "templates" / "components"
catalog = Catalog()
catalog.add_folder(templates_dir)
catalog.jinja_env.autoescape = True
# Configure renderer globally for all components
renderer = JinjaxRenderer(catalog)
Component.renderer = renderer
# Add component routes
create_component_routes(app)
@app.get("/", response_class=HTMLResponse)
async def index():
"""Serve demo page."""
# Initial render of counter
counter = Counter(initial=0)
result = counter.dispatch()
return f"""
<!DOCTYPE html>
<html>
<head>
<title>Component Framework Demo</title>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<style>
body {{
font-family: system-ui, -apple-system, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
}}
h1 {{
text-align: center;
color: #333;
}}
.info {{
background: #e3f2fd;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
}}
</style>
</head>
<body>
<h1>Component Framework Demo</h1>
<div class="info">
<h3>How it works:</h3>
<ul>
<li>Server-side components with state management</li>
<li>HTMX for dynamic updates</li>
<li>No JavaScript framework required</li>
<li>Click the buttons to interact!</li>
</ul>
</div>
{result["html"]}
<div class="info" style="margin-top: 30px;">
<h3>Component State:</h3>
<pre id="state-display">{result["state"]}</pre>
</div>
</body>
</html>
"""
if __name__ == "__main__":
import uvicorn
print("Starting Component Framework Demo")
print("Open http://localhost:8000")
uvicorn.run(app, host="0.0.0.0", port=8000)