Saturday, March 25, 2023

Implementing WebSocket with Flask And Python

Setup your virtual environment


python3 -m venv venv

Source (or activate) the virtual environment


source venv/bin/activate

First install Flask if you haven’t done so:


pip install flask

Install Flask-SocketIO with pip:


pip install flask_socketio


Python Flask Websocket

In the example below socket.io and the Flask module are used. socketio is an two-way event-based communication engine.


Events are triggered both by server and connected clients in socketio. If an event is detected, the related call back functions is called.


To implement event triggers or event callbacks in Flask is easy (The example below uses web sockets.)


Create a new file called app.py with this code:


from flask import Flask, render_template

from flask_socketio import SocketIO, emit


app = Flask(__name__)

socketio = SocketIO(app)


@app.route('/')

def index():

    return render_template('index.html')


@socketio.on('connect')

def test_connect():

    emit('after connect',  {'data':'Lets dance'})


if __name__ == '__main__':

    socketio.run(app)


then create a directory /templates/ with the file index.html. This uses JQuery and socket.io


<!DOCTYPE html>

<html lang="en">

   <head>

      <meta charset="UTF-8">

      <title>SocketIO example</title>

      <script src="https://code.jquery.com/jquery-3.3.1.js"></script>

      <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>

      <script type="text/javascript">

         $(document).ready(function() {

         

           // sending a connect request to the server.

           var socket = io.connect('http://localhost:5000');

         

           socket.on('after connect', function(msg) {

               console.log('After connect', msg);

               $('#log').append('<br>' + $('<div/>').text('Received: ' + msg.data).html());

          });        

         });

      </script>

   </head>

   <body>

    <h1>SocketIO Example</h1>

    <h2>Receive:</h2>

    <div id="log"></div>

   </body>

</html>


Start your app with:


python app.py


references:

https://pythonprogramminglanguage.com/python-flask-websocket/

No comments:

Post a Comment