繁体   English   中英

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

[英]get multiple variables from form with websockets in python

刚开始学习websockets和python。 目前,我正在使用Socket-IO,并且具有非常基本的“从表单中拉出并回显它”的功能,但是我需要能够从表单中提取2个以上变量并在程序中使用它们。 我为初学者所见的指南只是一个变量,我正在努力弄清楚它,并可能会使用一些帮助。

我正在表单中寻找第二个文本字段,并能够在应用程序中获取变量。 我假设它的形式为{'data':message ['data']}和{'data':message ['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)

我正在表单中寻找第二个文本字段,并能够在应用程序中获取变量。 我假设它的形式为{'data':message ['data']}和{'data':message ['data2']},但是只要我能得到值,那就是什么重要。

只要发送任意数量的变量即可:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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