Search code examples
pythonwebsocketaiopg

How can I use unique query for every client connected to websocket


I'm trying to have only one database connection in my websocket and return this information to each client connected. Is it possible to do that?

There is my current code:

import asyncio
import aiopg
import websockets
import logging
import sys
import configparser

config = configparser.ConfigParser()
config.read('config/config.ini')

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger('websockets.server')
logger2 = logging.getLogger('asyncio')
logger2.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger2.addHandler(logging.StreamHandler())

async def listen(websocket, path):

    async with aiopg.create_pool(config.get('default', 'connexion_bd'), maxsize=1, pool_recycle=0) as pool:
        async with pool.acquire() as conn1:
            async with conn1.cursor() as cur:

                await cur.execute(config.get('default', 'pg_listen'))
                while True:
                    msg = await conn1.notifies.get()
                    if msg.payload == 'finish':
                        return
                    else:
                        await websocket.send(msg.payload)


start_server = websockets.serve(listen, 'localhost', config.getint('default', 'port_websocket_server'))

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Currently, every time a client listen on my websocket, I got a new connection in my database. Every client will get same content so I don't need them to connect to database, only my websocket.

I try to split my code (connect on another websocket who is connecting on this one) but I got the same problem.

Any hints will be appreciated.

Thanks


Solution

  • Got it

    Need to put the websocket.serve after the query.

    import asyncio
    import functools
    
    import aiopg
    import websockets
    import logging
    import sys
    import configparser
    
    config = configparser.ConfigParser()
    config.read('config/config.ini')
    
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    logger = logging.getLogger('websockets.server')
    logger2 = logging.getLogger('asyncio')
    logger2.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
    logger2.addHandler(logging.StreamHandler())
    
    # Pour starter
    # env/bin/python3 websocket_server_aiopg.py
    
    USERS = set()
    
    
    async def listen(websocket, path, conn1):
        USERS.add(websocket)
    
        while True:
            msg = await conn1.notifies.get()
    
            if msg.payload == 'finish':
                return
            else:
                await asyncio.wait(([user.send(msg.payload) for user in USERS]))
    
    
    async def run_server():
        async with aiopg.create_pool(config.get('default', 'connexion_bd')) as pool:
            async with pool.acquire() as conn1:
                async with conn1.cursor() as cur:
                    await cur.execute(config.get('default', 'pg_listen'))
                    async with websockets.serve(functools.partial(listen, conn1=conn1), 'localhost', config.getint('default', 'port_websocket_server')) as ws:
                        await asyncio.sleep(1_000_000_000)  # consider waiting on an exit condition instead
    
    asyncio.get_event_loop().run_until_complete(run_server())