2.9 KiB
2.9 KiB
Serving Dynamic HTML Content in Vuer
Overview
Vuer allows you to serve dynamic content by adding custom route handlers to your application server.
Implementation Method
You can register a dynamic HTML handler using the add_route() method.
Basic Example
from vuer import Vuer
app = Vuer()
counter = 0
def dynamic_html_handler():
global counter
counter += 1
template = f"""
<!DOCTYPE html>
<html>
<head><title>Dynamic HTML</title></head>
<body>
<h1>Counter Value: {counter}</h1>
</body>
</html>
"""
return template
app.add_route("/dynamic", dynamic_html_handler, method="GET")
app.run()
Usage
After starting the server, visit http://localhost:8012/dynamic to see the dynamically generated content. The counter value will update on each page reload.
Key Parameters
- Route path: Specify the URL endpoint (e.g., "/dynamic")
- Handler function: Returns HTML content as a string
- HTTP method: Specify the request method (e.g., "GET")
Advanced Example with JSON Response
from vuer import Vuer
import json
app = Vuer()
def json_api_handler():
data = {
"status": "success",
"data": {
"message": "Hello from Vuer!",
"timestamp": time.time()
}
}
return json.dumps(data)
app.add_route("/api/data", json_api_handler, method="GET")
app.run()
Multiple Routes
You can add multiple routes to your application:
from vuer import Vuer
app = Vuer()
def home_handler():
return "<h1>Home Page</h1>"
def about_handler():
return "<h1>About Page</h1>"
def api_handler():
return '{"status": "ok"}'
app.add_route("/", home_handler, method="GET")
app.add_route("/about", about_handler, method="GET")
app.add_route("/api/status", api_handler, method="GET")
app.run()
Best Practices
- Return strings: Handler functions should return HTML or text as strings
- Use templates: Consider using template engines for complex HTML
- Handle errors: Add error handling in your route handlers
- Set content types: For JSON responses, consider setting appropriate headers
Combining with 3D Scenes
You can serve both dynamic HTML content and 3D scenes from the same Vuer application:
from vuer import Vuer
from vuer.schemas import Scene, Box
import asyncio
app = Vuer()
# Add dynamic HTML route
def stats_handler():
return f"""
<html>
<body>
<h1>Vuer Statistics</h1>
<p>Server running on port 8012</p>
</body>
</html>
"""
app.add_route("/stats", stats_handler, method="GET")
# Add 3D scene
@app.spawn
async def main(session):
session.set @ Scene(
Box(
args=[0.1, 0.1, 0.1],
position=[0, 0, 0],
key="box",
),
)
while True:
await asyncio.sleep(1.0)
app.run()
Source
Documentation: https://docs.vuer.ai/en/latest/tutorials/basics/adding_html_handler.html