我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用flask.request.sid()。
def s_connect(): g.user = get_jwt_user() if not g.user: return jsonify({}), 403 # get user rooms my_rooms = RoomMember.select('room_id').where('user_id', g.user['id']).group_by('room_id').get() for room in my_rooms: join_room('room-%s' % room.room_id) connected_users.append({ 'id': g.user['id'], 'sid': request.sid }) socketio.emit('user_connect',{'id':g.user['id']})
def on_disconnect() -> (int, None): """ when a client disconnects or the server no longer gets a ping response from the client :return json if ok, {'status_code': 200} """ user_id = str(environ.env.session.get(SessionKeys.user_id.value)) data = { 'verb': 'disconnect', 'actor': { 'id': user_id } } if not environ.env.config.get(ConfigKeys.TESTING): if environ.env.connected_user_ids.get(user_id) == request.sid: del environ.env.connected_user_ids[user_id] activity = as_parser(data) environ.env.observer.emit('on_disconnect', (data, activity)) return ECodes.OK, None
def background_thread(self): print 'processing clients' x = 0 polls_sent = {} while True: if self.client: line = self.client.readline() if line: #print 'line', line try: #data = {'data': json.loads(line.rstrip())} #print 'data', data socketio.emit('signalk', line.rstrip()) except: socketio.emit('log', line) print 'error: ', line.rstrip() continue polls = {} for sid in self.polls: for poll in self.polls[sid]: polls[poll] = True t = time.time() for message in polls: if not message in polls_sent or \ t - polls_sent[message] > 1: #print 'msg', message self.client.send(message + '\n') polls_sent[message] = t self.client.flush() self.client.recv() socketio.sleep(.25)
def on_signalk_poll(self, message): #print 'message', message if message == 'clear': self.polls[request.sid] = {} return self.polls[request.sid][message] = True #def on_disconnect_request(self): # disconnect()
def on_connect(self): #self.clients[request.sid] = Connection() #print('Client connected', request.sid, len(self.clients)) print('Client connected', request.sid) if not self.polls: self.connect_signalk(); self.polls[request.sid] = {} socketio.emit('signalk_connect', self.list_values)
def on_disconnect(self): #client = self.clients[request.sid].client #if client: # client.socket.close() del self.polls[request.sid] if not self.polls: self.client.socket.close() self.client = False print 'closed signalk client' print('Client disconnected', request.sid, len(self.polls))
def user_leave_room(room_id): member = RoomMember.select('room_members.id','room_members.user_id', 'r.user_id as owner_id') \ .join('rooms as r', 'r.id', '=', 'room_members.room_id') \ .where('room_members.room_id', room_id) \ .where('room_members.user_id', g.user['id']) \ .first() if not member: return jsonify({'message': "Unknown Room"}), 400 if member.user_id == member.owner_id: Room.where('id', room_id).delete() socketio.emit('close_room', {'room_id': room_id}, room='room-%s' % room_id) close_room(room='room-%s' % room_id, namespace='/') else: member.delete() clients = _.where(connected_users, {'id': member.user_id}) if clients and _.isList(clients): for item in clients: leave_room('room-%s' % room_id, sid=item['sid'], namespace='/') socketio.emit('update_members', {'room_id': room_id, 'detach': []}, room='room-%s' % room_id) return jsonify({'message': 'Success'}), 200
def s_disconnect(): client = _.findWhere(connected_users, {'sid': request.sid}) if client: user_id = client['id'] connected_users.remove(client) clients_exist = _.where(connected_users,{'id':user_id}) if not clients_exist or not len(clients_exist): socketio.emit('user_disconnect', {'id': user_id})
def s_message(data): rooms = socket_rooms() if 'room_id' in data and 'room-%s' % data['room_id'] in rooms: socketio.emit('message', data, room='room-%s' % data['room_id'], skip_sid=request.sid)
def s_user_typing(data): rooms = socket_rooms() if 'room_id' in data and 'room-%s' % data['room_id'] in rooms: socketio.emit('user_typing', data, room='room-%s' % data['room_id'], skip_sid=request.sid)
def on_login(login_info): try: game: Game = games[login_info['game']] player: Player = [player for player in game.players if player.token == login_info['token']][0] except KeyError: socketio.emit('error', 'Socket connection must start with sending of token (cookie) and game (id) in JSON format') return except IndexError: socketio.emit('error', 'User does not exist') return player.socket_sid = request.sid socketio.emit('client full', json.dumps(game.retrieve_game(player)), room=player.socket_sid)
def socketio_users_connect(): #~ print('sid:'+request.sid) join_room('user_'+current_user.username) socketio.emit('user_quota', json.dumps(app.isardapi.get_user_quotas(current_user.username, current_user.quota)), namespace='/sio_users', room='user_'+current_user.username)
def socketio_admins_connect(): #~ print('sid:'+request.sid) if current_user.role=='admin': join_room('admins') join_room('user_'+current_user.username) socketio.emit('user_quota', json.dumps(app.isardapi.get_user_quotas(current_user.username, current_user.quota)), namespace='/sio_admins', room='user_'+current_user.username) else: None
def socketio_admins_connect(join_rooms): #~ print('sid:'+request.sid) if current_user.role=='admin': for rm in join_rooms: join_room(rm) print('JOINED:'+rm)
def collect_topics(): topic_dict = dict() app.logger.debug("Inside Collected Topics - Number of connected clients: " + str(len(client_dict))) for sid in client_dict.keys(): for interest in client_dict[sid].keys(): for region in client_dict[sid][interest].keys(): if client_dict[sid][interest][region][0]: topic = interest + '_' + region try: if client_dict[sid][interest][region][1] < topic_dict[topic]: topic_dict[topic] = client_dict[sid][interest][region][1] except KeyError: topic_dict[topic] = client_dict[sid][interest][region][1] app.logger.debug("Topic Dict: " + str(topic_dict)) return topic_dict
def messenger(): while True: sleep(5) app.logger.debug("Inside Messenger Iteration") msgs = poll_topics() ads = dict() for topic in msgs.keys(): all_msgs = msgs[topic] ads[topic] = dict() for msg in all_msgs: offset = msg[2] ad = msg[-1] ads[topic][offset] = ad # offset = msg.offset # ad = msg.value # try: # ads[topic][offset] = ad # except KeyError: # ads[topic] = dict # ads[topic][offset] = ad for sid in client_dict.keys(): interest_list = client_dict[sid].keys() for interest in interest_list: regions = client_dict[sid][interest].keys() for region in regions: if client_dict[sid][interest][region][0]: offset = client_dict[sid][interest][region][1] while True: try: topic = interest+'_'+region app.logger.debug('Emitting to server with topic ' + topic) ad = ads[topic][offset] # if len(ad) == 0: # app.logger.debug('ad length was 0') # continue socketio.emit('server-message', {'topic': topic, 'ad': ad}, room=sid, callback=ack) offset += 1 except KeyError: app.logger.debug("Key Error Exception happened") break
def ack(topic, sid): app.logger.debug("Topic recevied is: " + topic) with lock: topic = topic.split('_') client_dict[sid][topic[0]][topic[1]][1] += 1
def index(): if request.method == 'GET': r = requests.get(lookupaddr+'/topiclist') topiclist = json.loads(r.content) return render_template('index.html', topiclist=topiclist) else: with lock: interest_list = request.form.getlist('adcat') sid = str(request.headers.get('sid')) client_dict[sid] = dict() for interest in interest_list: client_dict[sid][str(interest)] = dict() print interest_list return "subscribed!"
def get_region_polygon(): with lock: latitude = request.args.get('lat') print latitude longitude = request.args.get('lon') print longitude r = requests.get(lookupaddr+'/region?lat='+str(latitude)+'&lon='+str(longitude)) publishregion = r.content print publishregion publishregion = json.loads(publishregion) app.logger.debug("Region of publisher: " + str(publishregion)) # print publishregion # print type(publishregion) # print publishregion['name'] sid = str(request.headers.get('sid')) interest_list = client_dict[sid].keys() for interest in interest_list: regions = client_dict[sid][interest].keys() new_region_exists = False for region in regions: if region == publishregion['name']: new_region_exists = True client_dict[sid][interest][region][0] = True else: client_dict[sid][interest][region][0] = False if not new_region_exists: client_dict[sid][interest][publishregion['name']] = [True, 0] print client_dict return str(publishregion['polygon'])
def test_disconnect(): print('Client disconnected', request.sid)
def addDevice(message): try: global devices deviceClassName = message['classname'] deviceTitle = message['title'] devicePort = None deviceCategory = (message.has_key('category')) and message['category'] or None # if port is larger than 5000, then it is an remote device, # we should create an room based on its sid # if port is allready used, then update the device and make it accessable if message.has_key('port'): devicePort = message['port'] for i in range(len(devices)): if 'port' in dir(devices[i]): if devicePort > 5000: join_room(request.sid) if devices[i].port == devicePort: # update device deviceID = devices[i].id devices[i] = Device.updateDevice(deviceID, deviceClassName, deviceTitle, devicePort, deviceCategory) emit('remove', {'id':deviceID}, broadcast = True) emit('add', devices[i].description(), broadcast = True) return # add device as usual deviceID = devices[len(devices) - 1].id + 1 message['id'] = deviceID device = Device.addDevice(deviceID, deviceClassName, deviceTitle, devicePort, deviceCategory) devices.append(device) emit('add', device.description(), broadcast = True) except Exception as e: logging.debug(e) # Remove a device and notify all clients
def connect(): global tokens if (request.args.get('token', '') not in tokens): disconnect() return global thread if thread is None: thread = socketio.start_background_task(target=background_thread) # session['thread'] = socketio.start_background_task(background_thread, session['user']) # emit('response', {'data': 'Connected'}) print('Client connected: ', request.sid) # Disconnect the client and remove device if it has one # Current: no accessable funtion
def test_disconnect(): # here we have to use the sid to locate the the disconnected device # and if it exists, remove its room and set it as unaceessable try: close_room(request.sid) except Exception as e: logging.debug(e) # Remove token if exist global tokens token = request.args.get('token', '') if token in tokens: tokens.remove(token) logging.debug("Token removed:" + token) # disconnect() print('Client disconnected: ', request.sid) # @app.route('/') # def index(): # return render_template('index.html', async_mode=socketio.async_mode) # @socketio.on('request', namespace = mynamespace) # def broadcast_message(message): # message = {'data': {'message': 'I am the message'}} # emit('response', # {'data': message['data']['message']}, # broadcast=True)
def grading_disconnect(): print('Client disconnected', request.sid) if not current_app.config['DEBUG']: send_slack_msg('User {} has stopped grading'.format(current_user.id)) if 'grading_session' in session and session['grading_session']: grading_session = session['grading_session'] grading_session.ended_on = datetime.utcnow() db.session.add(grading_session) db.session.commit() else: grading_session = UserGradingSession.latest(current_user.id) grading_session.ended_on = datetime.utcnow() db.session.add(grading_session) db.session.commit()
def on_connect(): app.logger.info('New User Connection') try: user = get_current_user(request) except Exception: return rh.error(**ec.INVALID_USER_PERMISSIONS) connect(request.sid, user)
def on_disconnect(): app.logger.info('User Disconnected') try: user = get_current_user(request) except Exception: return rh.error(**ec.INVALID_USER_PERMISSIONS) disconnect(request.sid, user)
def on_join(data): room_id = data["room_id"] if room_id not in active_rooms: raise Exception("Room does not exist") room = active_rooms[room_id] new_player = room.add_new_player(UUID(request.sid)) active_players[UUID(request.sid)] = new_player join_room(room_id) player_list = list(map(lambda x: str(x), room.players.keys())) socketio.emit("game_update", build_game_update_payload(room), room=str(room_id))
def on_disconnect(): player_id = UUID(request.sid) room_id = active_players[player_id].room.id leave_room(room_id, player_id)
def on_ready(data): room_id = data['room_id'] room = active_rooms[room_id] player_id = UUID(request.sid) player = room.players[player_id] player.status = PlayerStatus.ready if len(room.players) != 1 and sum(map(lambda x: x.status == PlayerStatus.ready, room.players.values())) == len(room.players): session = Session(room) socketio.emit("game_update", build_game_update_payload(room), room=str(room_id))
def on_unready(data): room_id = data['room_id'] room = active_rooms[room_id] player_id = UUID(request.sid) player = room.players[player_id] if room.session is not None: room.session.eliminate_player_by_id(player_id) else: player.status = PlayerStatus.joined socketio.emit("game_update", build_game_update_payload(room), room=str(room_id))
def handle_connected(): # clients.append(request.namespace) sockets.append(request.sid)
def handle_disconnected(): # clients.remove(request.namespace) sockets.remove(request.sid)
def handle_connected(): """ connect: ???? """ sockets.append(request.sid)
def handle_disconnected(): """ disconnect: ?????? """ sockets.remove(request.sid)
def watchdog_connect(): if sentrygund.config.debug: print '[debug][views] %s connected' % (request.sid) clients.append(request.sid)
def watchdog_disconnect_request(): if sentrygund.config.debug: print '[debug][views] %s connected' % (request.sid) clients.remove(request.sid) disconnect() # VIEWS -----------------------------------------------------------------------
def handle_disconnect(): """ Disconnect handler that removes the client from the room list :return: """ app.logger.debug("Client disconnected: " + str(request.sid)) with lock: sid = str(request.sid) try: client_dict.pop(sid) except KeyError: pass # @socketio.on('client-message') # def handle_client_message(msg): # """ # Custom event name example # :param msg: # :return: # """ # # emit message on server-message channel and set a callback for handling delivery # emit('server-message', ('lele', 'theeke'), callback=ack) # app.logger.debug('Client message received: ' + msg) # # return acknowledgement: can be processed as args i client callback # return 'got it', 'carry on' # def ack(): # """ # Callback for acknowledging whether # client received the message or not # :return: # """ # print "ack" # def messenger(): # """ # Simple stupid test # :return: # """ # for i in range(0,100): # if len(client_dict) > 0: # idx = i % len(client_dict) # app.logger.info('Sending message to client in room: ') # socketio.emit('server-message', {'data': 'Message sent at time: ' + str(i)}) # app.logger.info('Messenger in iteration: ' + str(i)) # sleep(5) #
def uber_oauth_response(): params = parse_req_data(request) event = params.get('event_type') if event != 'requests.status_changed': logger.error('Unsure how to handle event from Uber: {}'.format(event)) return rh.json_response() metadata = params.get('meta') or {} external_ride_id = metadata.get('resource_id') if not external_ride_id: logger.error('Couldn\'t find meta.resource_id in params body...: {}'.format(params)) return rh.json_response() pending_ride = find(PendingRide, {'external_ride_id': external_ride_id}) if not pending_ride: logger.error('No Pending Ride for external_ride_id: {}'.format(external_ride_id)) return rh.json_response() user = find(User, {'id': pending_ride.user_id}) if not user: logger.error('No User for id: {}'.format(pending_ride.user_id)) return rh.json_response() # Get all socket ids associated with user from cache user_sids = cache.hget(config('USER_CONNECTIONS'), user.uid) or [] if not user_sids: logger.error('No open sockets registered for user with uid: {}'.format(user.uid)) return rh.json_response() status = metadata.get('status') status_update = uber_status_update(status) if not status_update: logger.error('No status update could be found for ride status: {}'.format(status)) return rh.json_response() # Update the ride even if no need to reach out to user logger.info('Updating pending ride with uid {} to status of {}'.format(pending_ride.uid, status)) update(pending_ride, {'status', status_update['status']}) if status_update.get('destroy_ride'): destroy_instance(pending_ride) response_msg = status_update.get('response') if response_msg: [socket.emit('job:update', {'text': response_msg}, namespace=namespace, room=sid) for sid in user_sids] return rh.json_response() # ---- Socket Listeners ----