Monday, 2 November 2020

Calling a flask_socketio function in an onload function

I am trying to load/initialize my whitelist textfield from the server using flask socket-io. To do this I want to obtain the data from the server whenever the textfield loads. I have written this javascript code:

    //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;
        })
    };

The onload call works and is defined here:

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

There is no error within the listener (as it is never called) but here it is:

#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()

I must have made a mistake in the javascript, but for the life of me I can't find the solution. Any help appreciated.

Update Some have requested full documents so I have provided them.

IndexA

<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 .</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 Script

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)

Doing further testing I have determined that I must not be calling this socket @socketio.on('init_whitelist') however I am not sure how to call it, as I don't have any text to send to the system in order to trigger it. Further putting in a request did not run the function.



from Calling a flask_socketio function in an onload function

No comments:

Post a Comment