miguelgrinberg / flask-sock

Modern WebSocket support for Flask.
MIT License
272 stars 24 forks source link

How to receive a JSON string? #54

Closed gkizhepat closed 1 year ago

gkizhepat commented 1 year ago

Miguel, In your echo example, if the data from the client side(javascript) is a JSON string, how do I get it and decode it on the Python side?
Javascript side

var dict = { Name: "Eric", Age = 23 Job: "Freelancer", Skills : "JavaScript" }; socket.send(JSON.stringify(dict))

Python side

data = sock.receive() decodedData = json.loads(data) --- This doesn't work. Any suggestion is much appreciated.

miguelgrinberg commented 1 year ago

"This doesn't work" does not really give me any clues. Please provide all the details that you have regarding this failure.

gkizhepat commented 1 year ago

Miguel, Here is the Python code

-----------------------------------------------
from flask import Flask, render_template
from flask_sock import Sock
import json
###################################
application = Flask(__name__)
sock = Sock(application)
#################################

@sock.route('/echo')
def echo(sock):
  try:
    while True:
        print("here1")
        data = sock.receive()
        print("here2")
        dataJ= json.loads(data)
        print(here3)
  except:
    print("connection closed")
#######
if __name__ == "__main__":
        #main()
        application.run(host='0.0.0.0')

Output is below

here1
here2
connection closed

I guess, while trying to execute this: dataJ= json.loads(data) , gives an exception All I want is to get the JSON values sent from the javascript side. I am perhaps not approaching it the right way. Please let me know how to accomplish this.

Here is the code on the client side

<html>
  <head>
    <title>Flask-Sock Demo</title>
  </head>
  <body>
    <h1>Flask-Sock Demo</h1>
    <div id="log"></div>
    <br>
    <form id="form">
      <label for="text">Input: </label>
      <input type="text" id="text" autofocus>
    </form>
    <script>
        const textField = document.getElementById('text');
      var dict = {
                Name: "Eric",
                Age = 23
                Job: "Freelancer",
                Skills : "JavaScript",
                TextVal: textField.value
                };
      const log = (text, color) => {
        document.getElementById('log').innerHTML += `<span style="color: ${color}">${text}</span><br>`;
      };

      const socket = new WebSocket('wss://prod4.companyxx.com/myproject/echo');
      socket.addEventListener('message', ev => {
        log('<<< ' + ev.data, 'blue');
      });
      document.getElementById('form').onsubmit = ev => {
        ev.preventDefault();
        log('>>> ' + textField.value, 'red');
        //socket.send(textField.value);
        socket.send(JSON.stringify(dict));
        textField.value = '';
      };
    </script>
  </body>
</html>
miguelgrinberg commented 1 year ago

You are silencing the exception that you are getting on the Python side. That is a bad practice, for that reason you do not know what's failing in your application. Can you let the exception bubble up so that the error is exposed please?

gkizhepat commented 1 year ago

Here is what I expanded the exception to except BaseException as error: print('An exception occurred: {}'.format(error))

Output: An exception occurred: Expecting value: line 1 column 1 (char 0)

Not a valid JSON string? If it is, could you tell me what is wrong with my JSON on the javascript side. Thanks a bunch.

miguelgrinberg commented 1 year ago

Not a valid JSON string?

Did you look at it? I have no way to know what the value of this string is.

gkizhepat commented 1 year ago

I figured it out. There was an error in the JSON input. Thanks a bunch for forcing me to expand the error. Much appreciated.