2

I'm building a Pyramid application using pyramid_sockjs. This app needs to react to incoming messages from redis pub/sub or rabbitmq. Where am I supposed to plug in the logic to listen to the messaging system and react by sending messages to sockjs clients?

I have found this link for socket.io, and I would like to do the same with sockjs and Pyramid.

tshepang
  • 12,111
  • 21
  • 91
  • 136
ascobol
  • 7,554
  • 7
  • 49
  • 70

1 Answers1

0

assuming you setup a pyramid config with config.include('pyramd_sockjs') followed by config.add_sockjs_route(). the general difficulty here is to figure out how to get hold of the app's current sockjs-sessions. i'm thinking of three scenarios:

  1. usually you react to messages from within you own subclass of pyramid_sockjs.session.Session as shown in the chat example.
  2. broadcasting messages from within one of your views is just as easy by calling request.get_sockjs_manager().broadcast(some_message)
  3. however, if you're neither inside the sockjs-messaging- nor the http-request-cycle like in your case, then you have to resort to pyramid's registry where all addons leave their traces.

at minute 5 in your video you would write something like this:

def listener():
    r = redis.Redis()
    r.subscribe(['foo'])
    for msg in r.listen():
        from pyramid.threadlocal import get_current_registry
        get_current_registry().__sockjs_managers__[''].broadcast(msg)

to explain the above hack:

  • get_current_registry is usually discouraged because it's hard to test your code. it returns the current request's or the global registry - a central core-component of pyramid.
  • for __sockjs_managers__ pyramid_sockjs should have provided a getter on the registry as it did for the request.
  • the empty string is the pyramid_sockjs' default name attribute (pass as kw to add_sockjs_route to change it)

unfortunately pyramid_sockjs doesn't provide "rooms" yet so your messages will be broadcasted to all connected clients without any prior filter mechanisms. to help that you might want to subclass pyramid_sockjs.session.Session and .SessionManager. (please tell if you do!)

espretto
  • 234
  • 2
  • 11