moved some models added cron and websocket base class
This commit is contained in:
59
backend/websocket/base.py
Normal file
59
backend/websocket/base.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from flask_login import current_user
|
||||
from flask_socketio import SocketIO, emit
|
||||
|
||||
from backend import app
|
||||
|
||||
logger = logging.getLogger("lrc.websocket")
|
||||
|
||||
async_mode = 'threading' # set to traditional python threading model
|
||||
# async_mode = None
|
||||
socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)
|
||||
|
||||
|
||||
class WebSocketBase:
|
||||
def __init__(self, flask_app_context=None):
|
||||
if flask_app_context is None:
|
||||
self.flask_app_context = app
|
||||
self.socket_thread = None
|
||||
|
||||
def start_websocket_in_thread(self, host=None, port=None, debug=None):
|
||||
self.socket_thread = threading.Thread(
|
||||
target=self.start_websocket,
|
||||
args=(host, port, debug))
|
||||
self.socket_thread.start()
|
||||
return self.socket_thread
|
||||
|
||||
def start_websocket(self, host=None, port=None, debug=None):
|
||||
if debug is None:
|
||||
debug = self.flask_app_context.debug
|
||||
socketio.run(self.flask_app_context, host=host, port=port, debug=debug)
|
||||
|
||||
@staticmethod
|
||||
@socketio.on('connect')
|
||||
def connect_handler():
|
||||
logger.debug("new connection...")
|
||||
print(current_user)
|
||||
if current_user.is_authenticated:
|
||||
logger.debug("user is authenticated")
|
||||
print("allowed!")
|
||||
emit('my response',
|
||||
{'message': '{0} has joined'.format(current_user.name)},
|
||||
broadcast=True)
|
||||
else:
|
||||
logger.info("user is not authenticated!")
|
||||
print("not allowed!!")
|
||||
return False # not allowed here
|
||||
|
||||
@socketio.on_error()
|
||||
def handle_error(self, error):
|
||||
logger.error(error)
|
||||
print(error)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
wsb = WebSocketBase()
|
||||
#wsb.start_websocket_in_thread(debug=True)
|
||||
wsb.start_websocket(debug=True)
|
||||
Reference in New Issue
Block a user