PubNub Python Tutorial

Just recently I discovered a nifty abstraction called PubNub which allows you to easily send point to point or broadcast messages. If you want to write a chat program or set up an Arduino that takes an action from a remote client, it’s really easy to setup.

There actually weren’t too many resources on the internets for a barebones Python example (or any Python example that I found), so I thought I’d just publish this into the wild to save everyone 10 minutes or so (and if I end up getting 4 million page views on this page, then the total time I will have saved everyone equates to one human lifetime!)

Server

import os
from Pubnub import Pubnub

PUBNUB_PUBLISH_KEY = os.environ['PUBNUB_PUBLISH_KEY']
PUBNUB_SUBSCRIBE_KEY = os.environ['PUBNUB_SUBSCRIBE_KEY']
PUBNUB_SECRET_KEY = os.environ['PUBNUB_SECRET_KEY']

CHANNEL = "Lobbdawg Awesome Channel"

if __name__ == "__main__":
    pubnub = Pubnub(publish_key=PUBNUB_PUBLISH_KEY,
                    subscribe_key=PUBNUB_SUBSCRIBE_KEY,
                    secret_key=PUBNUB_SECRET_KEY,
                    cipher_key='',
                    ssl_on=False
                    )

    def callback(message, channel):
        print "Channel %s: (%s)" % (channel, message)

    print "Listening on Channel %s" % CHANNEL
    pubnub.subscribe(CHANNEL, callback)

Client

import os
from Pubnub import Pubnub

PUBNUB_PUBLISH_KEY = os.environ['PUBNUB_PUBLISH_KEY']
PUBNUB_SUBSCRIBE_KEY = os.environ['PUBNUB_SUBSCRIBE_KEY']
PUBNUB_SECRET_KEY = os.environ['PUBNUB_SECRET_KEY']

CHANNEL = "Lobbdawg Awesome Channel"

if __name__ == "__main__":
    pubnub = Pubnub(publish_key=PUBNUB_PUBLISH_KEY,
                    subscribe_key=PUBNUB_SUBSCRIBE_KEY,
                    secret_key=PUBNUB_SECRET_KEY,
                    cipher_key='',
                    ssl_on=False
                    )

    pubnub.publish(CHANNEL, "Hello world")

Rather than worrying about IP addresses or sockets, you can just subscribe/unsubscribe to channels and publish messages to that channel.

And that’s it!

The End

  • cvconover

    Scott,

    Thanks for putting this tutorial together. I just wanted to comment on a change so that others don’t spin their wheels on this.

    import Pubnub from Pubnub

    should now be

    import pubnub from Pubnub

    See our Python docs page for more details:
    http://www.pubnub.com/docs/python/pubnub-python-sdk

    Cheers
    Craig Conover
    Manager of PubNub Customer Support