def test_add_equal_hashes(self): redis_set = Set() python_set = set() for value in [ 1.0, 1, complex(1.0, 0.0), Decimal(1.0), Fraction(2, 2), u'a', b'a', 'a', ]: redis_set.add(value) python_set.add(value) self.assertEqual(len(redis_set), len(python_set)) self.assertIn(value, redis_set) self.assertIn(value, python_set) redis_values = [] while redis_set: redis_values.append(redis_set.pop()) python_values = [] while python_set: python_values.append(python_set.pop()) self.assertEqual(sorted(redis_values), sorted(python_values))
def __init__(self, redis): self.orders = Set(key="orders", redis=redis) self.finished = Set(key="completed", redis=redis)
def create_set(self, *args, **kwargs): kwargs['redis'] = self.redis return Set(*args, **kwargs)
class ChatConsumer(AsyncJsonWebsocketConsumer): group_name = "broadcast" users = Set() messages = Deque([], settings.CHAT_QUEUE_LEN) async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: await self.accept() await self.join_room() async def receive_json(self, content): if content.get("type", None) == "ADD_MESSAGE": await self.channel_layer.group_send( self.group_name, { "type": "chat.message", "username": self.scope["user"].username, "message": content.get("message", None), } ) self.messages.append({ "author": self.scope["user"].username, "message": content.get("message", None) }) async def disconnect(self, code): self.users.remove(self.scope["user"]) await self.channel_layer.group_discard( self.group_name, self.channel_name, ) await self.channel_layer.group_send( self.group_name, { "type": "broadcast.presence", "users": [{'name': u.username, 'id': u.id} for u in self.users], } ) async def join_room(self): """ Called by receive_json when someone sent a join command. """ self.users.add(self.scope["user"]) # Add them to the group so they get room messages await self.channel_layer.group_add( self.group_name, self.channel_name, ) await self.channel_layer.group_send( self.group_name, { "type": "broadcast.presence", "users": [{'name': u.username, 'id': u.id} for u in self.users], } ) await self.send_json({"messages": list(self.messages), "type": "ADD_MESSAGES"}) # These helper methods are named by the types we send - so broadcast.presence becomes broadcast_presence async def broadcast_presence(self, event): """ Called when someone has joined or left our chat. """ # Send a message down to the client await self.send_json( { "type": "USERS_LIST", "users": event["users"], }, ) # These helper methods are named by the types we send - so chat.message becomes chat_message async def chat_message(self, event): """ Called when someone has messaged our chat. """ # Save message and send down to the client await self.send_json({ "author": event["username"], "message": event["message"], "type": "ADD_MESSAGE" })