Skip to content

Instantly share code, notes, and snippets.

@tobyshooters
Last active January 18, 2024 03:54
Show Gist options
  • Save tobyshooters/5aa0b729e961661156f903817e56226b to your computer and use it in GitHub Desktop.
Save tobyshooters/5aa0b729e961661156f903817e56226b to your computer and use it in GitHub Desktop.
web bootstrap
<script>
const $ = ({
el, // existing string type to create
pr = null, // parent node
at = {}, // attributes
st = {}, // style
ev = {}, // events, element injected as first parameter
ih = "" // innerHTML
}) => {
let n = el;
if (typeof el === "string") {
n = document.createElement(el);
}
if (pr) {
pr.appendChild(n);
}
for (const [k, v] of Object.entries(at)) {
n.setAttribute(k, v);
}
for (const [k, v] of Object.entries(st)) {
n.style.setProperty(k, v);
}
for (const [e, f] of Object.entries(ev)) {
const p = (...args) => f(n, ...args);
n.addEventListener(e, p);
}
n.innerHTML = ih;
return n;
}
const render = (db) => {
document.body.innerHTML = "";
window.db = db;
const count = db.count || 0;
const el = $({
el: "button",
pr: document.body,
st: {
"background": `hsl(${17 * count % 360}, 50%, 50%)`,
"border-radius": "11px",
},
ev: {
click: () => send({
op: "PUT",
path: ["count"],
data: count + 1
})
}
})
el.innerHTML = count;
}
const ws = new WebSocket("ws://localhost:1234/ws")
const send = (msg) => ws.send(JSON.stringify(msg));
window.send = send;
ws.onopen = () => send({op: "SUBSCRIBE", path: []});
ws.onmessage = (e) => render(JSON.parse(e.data));
</script>
import os
import json
import tornado.ioloop
import tornado.web
import tornado.websocket
class DB:
def __init__(self):
self.path = "./db.json";
self.db = {}
self.callbacks = []
if os.path.exists(self.path):
self.db = json.load(open(self.path, "r"))
def op(self, op, path, data):
location = self.db
for i in range(len(path) - 1):
location = location[path[i]]
if op == "SUBSCRIBE":
self.callbacks.append(data)
elif op == "PUT":
location[path[-1]] = data
elif op == "DELETE":
del location[path[-1]]
for cb in self.callbacks:
cb(self.db)
json.dump(self.db, open("./db.json", "w"), indent=2)
db = DB()
class WSHandler(tornado.websocket.WebSocketHandler):
def on_message(self, msg):
msg = json.loads(msg)
if msg["op"] == "SUBSCRIBE":
def cb(db):
if self.ws_connection:
self.write_message(json.dumps(db))
msg["data"] = cb
db.op(msg["op"], msg["path"], msg["data"])
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("interface.html")
if __name__ == "__main__":
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/ws', WSHandler),
], debug=True)
app.listen(1234)
tornado.ioloop.IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment