使用Flask-Restful(REST Api)在服务器端实现Web套接字功能 [英] To implement a web socket feature with Flask-Restful (REST Api) on the server side

查看:485
本文介绍了使用Flask-Restful(REST Api)在服务器端实现Web套接字功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:我已经用Mongo DB(PyMongo驱动程序)使用Flask-Restful实现了一个REST API,其中一个名为Users的端点由GET,POST,PUT,DELETE和
我的PUT方法:

def put(self,short_name):
coll = db.users
user_info = request.get_json()
打印user_info#用于调试
coll.update({'short_name':short_name'},{$ set:user _info})
返回响应(json_util.dumps(user _info),mimetype ='application / json')



上面的PUT方法接受一个short_name,更新User数据库并返回一个响应。


$ b 要完成的工作:我需要实现一个服务器端Web套接字功能之后 coll.update({ 'short_name':short_name'},{$ set:user _info})被执行时,必须发送一个消息给客户端(即完全建立在角上的前端)更新成功。



我在网上看到了一些片段,但是找不到一个带有REST Api的片段。现在我只需要服务器端的实现。稍后我会试图弄清楚客户端的实现。
如何做到这一点的任何帮助表示赞赏。可以用简单的python来完成,或者需要socket.io。所有的解决方案都欢迎。
$ b

编辑:我修改的服务器代码

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

方:

namespace ='/';

var socket = io.connect('http://'document.domain +':'+ location.port + namespace);

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

现在,当我运行我的应用程序时,客户端的控制台不会打印从服务器。任何人都可以解释我在哪里出错。
解决方案

这应该是有趣的... Flask或Django或类似的框架是建立基于HTTP请求的方法。用户点击按钮


/ li>

  • 您的框架接受请求

  • 完成需求

  • 并最终返回响应

  • 这是Web服务器的实际流程。但在你的情况下,你可能想要更新数据库更新或任何事件更改前端。在这种情况下,你需要与前端沟通的Socket。的网络套接字





    只要将javascript放在html页面就可以了

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

    现在你已经连接到了网站,所以接下来在你的python代码中。

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

    这个进口发出并把你的消息,你很好去。欲了解更多详情,请看这里 http://flask-socketio.readthedocs.org/en/latest/


    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.

    解决方案

    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/

    这篇关于使用Flask-Restful(REST Api)在服务器端实现Web套接字功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆