authentication.py (624B)
1 #!/usr/bin/env python 2 3 import asyncio 4 5 import django 6 import websockets 7 8 django.setup() 9 10 from sesame.utils import get_user 11 from websockets.frames import CloseCode 12 13 14 async def handler(websocket): 15 sesame = await websocket.recv() 16 user = await asyncio.to_thread(get_user, sesame) 17 if user is None: 18 await websocket.close(CloseCode.INTERNAL_ERROR, "authentication failed") 19 return 20 21 await websocket.send(f"Hello {user}!") 22 23 24 async def main(): 25 async with websockets.serve(handler, "localhost", 8888): 26 await asyncio.Future() # run forever 27 28 29 if __name__ == "__main__": 30 asyncio.run(main())