python - 使用 Python3 在 Pyramid 中使用 Websocket

标签 python python-3.x websocket pyramid pylons

有没有办法使用 Python 3 在 Pyramid 中使用 Websockets。 当服务器上有数据更改时,我想用它来实时更新表。

我已经想到了使用长轮询,但我认为这不是最好的方法。

有什么意见或想法吗?

最佳答案

https://github.com/housleyjk/aiopyramid为我工作。请参阅 websocket 的文档 http://aiopyramid.readthedocs.io/features.html#websockets

更新:

具有 Pyramid 环境的 WebSocket 服务器。

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 客户端:

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()

关于python - 使用 Python3 在 Pyramid 中使用 Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626177/

相关文章:

python - 基数排序, "Queue"对象不可迭代

java - Jersey 隐藏了 Spring 框架和 SockJS

java - Okhttp android Websocket 和 Jetty 服务器与 SSL 的连接

python - Linux 中 MP4 或 YUV 视频文件中的人脸检测?

python - Python BeautifulSoup 4 文档中给出的示例

python - PyCharm:如何在本地禁用缺少文档字符串检查

python - 如何在matplotlib绘图的xlabel中打印10K,20K......1M

python - 当一条记录属于多个组时,pandas groupby

python - AppVeyor 中的 UTF-8,Python 3.6

javascript - 为什么连接建立之前的 `websocket.close()` 会触发 `onerror` ?