【问题标题】:Calling a flask_socketio function in an onload function在 onload 函数中调用 flask_socketio 函数
【发布时间】:2020-10-28 13:45:38
【问题描述】:

我正在尝试使用烧瓶 socket-io 从服务器加载/初始化我的白名单文本字段。为此,我想在文本字段加载时从服务器获取数据。我已经写了这段 javascript 代码:

    //Initialisation
    function initWhitelist(){
        socket = io.connect('http://' + document.domain + ':' + location.port);
        socket.on('init_whitelist_received',function(data){
        var text = data['text'];
        alert("hello");
        document.getElementById("whitelist").innerHTML = text;
        })
    };

onload 调用有效并在此处定义:

    <textarea id="whitelist" name="whitelist" onload="initWhitelist()" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"> </textarea>

侦听器中没有错误(因为它从未被调用),但它是:

#Initially Read Whitelist
@socketio.on('init_whitelist')
def init_whitelist():
    #Receive updated whitelist from the front end HTML
    whitelist = open(r"whitelist.txt","r")
    # Output contents of whitelist
    emit('update_whitelist_received', {'text': whitelist.read()})
    whitelist.close()

我一定是在 javascript 中犯了一个错误,但对于我来说,我找不到解决方案。任何帮助表示赞赏。

更新 有些人要求提供完整的文件,所以我提供了。

索引A

<html>
    <head>
        <!-- Some basic meta info -->
        <title>Dashboard</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-   scale=1">
        <!-- A stylesheet to make things automatically look nice -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css">
    <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/1.3.6/socket.io.min.js"></script>
    <!-- Script to handle socket.io -->
    <script>
        // The http vs. https is important. Use http for localhost!
        socket = io.connect('http://' + document.domain + ':' + location.port);
        //Initialisation
        function initWhitelist(){
            socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('init_whitelist_received',function(data){
            var text = data['text'];
            alert("hello");
            document.getElementById("whitelist").innerHTML = text;
            })
        };
        var socket;
        $(document).ready(function() {
            // Button was clicked
            document.getElementById("send_button").onclick = function() {
            // Get the text value
            var text = document.getElementById("textfield_input").value;
            // Update the chat window
            document.getElementById("chat").innerHTML += "You: " + text + "\n\n";

            // Emit a message to the 'send_message' socket
            socket.emit('send_message', {'text':text});
            // Set the textfield input to empty
            document.getElementById("textfield_input").value = "";
            };

            // Message received from server (Goes into LOG textfield)
            socket.on('message_from_server', function(data) {
            var text = data['text'];
            document.getElementById("chat").innerHTML += "Server: " + text +   "\n\n";
            });

            //Update Whitelist Button Clicked
            // Button was clicked
            document.getElementById("update_whitelist_button").onclick = function() {
            // Get the text value
            var upd_white_list = document.getElementById("whitelist").value;
            // Update the chat window
            document.getElementById("chat").innerHTML += "You modified the Whitelist" + "\n";
            //Send updated Whitelist to server
            socket.emit('updated_whitelist',{'text':upd_white_list})
            };


            // Message received from server (Goes into LOG textfield)
            socket.on('update_whitelist_received', function(data) {
            var upd_white_list = data['text'];
            document.getElementById("whitelist").innerHTML = upd_white_list;

            });
             document.getElementById("test_button").onclick = initWhitelist();
        });
    </script>
    </head>
    <body>
    <div style="margin: 25px; display: flex; flex-direction: column;">
        <h1 class="title">Hello {{username}}.</h1>
        <p>Welcome to the dashboard.</p>
        <textarea id="chat" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"></textarea>
        <div style="display: flex; flex-direction: row;">
            <input type="text" id="textfield_input" style="height: 30px; width: 400px; margin-top: 5px; margin-right: 10px;" class="textfield">
            <button id="send_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Send</button>
            <button id="test_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Test</button>
        </div>


        <p>Whitelist</p>
        <div>
            <textarea id="whitelist" name="whitelist" onload="initWhitelist()" style="width: 500px; height: 250px; font-size: 18px; font-family: monospace; margin-top: 10px;"> </textarea>
            <button id="update_whitelist_button" class="button is-primary" style="margin-top: 5px; width: 90px; height: 30px;">Update!</button>
        </div>
    </div>
</body>
</html>

Python 脚本

from flask import *
from flask_socketio import *

# Init the server
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some super secret key!'
socketio = SocketIO(app, logger=True)


# Send HTML!
@app.route('/')
def root():
    return "Hello World!"


@app.route('/html/<username>')
# Display the HTML Page & pass in a username parameter
@app.route('/html/<username>')
def html(username):
    return render_template('indexA.html', username=username)

# Receive a message from the front end HTML
@socketio.on('send_message')
def message_received(data):
    print(data['text'])
    emit('message_from_server', {'text':'Message recieved!'})

#Initially Read Whitelist
@socketio.on('init_whitelist')
def init_whitelist():
    #Receive updated whitelist from the front end HTML
    emit('init_whitelist_received', {'text': 'debug'})
    whitelist = open(r"whitelist.txt","r")
    # Output contents of whitelist
    emit('init_whitelist_received', {'text': str(whitelist.read())})
    whitelist.close()

@socketio.on('updated_whitelist')
def message_update_whitelist_received(data):
    print(data['text'])
    whitelist = open(r"whitelist.txt","w")
    #Update write list
    whitelist.write(data['text'])
    whitelist.close()
    #Output to Log
    emit('message_from_server', {'text':'Changes to Whitelist Saved!'})
    #Output contents of whitelist
    emit('update_whitelist_received', {'text': data['text']})
    
# Actually Start the App
if __name__ == '__main__':
    """ Run the app. """
    socketio.run(app, port=8000, debug=True)

做进一步的测试我已经确定我不能调用这个套接字 @socketio.on('init_whitelist') 但是我不知道如何调用它,因为我没有任何文本可以发送到系统为了触发它。进一步提出请求并没有运行该函数。

【问题讨论】:

    标签: javascript python flask socket.io


    【解决方案1】:

    您正在侦听init_whitelist_received 事件,但也需要发出 in 以便侦听器回调运行。

    在注册回调后或在 window.onload 事件处理程序中发出 init_whitelist 事件,它应该可以按预期工作:

    //Initialisation
    function initWhitelist(){
      socket = io.connect('http://' + document.domain + ':' + location.port);
      socket.on('init_whitelist_received',function(data){
        var text = data['text'];
        alert("hello");
        document.getElementById("whitelist").innerHTML = text;
      });
      
      // emit init_whitelist
      socket.emit('init_whitelist');
    };
    

    【讨论】:

    • 所以只用 emit() 调用函数是标准的。我想我以为你必须向服务器发送消息。
    • @LyraOrwell 这取决于您的活动。如果您的事件需要有效负载而不是您需要传递它,但如果不是,您可以在没有任何有效负载的情况下发出事件。
    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 2014-03-17
    • 2018-02-09
    • 2012-11-19
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多