Is there a way to use Websockets in Pyramid using Python 3. I want to use it for live-updating tables when there are data changes on the server.
I already thought of using long-polling, but I don't think this is the best way.
Any comments or ideas?
https://github.com/housleyjk/aiopyramid works for me. See the documentation for websocket http://aiopyramid.readthedocs.io/features.html#websockets
UPD:
WebSocket server with pyramid environment.
import aiohttp
import asyncio
from aiohttp import web
from webtest import TestApp
from pyramid.config import Configurator
from pyramid.response import Response
async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    while not ws.closed:
        msg = await ws.receive()
        if msg.tp == aiohttp.MsgType.text:
            if msg.data == 'close':
                await ws.close()
            else:
                hello = TestApp(request.app.pyramid).get('/')
                ws.send_str(hello.text)
        elif msg.tp == aiohttp.MsgType.close:
            print('websocket connection closed')
        elif msg.tp == aiohttp.MsgType.error:
            print('ws connection closed with exception %s' %
                  ws.exception())
        else:
            ws.send_str('Hi')
    return ws
def hello(request):
    return Response('Hello world!')
async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/{name}', websocket_handler)
    config = Configurator()
    config.add_route('hello_world', '/')
    config.add_view(hello, route_name='hello_world')
    app.pyramid = config.make_wsgi_app()
    srv = await loop.create_server(app.make_handler(),
                                   '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
WebSocket client:
import asyncio
import aiohttp
session = aiohttp.ClientSession()
async def client():
    ws = await session.ws_connect('http://0.0.0.0:8080/foo')
    while True:
        ws.send_str('Hi')
        await asyncio.sleep(2)
        msg = await ws.receive()
        if msg.tp == aiohttp.MsgType.text:
            print('MSG: ', msg)
            if msg.data == 'close':
                await ws.close()
                break
            else:
                ws.send_str(msg.data + '/client')
        elif msg.tp == aiohttp.MsgType.closed:
            break
        elif msg.tp == aiohttp.MsgType.error:
            break
loop = asyncio.get_event_loop()
loop.run_until_complete(client())
loop.close()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With