Realtime chat app using flask

Hey, In this tutorial we will look at how we can create a real-time chat app using python, flask, socketIO.

Real time chat app using flask

First of all, you need to install requirements (pip install requirements.txt)

Now, we are creating the main python file let’s name it

from flask import Flask, render_template, request
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app, cors_allowed_origins='*')

def handleMessage(msg):
   print('Message: ' + msg)
   send(msg, broadcast=True)

@app.route('/', methods=['GET', 'POST'])
def index():
   if request.method == 'POST':
      name = request.form.get('name')
      return render_template('index.html', name=name)

   return render_template('register.html')

if __name__ == '__main__':

Create register.html

<!doctype html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <h1>Enter your name</h1>
    <form action="" method="POST">
        <input type="text" name="name" placeholder="Name">
        <input type="submit" name="submit" value="Join now">

Create index.html

<title>Chat Room</title>
<script type="text/javascript" src=""></script>
<script src=""></script>
<script type="text/javascript">
$(document).ready(function() {

   var socket = io.connect('/');

    var username = "{{name}}";

   socket.on('connect', function() {
      socket.send(username + ' has connected!');

   socket.on('message', function(msg) {
      $("#messages").append('<li>' + msg + '</li>');
      console.log('Received message');

   $('#sendbutton').on('click', function() {

<h1>Realtime Chat App in Flask</h1>
<h2>Welcome, {{name}}</h2>
<ul id="messages"></ul>
<input type="text" id="myMessage" placeholder="Message">
<button id="sendbutton">Send</button>


Here is the GitHub link

Leave a Comment