Ask Your Question
1

How can the reception of websocket messages be achieved with the Textual Python TUI module?

asked 2021-12-07 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-11-28 17:00:00 +0000

djk gravatar image

To receive websocket messages using the Textual Python TUI module, you can create a subclass of the textual.widgets.ScrollView class and override the will_draw method to listen for and process the messages.

Here is an example implementation:

import json
import websocket
import threading
import textual
from textual.app import App
from textual.widget import ScrollView

class MyScrollView(ScrollView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.websocket_thread = threading.Thread(target=self.connect_websocket)
        self.websocket_thread.start()

    def connect_websocket(self):
        ws = websocket.WebSocketApp("ws://localhost:8000/ws/")
        ws.on_message = self.on_message
        ws.run_forever()

    def on_message(self, message):
        data = json.loads(message)
        # handle the incoming message here
        self.buffer.puts(data['text'])

    async def will_draw(self):
        await super().will_draw()
        # redraw the buffer to display any new messages
        self.buffer.force_display()


class MyApp(App):
    async def on_load(self, event):
        self.set_root_widget(MyScrollView())

MyApp.run(log_level="INFO")

In this example, we create a MyScrollView subclass of ScrollView and override the will_draw method to redraw the buffer whenever new messages arrive. We also add a connect_websocket method that creates a WebSocketApp instance and sets its on_message handler to call the on_message method, which processes each incoming message and adds it to the buffer.

To start the websocket connection, we create a websocket_thread and call connect_websocket in its run method. Finally, we set the root widget of the MyApp instance to an instance of MyScrollView.

Of course, this is just an example, and you will need to modify the code to fit your specific use case.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-07 11:00:00 +0000

Seen: 8 times

Last updated: Nov 28 '21