-
Notifications
You must be signed in to change notification settings - Fork 7
08 Using Python and HTML
In user code, you have access to the stable APIs, by importing kaithem.api.\<module\>. Documentation
for these can be found here, generated with handsdown.
Go to the modules page and create a new module. On the module's page create an event.


On the event page you get three boxes, setup, trigger, and action. When the event loads, the setup code runs. It is scoped like as if it were code directly in a module.
The system will poll the trigger at a configurable rate. When it becomes true, or repeatedly while true, the action runs.
The action is a function body, you must use the global keyword to set things declared in the setup.
All events and pages have access to a shared "module" object shared between everything in a module, and the "kaithem" API object documented here

Back on the same module UI, create a page. You will see a page body, where you can place HTML, and also use Jinja templates to add dynamic content.
There is also a box for setup code that runs once when the page is set up, and handler code which runs every load. In these you can provide variables to be accessed by the page template syntax.
You can select which permissions if any should be required to access the page.
If you're on V0.79.0 or later, try this code in the HTML box if a page, with the jinja2 template engine selected.
What it does is uses the default pagetemplate.j2.html that almost all Kaithem pages use.
It calls the render function of the widget to get some JS code that creates an APIWidget, which is a websocket link between frontend and backend.
It gives the backend a simple echo callback, and the frontend sends a basic test message, which should be echoed back, to be printed in the browser console.
{% extends "pagetemplate.j2.html" %}
{% block title %} {basename} {% endblock %}
{% block body %}
{{t.render("api")}}
<script type="module">
import { kaithemapi, APIWidget} from "/static/js/widget.mjs"
let api = new APIWidget("widget_id")
api.upd = (val) => alert(val)
api.send("MyValue")
</script>
{% endblock %}And this code in the setup box:
from kaithem.api.widgets import APIWidget
t = APIWidget(echo=False, id="YourWidgetID")
def f(user: str, value, connection_id: str):
t.send_to(f"Echoing {value} from {user} on {connection_id}", connection_id)
t.attach2(f)
# This returns an HTML string to embed in a page
# which also includes /static/js/widget.js
t.render("js_var_name")