简体   繁体   中英

How to access formData in flask sent using websockets?Flask-SocketIO

How to access form data sent to Flask using web sockets? I receive invalid frame header in google chrome developer tools->console.

Extract from my javascript code:

var form_data = new FormData($('#my_form')[0]);

socket.emit('handle_form',{data:form_data});

How would I access, say 'title' field in my_form from flask ?

request.form throws the same error "Invalid frame header"

One more question, is it good to use web sockets for form submission and as an entire replacement for ajax ?

Instead of sending a FormData object, which is a client-side only construct, you should build a plain dictionary and send that, as all the data that is transferred back and forth in Socket.IO is serialized to JSON.

Then on the server, you will have a dict that is sent as an argument to your socket callback function. See this example for ideas on how to send form data to the server.

It is not like Flask-SocketIO works.

When you socket.emit something, you handle it with a callback.

@socketio.on('handle_form')
def handle_form_callback(data):
    print('received message: ' + data)

You don't have a request.form in this case.

It works as a form submission replacement, but I don't think it is a good replacement. Websockets are not stateless, they are difficulty to scale and are essentially bound to a server. Of course it has some workarounds, but it is not like the very well documented HTTP server scaling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM