在python中使用websockets从表单中获取多个变量

时间:2014-09-28 16:41:05

标签: javascript python websocket flask socket.io

刚开始学习websockets和python。现在我正在使用Socket-IO,并从表单中获取非常基本的信息并将其回显出去#39;但我需要能够从表单中提取2+个变量并在程序中使用它们。我为初学者看到的指南都只是一个变量,我正在努力解决它并可以使用一些帮助。

我在表单中寻找第二个文本字段,并能够在应用程序中获取变量。我假设它的格式为{'数据':消息['数据']}和{'数据':消息[&# 39; data2']}但是只要我能得到这些值,那就重要了。

我现在拥有的:

的index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
            namespace = '/test'; // change to an empty string to use the global namespace

            var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
            socket.on('connect', function() {
                socket.emit('my event', {data: 'Connected... Waiting for you...'});
            });


            socket.on('my response', function(msg) {
                $('#log').append('<br>' + msg.data);
            });


            $('form#emit').submit(function(event) {
                socket.emit('my event', {data: $('#emit_data').val()});
                return false;
            });

        });
    </script>
</head>
<body>
    <h1>Flask-SocketIO Test</h1>
    <h2>Send:</h2>
    <form id="emit" method='POST' action='#'>
        <input type="text" name="emit_data" id="emit_data" placeholder="Message"><br>
        <input type="submit" value="Echo"></div>
    </form>
    <h2>Receive:</h2>
    <div id="log"></div>
</body>
</html>

app.py

from gevent import monkey
monkey.patch_all()

import time
from threading import Thread
from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        time.sleep(60)
        count += 1
        #'<br>Received #' + msg.count + ': ' + msg.data
        socketio.emit('my response', {'data': 'Connection to server still alive'}, namespace='/test')

@app.route('/')
def index():
    #kick off thread that every 10 seconds sends a response
    global thread
    if thread is None:
        thread = Thread(target=background_thread)
        thread.start()
    return render_template('index.html')

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

@socketio.on('connect', namespace='/test')
def test_connect():
    emit('my response', {'data': 'Trying to connect to server...'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

我在表单中寻找第二个文本字段,并能够在应用程序中获取变量。我假设它的格式为{&#39;数据&#39;:消息[&#39;数据&#39;]}和{&#39;数据&#39;:消息[&# 39; data2&#39;]}但是只要我能得到这些值,那就重要了。

1 个答案:

答案 0 :(得分:1)

只需发送任意数量的变量:

socket.emit('my event', {data: $('#emit_data').val(), data2: $('#emit_data2').val()});

data只是变量的示例名称。您可以使用任何数量和名称的字典键。