使用Flask SocketIO注册服务器事件 [英] Registering server events with flask SocketIO

查看:75
本文介绍了使用Flask SocketIO注册服务器事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://github.com/miguelgrinberg/Flask-开始使用flask和SocketIOSocketIO .

我想将字符串发布到Flask服务器,然后通过SocketIO将其发送到客户端网页.

I want to post a string to the flask server and then via SocketIO, emit this to the client webpage.

通常我的发布代码如下:

Normally my posting code would look like:

@app.route('/index',methods=['POST'])
def index():
    token = request.form['token']

据我了解,需要以下内容将数据从服务器发送到客户端页面:

As far as I understand, something like the following is needed to emit data from the server to client page:

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

我不清楚如何将这两个功能结合在一起,以便在发布后将令牌的值发送给客户端.

It's not clear to me how to tie the 2 functions together so that on a post the value of token would be emitted to the client.

我在文档中找到的最接近的是:

The closest I can find in the docs is:

Receiving Messages¶
When using SocketIO messages are received by both parties as events. On the client side Javascript callbacks are used. With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions.

我该如何工作?

推荐答案

您的假设是正确的.首先,将数据发布到Flask:

You're right with your assumptions. First, POST the data to Flask:

.ajax({
    url: "{{ url_for('index') }}",
    method: "POST",
    data: {
        token: "value"
    }
});

您的视图看起来

@app.route('/index',methods=['POST'])
def index():
    token = request.form['token']
    test_message(dict(data=token))
    return '1'

并且您的 JavaScript 看起来会有些变化喜欢

And your JavaScript would look something like

var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
    socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('my response', function(msg) {
    // do something with msg.data
});

这篇关于使用Flask SocketIO注册服务器事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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