Home > Net >  How can I send a request to flask socket.io with the click of a button?
How can I send a request to flask socket.io with the click of a button?

Time:01-01

The following source code sends a request to the server upon page load, and when the task is done, the page is updated automatically.

app.py

from flask import Flask, render_template
from flask_socketio import SocketIO, emit, disconnect

from time import sleep

async_mode = None

app = Flask(__name__)

socket_ = SocketIO(app, async_mode=async_mode)

@app.route('/')
def index():
    return render_template('index.html',
                           sync_mode=socket_.async_mode)

@socket_.on('do_task', namespace='/test')
def run_lengthy_task(data):
    try:
        duration = int(data['duration'])
        sleep(duration)
        emit('task_done', {'data': 'long task of {} seconds complete'.format(duration)})
        disconnect()
    except Exception as ex:
        print(ex)

if __name__ == '__main__':
    socket_.run(app, host='0.0.0.0', port=80, debug=True)

index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Long task</title>
    <script src="https://code.jquery.com/jquery-3.6.3.js"></script>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {

            namespace = '/test';
            var socket = io(namespace);

            socket.on('connect', function() {
                $('#messages').append('<br/>'   $('<div/>').text('Requesting task to run').html());
                socket.emit('do_task', {duration: '60'});
            });

            socket.on('task_done', function(msg, cb) {
                $('#messages').append('<br/>'   $('<div/>').text(msg.data).html());
                if (cb)
                    cb();
            });
        });
    </script>
</head>
<body>
    <h3>Messages</h3>
    <div id="messages" ></div>
</body>
</html>

How can this program be modified, so that the request is sent only up on the click of a button?

CodePudding user response:

Here's an edit to move the event from the document load to the button being clicked.

<!DOCTYPE HTML>
<html>
<head>
    <title>Long task</title>
    <script src="https://code.jquery.com/jquery-3.6.3.js"></script>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <script type="text/javascript" charset="utf-8">
         $(document).on('click', '.widget input', function (event) {
            namespace = '/test';
            var socket = io(namespace);

            socket.on('connect', function() {
                $('#messages').append('<br/>'   $('<div/>').text('Requesting task to run').html());
                socket.emit('do_task', {duration: '60'});
            });

            socket.on('task_done', function(msg, cb) {
                $('#messages').append('<br/>'   $('<div/>').text(msg.data).html());
                if (cb)
                    cb();
            });
            event.preventDefault();
        });
    </script>
</head>
<body>
    <div >
        <input type="submit" value="Click me" />
    </div>
    <h3>Messages</h3>
    <div id="messages" ></div>
</body>
</html>
  • Related