You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.5 KiB
97 lines
2.5 KiB
import os.path
|
|
from tornado import gen, web, websocket, escape, options
|
|
from tornado.ioloop import IOLoop
|
|
from tornado.httpserver import HTTPServer
|
|
from tornado.options import parse_command_line
|
|
|
|
import psycopg2
|
|
import momoko
|
|
|
|
|
|
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 BaseHandler(web.RequestHandler):
|
|
@property
|
|
def db(self):
|
|
return self.application.db
|
|
|
|
|
|
class TutorialHandler(websocket.WebSocketHandler):
|
|
|
|
@property
|
|
def db(self):
|
|
return self.application.db
|
|
|
|
waiters = set()
|
|
|
|
def open(self, *args, **kwargs):
|
|
self.waiters.add(self)
|
|
# cursor = self.db.execute("SELECT * FROM users_user WHERE id=2")
|
|
# data = cursor.fetchone()
|
|
print({'hello': 'test'})
|
|
|
|
@gen.coroutine
|
|
def on_message(self, message):
|
|
parsed = escape.json_decode(message)
|
|
if 'dummy' in parsed:
|
|
return
|
|
|
|
insert_sql = "INSERT INTO chat_message (id,text,created,order_id, user_id) VALUES (DEFAULT,'{0}',NOW(),6,4)".format(str(parsed['message']))
|
|
|
|
yield self.db.execute(insert_sql)
|
|
|
|
cursor = yield self.db.execute("SELECT * FROM chat_message")
|
|
data = cursor.fetchall()
|
|
|
|
for waiter in self.waiters:
|
|
waiter.write_message({'msg': parsed['message']})
|
|
|
|
|
|
def check_origin(self, origin):
|
|
return True
|
|
# @gen.coroutine
|
|
# def get(self):
|
|
# cursor = yield self.db.execute("SELECT * FROM users_user WHERE id=2")
|
|
# data = cursor.fetchone()
|
|
# print(data[0])
|
|
# self.finish()
|
|
|
|
|
|
class Application(web.Application):
|
|
|
|
def __init__(self):
|
|
handlers = [
|
|
(r"/chat", TutorialHandler),
|
|
]
|
|
super().__init__(handlers=handlers, **settings)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parse_command_line()
|
|
application = Application()
|
|
ioloop = IOLoop.instance()
|
|
|
|
application.db = momoko.Pool(
|
|
dsn='dbname=archilance user=postgres password=postgres host=localhost',
|
|
size=1,
|
|
ioloop=ioloop,
|
|
)
|
|
future = application.db.connect()
|
|
ioloop.add_future(future, lambda f: ioloop.stop())
|
|
ioloop.start()
|
|
future.result()
|
|
|
|
http_server = HTTPServer(application)
|
|
http_server.listen(8888, 'localhost')
|
|
ioloop.start()
|
|
|
|
|
|
|