1

So, I have a local script, which should output a specific message to display to the client of an user connected in the flask app. From local script to server I've used:

import requests
requests.post(address, json=json)

And the message is received correctly to the server. Problem is that I can't manage to get it displayed through the client because doing something like:

from flask import render_template, url_for, redirect, request
@app.route('/home', methods=['GET', 'POST'])
def home(): 
    if request.method == 'POST': 
        result = request.json 
        return render_template('home.html', result=result, title='Homepage', current_user=current_user)

Doesn't effectively render any template.

I suspect that it's due to the nature of a socket connection, so probably I should set up a similar architecture using sockets events.

Problem is that I'd like to have for each user a unique message displayed on the home route and I fear that with sockets it would be impossible to do so.

Forgive me for the bad explanation of my question, I'm still a newbie regarding networks and web development with Flask.

f-starace
  • 278
  • 1
  • 17

1 Answers1

3

Resolved, it was easier than I imagined. I ended up using socket events instead of http in the end. Here's the code from the server and client side (simplified for others that might have a similar situation).

The only thing that sucked was not being able to use jinja2 to display elements in the webpage. But with a bit of (bad) js I resolved.

Server side:

@app.route('/home', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        result = request.json
        socketio.emit('my_socket_event',
                       result, 
                       broadcast=True  #use broadcast=True if you want the message to be displayed to all connected clients
                      )

Client side:

<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);


socket.on('my_socket_event',function(result) {
    console.log('[EVENT CALLED] my_socket_event')
    for (var elem in result) {
        let htmlFrag = "<p>" + elem + "</p>"
        $('.container').append(htmlFrag);
    }
    
})
</script>
f-starace
  • 278
  • 1
  • 17