Headlines
Loading...
Real time chat app using flask

Real time 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.



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


Now, we are creating the main python file let's name it main.py

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='*')

@socketio.on('message')
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__':
socketio.run(app)


Create register.html

<!doctype html>
<html lang="en">
<head>
<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">
<title>Register</title>
</head>
<body>
<h1>Enter your name</h1>
<form action="" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="submit" name="submit" value="Join now">
</form>
</body>
</html>


Create index.html

<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<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() {
socket.send($('#myMessage').val());
$('#myMessage').val('');
});

});
</script>
<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>
</body>
</html>


Here is the GitHub link

0 Comments: