Flask-SocketIO如何在事件处理程序中桥接用户与生成进程的通信

时间:2018-05-26 09:26:41

标签: python-3.x flask flask-socketio

我的目标是在用户单击网页上的按钮后,使用另一个python脚本(需要一些shell交互来输入auth代码)来生成进程。

register.py脚本有两个可能的shell结果,如果用户未经过身份验证,则要求输入auth代码,或者只是结束时没有返回消息,表明用户已经过身份验证。

到目前为止,我能够触发这个register.py文件,并且如果脚本要求使用auth代码并通过socketio发出返回状态并将其显示给用户,但是我不知道,我该怎么接受来自网页上用户输入的验证码,如果用户未经过验证,又将其加载到寄存器功能中?

代码:

Flask app文件 - 代码有点调整Flask-SocketIO示例

from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect

import pexpect


async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()


def register(username, phone):
    child = pexpect.spawn('python3 register.py -u ' + username + ' -p ' + phone )
    i = child.expect(['Please enter the code .*', pexpect.EOF])
    socketio.emit('my_response', {'data': 'pexpect result ' + str(i) + ' ' + child.after.decode(), 'count': 55555}, namespace='/test')


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on("authenticate", namespace="/test")
def authenticate(message):
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=lambda: register("radicz", "+999999000999"))

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

HTML文件

    <!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            // Use a "/test" namespace.
            // An application can open a connection on multiple namespaces, and
            // Socket.IO will multiplex all those connections on a single
            // physical channel. If you don't care about multiple channels, you
            // can set the namespace to an empty string.
            namespace = '/test';

            // Connect to the Socket.IO server.
            // The connection URL has the following format:
            //     http[s]://<domain>:<port>[/<namespace>]
            var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);


            // Event handler for new connections.
            // The callback function is invoked when a connection with the
            // server is established.
            socket.on('connect', function() {
                socket.emit('my_event', {data: 'I\'m connected!'});
            });

            $("#register").on("click", function(){
                socket.emit("authenticate", {data: "cislo + jmeno"})
                console.log("register fired!");
            });

            // Event handler for server sent data.
            // The callback function is invoked whenever the server emits data
            // to the client. The data is then displayed in the "Received"
            // section of the page.
            socket.on('my_response', function(msg) {
                $('#log').append('<br>' + $('<div/>').text('Received #' + msg.count + ': ' + msg.data).html());
            });


            // Handlers for the different forms in the page.
            // These accept data from the user and send it to the server in a
            // variety of ways
            $('form#emit').submit(function(event) {
                socket.emit('my_event', {data: $('#emit_data').val()});
                return false;
            });
            $('form#disconnect').submit(function(event) {
                socket.emit('disconnect_request');
                return false;
            });
        });
    </script>
</head>
<body>
    <h1>Flask-SocketIO Test</h1>
    <button id="register">register</button>
    <h2>Send:</h2>
    <form id="emit" method="POST" action='#'>
        <input type="text" name="emit_data" id="emit_data" placeholder="Message">
        <input type="submit" value="Echo">
    </form>
    <form id="disconnect" method="POST" action="#">
        <input type="submit" value="Disconnect">
    </form>
    <h2>Receive:</h2>
    <div id="log"></div>
</body>
</html>

所以问题是,如何获得用户提供的auth代码并将其加载到寄存器功能?我以为我可以使用一些让步技术,比如发出如果需要从服务器端进行身份验证,然后从客户端发出事件,再次触发后端的寄存器功能,但该功能将从上次产生时继续,但是我我不确定如何正确地做到这一点,或者它是否可行,或者我是完全关闭的,还有其他一些技术可以更容易地实现这一目标吗?

编辑:或者this是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

我没有很好地测试它,但似乎在寄存器函数中添加另一个socketio事件处理程序有助于我的目的。

def register(username, phone):
    child = pexpect.spawn('python3 register.py -u ' + username + ' -p ' + phone )
    i = child.expect(['Please enter the code .*', pexpect.EOF])
    socketio.emit('my_response', {'data': 'pexpect result ' + str(i) + ' ' + child.after.decode(), 'count': 55555}, namespace='/test')

    @socketio.on("another_event", namespace="/test")
    def another_callback(message):
        # actual code that I wanted to run