Skip to content

Instantly share code, notes, and snippets.

@nautics889
Last active April 23, 2018 22:59
Show Gist options
  • Save nautics889/c5f3a7141a4543bf88e6c0e439d5133b to your computer and use it in GitHub Desktop.
Save nautics889/c5f3a7141a4543bf88e6c0e439d5133b to your computer and use it in GitHub Desktop.
from flask import Flask, render_template
from flask_socketio import SocketIO, send
from flask_sqlalchemy import SQLAlchemy
import os
import datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'keeeeyyyy'
socketio = SocketIO(app)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(basedir, 'app.db')
db = SQLAlchemy(app)
class History(db.Model):
id = db.Column('id', db.Integer, primary_key=True)
message = db.Column('message', db.String(500))
time = db.Column('time', db.String(80))
@socketio.on('message')
def handleMessage(msg):
now = datetime.datetime.now().strftime("%d-%m-%Y %H:%M")
print('Message: ' + msg + now)
message = History(message=msg, time=now)
db.session.add(message)
db.session.commit()
send(msg+now, broadcast=True)
@app.route('/')
def index():
messages = History.query.all()
return render_template('index.html', messages=messages)
if __name__ == '__main__':
socketio.run(app)
<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();
socket.on('connect', function() {
socket.send('User 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>
<ul id="messages">
{% for msg in messages %}
<li>{{msg.message}} - {{msg.time}}</li>
{% endfor %}</ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment