[Python] How do I display UTF-8 characters sent through a websocket?

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to build a simple web socket server that loads a file with some tweets in it (as CSV) and then just sends the string of the tweet to a web browser through a websocket. Here is a gist with the sample that I'm using for testing. Here's the Autobahn server component (server.py):

    import random
    import time
    from twisted.internet import reactor
    from autobahn.websocket import WebSocketServerFactory, \
    WebSocketServerProtocol, \
    listenWS


    f = open("C:/mypath/parsed_tweets_sample.csv")

    class TweetStreamProtocol(WebSocketServerProtocol):

    def sendTweet(self):
    tweet = f.readline().split(",")[2]
    self.sendMessage(tweet, binary=False)

    def onMessage(self, msg, binary):
    self.sendTweet()

    if __name__ == '__main__':

    factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
    factory.protocol = TweetStreamProtocol
    listenWS(factory)
    reactor.run()


    And here is the web component (index.html):

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:9000");

    ws.onmessage = function(e) {
    document.getElementById('msg').textContent = e.data; //unescape(encodeURIComponent(e.data));
    console.log("Got echo: " + e.data);
    }
    </script>
    </head>
    <body>
    <h3>Twitter Stream Visualization</h3>
    <div id="msg"></div>
    <button onclick='ws.send("tweetme");'>
    Get Tweet
    </button>
    </body>
    </html>


    When the tweet arrives in the browser, the UTF-8 characters aren't properly displayed. How can I modify these simple scripts to display the proper UTF-8 characters in the browser?

    Continue reading...

Compartilhe esta Página