Search code examples
flaskflask-socketio

How to serve html code when socketio event happens?


I am trying to serve HTML code if any SocketIO event occurs , so instead of doing :

$(document).ready(function(){

    var notification_back = '/notifications';
    var callback = 'http://' + document.domain + ':' + location.port + notification_back;
    var socket = io.connect(callback);

    socket.on('new_test_event', function(data){
    var testList = $('#new_test_list');
    testList.prepend(
        '\
            <li>\
                <a href="'+data.url_to+'">\
                    <div class="user-new">\
                        <p>'+data.title+'</p>\
                        <span>'+moment(data.timestamp).fromNow()+'</span>\
                    </div>\
                    <div class="user-new-left">\
                        <i class="fa fa-rss"></i>\
                    </div>\
                    <div class="clearfix"> </div>\
                </a>\
            </li>\
        '
    )
    console.log(data);
});

i would prefer to serve that html code from the back-end, so something like this:

@socketio.on('new_test_event', namespace='/notifications')
def raise_new_attack(data):
    return Markup("THE HTML CODE GOES HERE")

Is there any way to make that work ? or its not possible ?!


Solution

  • That's not how SocketIO works, you seem to be trying to adapt SocketIO to how HTTP does things, so maybe you should consider if SocketIO is what you want.

    There is nothing wrong with returning HTML from a SocketIO event, but you will need to add some JavaScript on the client that receives the HTML and inserts it in the correct place in the page.

    The following is an example of an event returning HTML:

    @socketio.on('new_test_event', namespace='/notifications')
    def raise_new_attack(data):
        emit("my_notification", "THE HTML CODE GOES HERE")
    

    Then in the client you would have something like this:

    socket.on("my_notification", function(html_code) {
        // use jQuery or similar to insert the html in the page
    });