parent
66d1e863fa
commit
d97543382e
5 changed files with 198 additions and 4 deletions
@ -1,19 +1,102 @@ |
|||||||
import logging |
import logging |
||||||
import datetime |
import datetime |
||||||
|
import os.path |
||||||
from redis import StrictRedis |
from redis import StrictRedis |
||||||
from tornado import web, websocket, escape |
from tornado import web, websocket, escape, options, locale, ioloop |
||||||
|
from tornado.httpserver import HTTPServer |
||||||
|
|
||||||
r = StrictRedis(db=1) |
r = StrictRedis(db=1) |
||||||
|
|
||||||
logger = logging.getLogger('handlers') |
logger = logging.getLogger('handlers') |
||||||
|
|
||||||
|
settings = { |
||||||
|
'cookie_secret': '__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__', |
||||||
|
'template_path': os.path.join(os.path.dirname(__file__), 'templates'), |
||||||
|
'static_path': os.path.join(os.path.dirname(__file__), 'static'), |
||||||
|
'login_url': '/login', |
||||||
|
'xsrf_cookies': True, |
||||||
|
'debug': True, |
||||||
|
'autoreload': True, |
||||||
|
'server_traceback': True, |
||||||
|
} |
||||||
|
|
||||||
class ChatHandler(websocket.WebSocketHandler): |
|
||||||
|
class Application(web.Application): |
||||||
|
def __init__(self): |
||||||
|
handlers = [ |
||||||
|
(r"/",ChannelHandler), |
||||||
|
(r"/chatsocket/(?P<channel>\w+)/", ChatSocketHandler) |
||||||
|
] |
||||||
|
super().__init__(handlers=handlers, **settings) |
||||||
|
|
||||||
|
|
||||||
|
class ChannelHandler(web.RequestHandler): |
||||||
|
def get(self, *args, **kwargs): |
||||||
|
title = kwargs.get('channel', 'main') |
||||||
|
self.chnl = kwargs.get('channel', 'main') |
||||||
|
cache = r.lrange('channels:{}'.format(title), 0, -1) |
||||||
|
messages =(escape.json_decode(x) for x in cache) if cache else [] |
||||||
|
print(messages) |
||||||
|
|
||||||
|
self.render('index2.html',messages=messages) |
||||||
|
|
||||||
|
|
||||||
|
class ChatSocketHandler(websocket.WebSocketHandler): |
||||||
|
|
||||||
waiters = set() |
waiters = set() |
||||||
|
|
||||||
def open(self, *args, **kwargs): |
def open(self, *args, **kwargs): |
||||||
self.chnl = kwargs.get('channel', 'main') |
self.chnl = kwargs.get('channel', 'main') |
||||||
self.waiters.add((self.chn1, self)) |
self.waiters.add((self.chnl, self)) |
||||||
self.chnl_key = 'channels:{}' |
# self.chnl_key = 'channels:{}:users'.format(self.chnl) |
||||||
|
# count = int(r.zcard(self.chnl_key)) |
||||||
|
# r.zadd(self.chnl_key, count+1, "mukhtar") |
||||||
|
# users = r.zrange(self.chnl_key,0,-1) |
||||||
|
# self.send_updates() |
||||||
|
|
||||||
|
def on_close(self): |
||||||
|
self.waiters.remove(self.chnl, self) |
||||||
|
|
||||||
|
def on_message(self, message): |
||||||
|
parsed = escape.json_decode(message) |
||||||
|
if 'dummy' in parsed: |
||||||
|
return |
||||||
|
|
||||||
|
chat = { |
||||||
|
'parent': 'inbox', |
||||||
|
'body': parsed['message'], |
||||||
|
'user': 'Mukhtar', |
||||||
|
'time': datetime.datetime.now().strftime('%H:%M:%S %Y-%m-%d') |
||||||
|
} |
||||||
|
self.update_channel_history(chat) |
||||||
|
self.send_updates(parsed); |
||||||
|
|
||||||
|
def update_channel_history(self,chat): |
||||||
|
chnl = 'channels:{}'.format(self.chnl) |
||||||
|
r.rpush(chnl, escape.json_encode(chat)) |
||||||
|
r.ltrim(chnl, -25, -1) |
||||||
|
|
||||||
|
def send_updates(self, chat): |
||||||
|
chnl_waiters = tuple(w for c, w in self.waiters) |
||||||
|
for waiter in chnl_waiters: |
||||||
|
try: |
||||||
|
waiter.write_message(chat) |
||||||
|
except: |
||||||
|
pass |
||||||
|
|
||||||
|
def __del__(self): |
||||||
|
r.zrem(self.chnl_key, self.current_user) |
||||||
|
self.log('PUSHED OUT') |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
options.parse_command_line() |
||||||
|
app = Application() |
||||||
|
server = HTTPServer(app) |
||||||
|
server.listen(8888) |
||||||
|
loop = ioloop.IOLoop.current() |
||||||
|
loop.start() |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': |
||||||
|
main() |
||||||
|
|||||||
@ -0,0 +1,42 @@ |
|||||||
|
<!DOCTYPE html> |
||||||
|
<html lang="en"> |
||||||
|
<head> |
||||||
|
<meta charset="UTF-8"> |
||||||
|
<title>Title</title> |
||||||
|
</head> |
||||||
|
<body> |
||||||
|
<h1>Всем привет , дети мои!!</h1> |
||||||
|
<div id="output"> |
||||||
|
</div> |
||||||
|
|
||||||
|
<form id="chatform"> |
||||||
|
<input id="text" type="text" /> |
||||||
|
<input type="submit" /> |
||||||
|
</form> |
||||||
|
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> |
||||||
|
<script type="text/javascript"> |
||||||
|
$(document).ready(function(){ |
||||||
|
var url = 'ws://127.0.0.1:8888/chat'; |
||||||
|
var socket = new WebSocket(url); |
||||||
|
|
||||||
|
socket.onopen = function(){ |
||||||
|
console.log("Соединение установлено"); |
||||||
|
socket.send("start"); |
||||||
|
} |
||||||
|
|
||||||
|
socket.onmessage = function (event) { |
||||||
|
console.log(event.data); |
||||||
|
var data = JSON.parse(event.data); |
||||||
|
output = output + '<h3>'+ data.msg +'</h3>'; |
||||||
|
$("#output").html(output); |
||||||
|
} |
||||||
|
$('form').submit(function(e){ |
||||||
|
e.preventDefault(); |
||||||
|
var currentText = $("#text").val(); |
||||||
|
socket.send(currentText); |
||||||
|
}); |
||||||
|
}); |
||||||
|
|
||||||
|
</script> |
||||||
|
</body> |
||||||
|
</html> |
||||||
@ -0,0 +1,61 @@ |
|||||||
|
<!DOCTYPE html> |
||||||
|
<html lang="en"> |
||||||
|
<head> |
||||||
|
<meta charset="UTF-8"> |
||||||
|
<title>Title</title> |
||||||
|
</head> |
||||||
|
<body> |
||||||
|
<h1>Chat</h1> |
||||||
|
<div id="inbox"> |
||||||
|
{% for message in messages %} |
||||||
|
<h1>{{ message["body"] }}</h1> |
||||||
|
<h3>{{ message["time"] }} </h3> |
||||||
|
{% end%} |
||||||
|
</div> |
||||||
|
<form method="post" id="messageform"> |
||||||
|
<textarea id="message" name="message"></textarea> |
||||||
|
<input type="submit" /> |
||||||
|
</form> |
||||||
|
<script type="text/javascript"> |
||||||
|
window.onload = function(){ |
||||||
|
var socket = new SocketHandler(); |
||||||
|
var form = document.getElementById('messageform'); |
||||||
|
|
||||||
|
form.onsubmit = function(e){ |
||||||
|
e.preventDefault(); |
||||||
|
console.log('submit click'); |
||||||
|
socket.send_message(form); |
||||||
|
} |
||||||
|
}; |
||||||
|
|
||||||
|
var SocketHandler = function(){ |
||||||
|
var url = 'ws://' + location.host + '/chatsocket/main/'; |
||||||
|
var sock = new WebSocket(url); |
||||||
|
var intervalId; |
||||||
|
sock.onopen = function(){ |
||||||
|
console.log("Start connect"); |
||||||
|
intervalId = setInterval(function(){sock.send('{"dummy": 1}');}, 150000); |
||||||
|
}; |
||||||
|
sock.onmessage = function(event){ |
||||||
|
console.log(event.data); |
||||||
|
message = JSON.parse(event.data); |
||||||
|
var inbox = document.getElementById('inbox'); |
||||||
|
inbox.innerHTML += '<h2>' + message.message + '</h2>'; |
||||||
|
}; |
||||||
|
this.send_message = function(form){ |
||||||
|
var elements = form.elements; |
||||||
|
var data = {}; |
||||||
|
var i=0; |
||||||
|
for(var i; i< elements.length; i++){ |
||||||
|
if (elements[i].name == 'message') { |
||||||
|
data[elements[i].name] = elements[i].value; |
||||||
|
} |
||||||
|
} |
||||||
|
sock.send(JSON.stringify(data)); |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
</script> |
||||||
|
</body> |
||||||
|
</html> |
||||||
@ -0,0 +1,6 @@ |
|||||||
|
import psycopg2 |
||||||
|
conn = psycopg2.connect(database="archilance", user="postgres", password="postgres", host="localhost") |
||||||
|
cursor = conn.cursor() |
||||||
|
cursor.execute("SELECT 1") |
||||||
|
rows = cursor.fetchall() |
||||||
|
print(rows) |
||||||
Loading…
Reference in new issue