To implement a web socket feature with Flask-Restf

2019-09-20 17:42发布

问题:

WORK DONE: I have implemented a REST API with Mongo DB (PyMongo driver) using Flask-Restful having one endpoint named “Users” consisting of GET, POST, PUT, DELETE
My PUT method:
def put(self, short_name ): coll = db.users user_info = request.get_json() print user_info #for debugging coll.update({'short_name': short_name'}, {"$set": user _info}) return Response(json_util.dumps(user _info), mimetype='application/json')

The above PUT method accepts a short_name, updates the User database and returns a response.

Work to be done: I need to implement a server side web socket feature where after coll.update({'short_name': short_name'}, {"$set": user _info}) is executed, a message to the client (i.e frontend which is built completely on angular) has to be sent stating “Data updated successfully”.

I saw a couple of snippets online but couldn’t find one with REST Api. For now I only require the server side implementation. I will try to figure out the client side implementation later. Any help on how to accomplish this is appreciated. Can it be done with simple python or is socket.io needed. All solutions are welcome.

EDIT: My modified server code

def put(self, short_name ):
    coll = db.users
    user_info = request.get_json()
    print user_info             #for debugging
    coll.update({'short_name': short_name'}, {"$set": user _info})
    emit('my response', {'data': 'update successful'})
    return Response(json_util.dumps(user _info), mimetype='application/json')  

Added this on the client side:
namespace = '/';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);

socket.on('my response', function(msg) {
            console.log(msg.data)
        });

Now when I run my application, the console on the client side does not print my data sent from the server. Can anyone explain where am I going wrong.

回答1:

This should be interesting... Flask or Django or similar frameworks are built to serve HTTP request based method.

Imagine

  1. user click the button
  2. Your framework take the request
  3. do the needs
  4. and finally return the response

This is the actual flow of web server. but in your case you may want to update the frontend when DB updated or Any event changes.. In this case you need Socket to communicate with frontend.

Features of web sockets

  • Communicate with your website whenever you need.

Just put the javascript in the html page like this

$(document).ready(function(){
    var socket = io.connect('http://localhost:8000/test');
});

And now you are connected with Website so next in your python code..

@socketio.on('my event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']})

just like this import emit and put your message and you are good to go. For more detail please look here http://flask-socketio.readthedocs.org/en/latest/