Package: domsync
domsyncdomsync is a library for building responsive web UIs in Python. A DOM document containing the whole UI is built and updated on the Python server side,
changes to this DOM are synchronised efficiently to the Browser. Events that happen on the Browser-side trigger callbacks on the Python-side.
This allows you to keep what the user sees in your Python process, close to your existing Python logic, eliminating the need for
creating and maintaining a separate Javascript client application and building an API interface to communicate with the client.The syntax of domsync closely follows the core Javascript syntax for manipulating a DOM document:
we gotgetElementById,createElement,appendChild,setAttribute,addEventListener, and so on. Every change to the Python domsync document
generates Javascript code which is almost equivalent to the Python domsync call, this allows users to clearly understand and control what
is happening to the DOM document on the Browser-side.InstallationInstall domsync with:pip install domsyncBasic exampleThis Python domsync app shows the current time:importasynciofromdatetimeimportdatetimefromdomsync.domsync_serverimportDomsyncServerasyncdefconnection_handler(server,client):"""connection_handler is called when a client connects to the server:param server: is the DomsyncServer instance:param client: is a websocket client connection instance"""# get the client's domsync Documentdocument=server.get_document(client)# add a div to the root elementroot_element=document.getElementById(document.getRootId())div_element=document.createElement('div')root_element.appendChild(div_element)whileTrue:# update the text of the div to the current timediv_element.innerText='The current time is: '+datetime.utcnow().isoformat()# send updates to the clientawaitserver.flush(client)# wait a bitawaitasyncio.sleep(0.1)asyncdefmain():# start a domsync server on localhost port 8888awaitDomsyncServer(connection_handler,'localhost',8888).serve()if__name__=="__main__":asyncio.get_event_loop().run_until_complete(main())asyncio.get_event_loop().run_forever()Let's take a look at what happens here.await DomsyncServer(connection_handler, 'localhost', 8888).serve()starts a domsync server which is essentially a websocket server with a domsyncDocumentinstance for each connected client.async def connection_handler(server, client)is the handler that runs when a new client connects to the server. The arguments of this function are theDomsyncServerinstance and the websocket client connection instance.doc = server.get_document(client)gets the domsyncDocumentassociated with the client which contains the DOM. Each client has it's separateDocumentthat can be manipulated separately.root_element = document.getElementById(document.getRootId())gets the root element of theDocumentwhich corresponds to the<div id='domsync_root_id'></div>element in the client-side HTML.div_element = document.createElement('div')creates a newdivelement in the document.root_element.appendChild(div_element)appends thedivelement under the root element as a child.div_element.innerText = 'The current time is: ' + datetime.utcnow().isoformat()updates the text of the div element to the current time.These operations modify the domsyncDocumentin memory but also generate Javascript code which is saved in an internal buffer of theDocument. At this point the content of the buffer is this generated Javascript code:var__domsync__=[];__domsync__["domsync_root_id"]=document.getElementById("domsync_root_id");__domsync__["__domsync_el_0"]=document.createElement("div");__domsync__["__domsync_el_0"].setAttribute("id","__domsync_el_0");__domsync__["domsync_root_id"].appendChild(__domsync__["__domsync_el_0"]);__domsync__["__domsync_el_0"].innerText=`The current time is: 2022-06-08T03:23:14.818841`;await server.flush(client)sends the contents of the Javascript buffer to the client where it gets evaluated and as a result the current time appears on the screen.As thewhileloop progresses, theDocumentis modified and the generated Javascript code is sent to the client continuously. However, domsync is efficient in the sense that it only sends changes for those elements that have actually changed, in this example this is the only line of generated Javascript that is sent by the nextawait server.flush(client):__domsync__["__domsync_el_0"].innerText=`The current time is: 2022-06-08T03:23:14.925521`;This is the generic Browser-side domsync client:<html><!-- domsync will render into this element --><body><divid='domsync_root_id'></div></body><scripttype="text/javascript">// server -> client: DOM changes are coming from websocket as javascript code and are eval'ed heresocket=newWebSocket("ws://localhost:8888");socket.onmessage=function(event){(function(){eval.apply(this,arguments);}(event.data));};// client -> server: ws_send is called by event handlers to send event messages to the serverfunctionws_send(msg){socket.send(JSON.stringify(msg));};</script></html>The client connects to the domsync server running on localhost port 8888 over websocket.
The domsync server sends javascript code containing DOM operations that are evaluated insocket.onmessage.
Thews_sendfunction is used as an event callback to send events back to the server.This example is inexamples/example_clock.pywith the client-side html inexamples/client.html.Read the docs:https://domsync.readthedocs.io/