2013-05-18 10 views
6

Python 3을 사용하여 Pyramid에서 Websocket을 사용하는 방법이 있습니까? 서버에서 데이터가 변경 될 때 라이브 업데이트 테이블에 사용하고 싶습니다.Python3을 사용하여 Pyramid에서 Websocket 사용

나는 이미 긴 폴링을 사용한다고 생각했지만, 이것이 최선의 방법이라고 생각하지 않습니다.

의견이나 아이디어?

+0

확실하지 파이썬 웹 소켓에 대해 (gevent-socketio이 gevent에 의존, 잘 모르겠어요 파이썬 3에서 지원됩니다). 하지만 Server Sent Events를 고려해 보셨습니까? 예 : https://github.com/antoineleclair/zmq-sse-chat/blob/master/sse/views.py –

답변

3

https://github.com/housleyjk/aiopyramid이 맞습니다. 웹 소켓 http://aiopyramid.readthedocs.io/features.html#websockets 설명서를 참조하십시오

UPD : 피라미드 환경

웹 소켓 서버입니다.

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 

웹 소켓 클라이언트 : 3

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

aiopyramid를 지금 사용하십니까? 안정 됐어? – Infernion

+0

@Infernion 잘 작동하지만 새로운 프로젝트에서 websocket에 aiohttp를 사용합니다 – uralbash

+0

피라미드없이 그냥 aiohttp 만 사용합니까? – Infernion