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