Can I emit a message from socketio server side within a function in flask route?

Viewed 12

I have a flask app that is running selenium on a VM server. I am running a long looping function, and I want to alert the user on the client side if the driver have reached certain points while scrawling (because the function runs in a very long loop, it's not possible afaik to use flask flash without returning redirect or render_template)

This why I think socketio is my only option.

What I have currently is:

Snippet from routes.py (trying to connect a driver)

@app.route("/", methods=["GET", "POST"])
@login_required
def index():
    if request.method == "POST":
    try:
       globals()["driver_" + str(user_id)] = uc.Chrome(options=chrome_options, use_subprocess=True)

What I want to achieve:

try:
  globals()["driver_" + str(user_id)] = uc.Chrome(options=chrome_options, use_subprocess=True)
  message = "Driver connected succssefully"
  socket.emit('send-message', message)

I have the following in layout.html:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
  <script type="text/javascript" charset="utf-8">
    var socket = io();
    socket.on('connect', function() {
        console.log('initSocketIO');
    });

    socket.on('send-message', (message) => {
        console.log(message);
    });
  </script>

I can see in the console initSocketIO but how do I set it up that I will also see send-message data ("Driver connected succssefully") on the console?

0 Answers
Related