Python flask_socketio.disconnect() Examples

The following are 12 code examples of flask_socketio.disconnect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_socketio , or try the search function .
Example #1
Source File: event_stream.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_app(redis_url):
    socketio = SocketIO(logger=True)

    app = Flask(__name__)
    app.config.from_object(config)

    @app.route("/")
    def index():
        return jsonify({"name": "%s Event stream" % config.APP_NAME})

    @socketio.on("connect", namespace="/events")
    def connected():
        try:
            verify_jwt_in_request()
            app.logger.info("New websocket client connected")
        except Exception:
            app.logger.info("New websocket client failed to connect")
            disconnect()
            return False

    @socketio.on("disconnect", namespace="/events")
    def disconnected():
        app.logger.info("Websocket client disconnected")

    @socketio.on_error("/events")
    def on_error(error):
        app.logger.error(error)

    socketio.init_app(app, message_queue=redis_url, async_mode="gevent")
    return (app, socketio) 
Example #2
Source File: sockets.py    From dino with Apache License 2.0 5 votes vote down vote up
def disconnect_by_sid(sid: str) -> None:
        if sid is None:
            raise ValueError('need sid to disconnect client')
        environ.env._force_disconnect_by_sid(sid, '/ws') 
Example #3
Source File: sockets.py    From dino with Apache License 2.0 5 votes vote down vote up
def on_login(data: dict, activity: Activity) -> (int, str):
    try:
        status_code, msg = api.on_login(data, activity)
        if status_code != 200:
            disconnect()
        return status_code, msg
    except Exception as e:
        logger.error('could not login, will disconnect client: %s' % str(e))
        logger.exception(traceback.format_exc())
        environ.env.capture_exception(sys.exc_info())
        return 500, str(e) 
Example #4
Source File: sockets.py    From dino with Apache License 2.0 5 votes vote down vote up
def on_leave(data: dict, activity: Activity) -> (int, Union[str, dict, None]):
    return api.on_leave(data, activity)


# no pre-processing for disconnect event 
Example #5
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def diagnostic():
    """
    Get services journal and status
    """
    getServicesStatus()
    logs = []
    for service in services_list:
        sysctl_status = subprocess.run(['systemctl', 'status', service['service_unit']],
                                stdout=subprocess.PIPE,
                                universal_newlines=True)
        journalctl = subprocess.run(['journalctl', '--since', '7 days ago', '-u', service['service_unit']], 
                                 stdout=subprocess.PIPE, 
                                 universal_newlines=True)
        
        #Replace carrier return to <br> for html view
        sysctl_status = sysctl_status.stdout.replace('\n', '<br>') 
        journalctl = journalctl.stdout.replace('\n', '<br>')
        active_state = "Active" if service['active'] == True else "Inactive"
        logs.append({'name' : service['service_unit'], 'active' : active_state, 'sysctl_status' : sysctl_status, 'journalctl' : journalctl})
        
    return render_template('diagnostic.html', logs = logs)
    

#### Handle connect/disconnect events #### 
Example #6
Source File: websockets.py    From Lie_to_me with MIT License 5 votes vote down vote up
def handle_client_disconnect(msg):
    disconnect()


# Affectiva Client ready to receive photos (base64_images) 
Example #7
Source File: websockets.py    From Lie_to_me with MIT License 5 votes vote down vote up
def handle_next_frame_request(json):
    global current_frame
    
    # print("Previous frame data: {0}".format(str(json)))

    if json['data']:
        # anger, contempt, disgust, engagement, fear, joy, sadness, surprise, valence
        emotions = json['data'][0]['emotions']
        expressions = json['data'][0]['expressions']
        eye_closure = expressions['eyeClosure']

        emotion_data.append(emotions)
        eye_closure_data.append(eye_closure)
    else:
        # No data was obtained
        emotion_data.append(None)
        eye_closure_data.append(None)

    if current_frame[0] < len(base64_frames):
        emit('next_frame', [current_frame[0], base64_frames[current_frame[0]]])
        current_frame[0] += 1
    else:
        emit('no_more_frames', 'Completed')
        # disconnect()

        # Parse Data and Save Data to Disk
        blink_data = detect_blinks(eye_closure_data, video_fps_rate[0])
        microexpression_data = microexpression_analyzer(emotion_data, video_fps_rate[0])
        json_path = os.path.join(basedir, 'static', 'data', 'tmp_json')

        with shelve.open(os.path.join(json_path, 'facial_data.shlf')) as shelf:
            shelf['emotion_data'] = emotion_data
            shelf['micro_expression_data'] = microexpression_data
            shelf['blink_data'] = blink_data

        # Notify client that facial data write is complete
        emit('data_complete', 'Facial_Complete') 
Example #8
Source File: socketserver.py    From docassemble with MIT License 5 votes vote down vote up
def terminate_interview_connection():
    sys.stderr.write("terminate_interview_connection\n")
    # hopefully the disconnect will be triggered
    # if request.sid in threads:
    #     rr.publish(request.sid, json.dumps(dict(origin='client', message='KILL', sid=request.sid)))
    socketio.emit('terminate', {}, namespace='/wsinterview', room=request.sid)
    #disconnect() 
Example #9
Source File: socketserver.py    From docassemble with MIT License 5 votes vote down vote up
def on_interview_manual_disconnect(data):
    sys.stderr.write("Client manual disconnect\n")
    yaml_filename = data['i']
    session_info = get_session(yaml_filename)
    session_id = session_info['uid']
    the_user_id = session.get('user_id', 't' + str(session.get('tempuser', None)))
    if request.sid in secrets:
        del secrets[request.sid]
    if session_id is not None:
        rr.delete('da:interviewsession:uid:' + str(session_id) + ':i:' + str(yaml_filename) + ':userid:' + str(the_user_id))
        key = 'da:session:uid:' + str(session_id) + ':i:' + str(yaml_filename) + ':userid:' + str(the_user_id)
        rr.expire(key, 10)
        rr.publish(request.sid, json.dumps(dict(origin='client', message='KILL', sid=request.sid))) 
Example #10
Source File: socketserver.py    From docassemble with MIT License 5 votes vote down vote up
def terminate_monitor_connection():
    sys.stderr.write("terminate_monitor_connection\n")
    # hopefully the disconnect will be triggered
    # if request.sid in threads:
    #     rr.publish(request.sid, json.dumps(dict(origin='client', message='KILL', sid=request.sid)))
    socketio.emit('terminate', {}, namespace='/monitor', room=request.sid)
    #disconnect() 
Example #11
Source File: socketserver.py    From docassemble with MIT License 5 votes vote down vote up
def terminate_observer_connection():
    sys.stderr.write("terminate_observer_connection\n")
    # hopefully the disconnect will be triggered
    # if request.sid in threads:
    #     rr.publish(request.sid, json.dumps(dict(origin='client', message='KILL', sid=request.sid)))
    socketio.emit('terminate', {}, namespace='/observer', room=request.sid)
    #disconnect() 
Example #12
Source File: utils.py    From Titan with GNU Affero General Public License v3.0 5 votes vote down vote up
def default_socketio_error_handler(e):
    disconnect()