HTML form data not received by the Tornado class

I use WebSockets in the Tornado Framework and cannot get html data to send to the tornado class.

This is my code:

class MainHandler(tornado.web.RequestHandler): event = [] def get(self): self.render('main.html') def post(self): MainHandler.event = self.get_argument('event') 

When I try to send an event to the WebSocketHandler class. data not received from form:

 class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print "tailing..." db = Connection().blah coll = db.blah_tail event = MainHandler.event print 'Filtered', event 

'Filtered' just prints an empty list: "Filtered []".

Html form:

 <form action="/" method="post"> <input type="text" name="event" /> <input type="submit" id="open" value="Submit Query" /> </form> 

How can you submit form data to the WSHandler class?

thanks

js to create websocket:

 <script> $(document).ready(function() { var ws; $("#open").click(function(evt){ evt.preventDefault(); ws = new WebSocket("ws://" + "localhost" + ":" + "8888" + "/ws"); ws.onmessage = function(evt) $("#display").append(evt.data + "<br />"); ws.onclose = function(evt) {alert("Server connection terminated");}; }); }); </script> 
+4
source share
2 answers

As in the example from the Tornado documentation, I will use set for WebSocket clients. Improving this is left as an exercise for the reader.

 # clients listing on the WebSocket clients = set() class MainHandler(tornado.web.RequestHandler): def get(self): return self.render("index.html") def post(self): global clients event = self.get_argument("event") print "got event", event if not clients: print "No WebSockets, no point in querying the database" return for coordinate in self.get_coordinates(event): for client in clients: print "sending coordinate", coordinate, "to client", client client.write_message(json.dumps(coordinate, default=json_util.default)) def get_coordinates(self, event): # replace with a real database query for coordinate in ("No", "man's", "land"): time.sleep(1) yield coordinate class WSHandler(tornado.websocket.WebSocketHandler): def open(self): global clients print "WebSocket opened..." clients.add(self) def on_close(self): global clients print "WebSocket closed..." clients.remove(self) 

The corresponding part of the index.html template is:

  <script type="text/javascript"> $(document).ready(function() { var ws; // open WebSocket for getting the results ws = new WebSocket("ws://" + location.host + "/ws"); ws.onmessage = function(evt) { $("#display").append(evt.data + "<br>"); }; ws.onclose = function(evt) {alert("Server connection terminated");}; $("#open").click(function(evt) { evt.preventDefault(); $.post("/", $("#eventForm").serialize()); }); }); </script> </head> <body> <h1>Event follower</h1> <h2>Enter the event you would like to follow</h2> <form id="eventForm" action="/" method="post"> <input type="text" name="event" /> <input type="submit" id="open" value="Submit Query" /> </form> <h2>Coordinates</h2> <div id="display"> </div> </body> 

When the page loads, the WebSocket connection with the WSHandler class is connected to the WSHandler , and the client is added to the clients set. When the page is closed, the WebSocket connection is closed, and the server removes it from the set.

When the submit button is clicked open , the form will be submitted asynchronously using AJAX until MainHandler.post . The method will determine the coordinates associated with this event and send them to client listeners as they become available. The browser receives each coordinate and adds it to the screen. div

+3
source

What is the handler of your MainHandler or WSHandler function,

Only one of them is called at a time, so your syntax event = MainHandler.event will not give you the result.

  • If your goal is only to submit the form. Then, when sending an event type, you need to write a message or get a function related to your send call in your JS. This will work with the normal server-side tornado.web.RequestHandler.

Ref. tornado chat example

I updated the chat example:

 $(document).ready(function() { if (!window.console) window.console = {}; if (!window.console.log) window.console.log = function() {}; $("#messageform").live("submit", function() { newMessage($(this)); return false; }); $("#message").select(); } }); function newMessage(form) { var message = form.formToDict(); var disabled = form.find("input[type=submit]"); disabled.disable(); $.postJSON("URL", message, function(response) { console.log(response); }); } function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } jQuery.postJSON = function(url, args, callback) { args._xsrf = getCookie("_xsrf"); $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST", success: function(response) { if (callback) callback(eval("(" + response + ")")); }, error: function(response) { console.log("ERROR:", response) }}); }; 

When you call $("#message").submit() , you will receive the form data in your URL function

If you want to use WSHandler then

Ref. example will help you.

See if that helps.

0
source

Source: https://habr.com/ru/post/1445231/


All Articles