@@ -169,6 +169,73 @@ async def close_room(self, room, namespace=None):
169169 self .logger .info ('room %s is closing [%s]' , room , namespace )
170170 await self .manager .close_room (room , namespace )
171171
172+ async def get_session (self , sid , namespace = None ):
173+ """Return the user session for a client.
174+
175+ :param sid: The session id of the client.
176+ :param namespace: The Socket.IO namespace. If this argument is omitted
177+ the default namespace is used.
178+
179+ The return value is a dictionary. Modifications made to this
180+ dictionary are not guaranteed to be preserved. If you want to modify
181+ the user session, use the ``session`` context manager instead.
182+ """
183+ namespace = namespace or '/'
184+ eio_session = await self .eio .get_session (sid )
185+ return eio_session .setdefault (namespace , {})
186+
187+ async def save_session (self , sid , session , namespace = None ):
188+ """Store the user session for a client.
189+
190+ :param sid: The session id of the client.
191+ :param session: The session dictionary.
192+ :param namespace: The Socket.IO namespace. If this argument is omitted
193+ the default namespace is used.
194+ """
195+ namespace = namespace or '/'
196+ eio_session = await self .eio .get_session (sid )
197+ eio_session [namespace ] = session
198+
199+ def session (self , sid , namespace = None ):
200+ """Return the user session for a client with context manager syntax.
201+
202+ :param sid: The session id of the client.
203+
204+ This is a context manager that returns the user session dictionary for
205+ the client. Any changes that are made to this dictionary inside the
206+ context manager block are saved back to the session. Example usage::
207+
208+ @eio.on('connect')
209+ def on_connect(sid, environ):
210+ username = authenticate_user(environ)
211+ if not username:
212+ return False
213+ with eio.session(sid) as session:
214+ session['username'] = username
215+
216+ @eio.on('message')
217+ def on_message(sid, msg):
218+ async with eio.session(sid) as session:
219+ print('received message from ', session['username'])
220+ """
221+ class _session_context_manager (object ):
222+ def __init__ (self , server , sid , namespace ):
223+ self .server = server
224+ self .sid = sid
225+ self .namespace = namespace
226+ self .session = None
227+
228+ async def __aenter__ (self ):
229+ self .session = await self .server .get_session (
230+ sid , namespace = self .namespace )
231+ return self .session
232+
233+ async def __aexit__ (self , * args ):
234+ await self .server .save_session (sid , self .session ,
235+ namespace = self .namespace )
236+
237+ return _session_context_manager (self , sid , namespace )
238+
172239 async def disconnect (self , sid , namespace = None ):
173240 """Disconnect a client.
174241
0 commit comments