diff options
| author | Devendra | 2014-06-18 01:02:15 +0530 | 
|---|---|---|
| committer | Devendra | 2014-06-18 01:02:15 +0530 | 
| commit | a1ee7f8bd90b463318bfa75f7ee4f58d458d2a24 (patch) | |
| tree | 9e260902f960f792a93fa25e3b619c42ecb5f4d4 /python-tornado | |
| parent | bfd5c64bdf7ed45f21207cb53c653e7220e39eff (diff) | |
| parent | 083127cde127dd78fc88ffe2b3b82144b2c07038 (diff) | |
| download | pubnub-python-a1ee7f8bd90b463318bfa75f7ee4f58d458d2a24.tar.bz2 | |
Merge branch 'master' into develop
Diffstat (limited to 'python-tornado')
21 files changed, 1354 insertions, 1310 deletions
| diff --git a/python-tornado/Makefile b/python-tornado/Makefile deleted file mode 100644 index bf23137..0000000 --- a/python-tornado/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -include ../Makefile.inc - - -.PHONY: all -all: build - -.PHONY: build -build: -	cat ../common/LICENSE_HEADER > ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubCrypto.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubBase.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ../common/PubnubCoreAsync.py >> ./Pubnub.py -	echo "\n" >> ./Pubnub.py -	cat ./unassembled/Platform.py >> ./Pubnub.py -	find -name "Pubnub*py" | xargs sed -i "s/PubNub\ [0-9]\.[0-9]\.[0-9]/PubNub\ $(VERSION)/g" - - -.PHONY: clean -clean: -	rm -f Pubnub.py* - -.PHONY: test -test: -	python tests/unit-tests.py - diff --git a/python-tornado/Pubnub.py b/python-tornado/Pubnub.py deleted file mode 100644 index 89c0d97..0000000 --- a/python-tornado/Pubnub.py +++ /dev/null @@ -1,709 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.3.5 Real-time Push Cloud API -## ----------------------------------- - - -from Crypto.Cipher import AES -from Crypto.Hash import MD5 -from base64 import encodestring, decodestring  -import hashlib -import hmac - -class PubnubCrypto() : -    """ -    #** -    #* PubnubCrypto -    #* -    #** - -    ## Initiate Class -    pc = PubnubCrypto - -    """ -    -    def pad( self, msg, block_size=16 ): -        """ -        #** -        #* pad -        #* -        #* pad the text to be encrypted -        #* appends a padding character to the end of the String -        #* until the string has block_size length -        #* @return msg with padding. -        #** -        """ -        padding = block_size - (len(msg) % block_size) -        return msg + chr(padding)*padding -        -    def depad( self, msg ): -        """ -        #** -        #* depad -        #* -        #* depad the decryptet message" -        #* @return msg without padding. -        #** -        """ -        return msg[0:-ord(msg[-1])] - -    def getSecret( self, key ): -        """ -        #** -        #* getSecret -        #* -        #* hases the key to MD5 -        #* @return key in MD5 format -        #** -        """ -        return hashlib.sha256(key).hexdigest() - -    def encrypt( self, key, msg ): -        """ -        #** -        #* encrypt -        #* -        #* encrypts the message -        #* @return message in encrypted format -        #** -        """ -        secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        enc = encodestring(cipher.encrypt(self.pad(msg))) -        return enc -    def decrypt( self, key, msg ): -        """ -        #** -        #* decrypt -        #* -        #* decrypts the message -        #* @return message in decryped format -        #** -        """ -        secret = self.getSecret(key) -        Initial16bytes='0123456789012345' -        cipher = AES.new(secret[0:32],AES.MODE_CBC,Initial16bytes) -        return self.depad((cipher.decrypt(decodestring(msg)))) - - -try: import json -except ImportError: import simplejson as json - -import time -import hashlib -import urllib2 -import uuid  - -class PubnubBase(object): -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        UUID = None -    ) : -        """ -        #** -        #* Pubnub -        #* -        #* Init the Pubnub Client API -        #* -        #* @param string publish_key required key to send messages. -        #* @param string subscribe_key required key to receive messages. -        #* @param string secret_key optional key to sign messages. -        #* @param boolean ssl required for 2048 bit encrypted messages. -        #* @param string origin PUBNUB Server Origin. -        #* @param string pres_uuid optional identifier for presence (auto-generated if not supplied) -        #** - -        ## Initiat Class -        pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - -        """ -        self.origin        = origin -        self.limit         = 1800 -        self.publish_key   = publish_key -        self.subscribe_key = subscribe_key -        self.secret_key    = secret_key -        self.cipher_key    = cipher_key -        self.ssl           = ssl_on -        self.pc            = PubnubCrypto() - -        if self.ssl : -            self.origin = 'https://' + self.origin -        else : -            self.origin = 'http://'  + self.origin -         -        self.uuid = UUID or str(uuid.uuid4()) -         -        if not isinstance(self.uuid, basestring): -            raise AttributeError("pres_uuid must be a string") - -    def sign(self, channel, message): -        ## Sign Message -        if self.secret_key: -            signature = hashlib.md5('/'.join([ -                self.publish_key, -                self.subscribe_key, -                self.secret_key, -                channel, -                message -            ])).hexdigest() -        else: -            signature = '0' -        return signature - -    def encrypt(self, message): -        if self.cipher_key: -            message = json.dumps(self.pc.encrypt(self.cipher_key, json.dumps(message)).replace('\n','')) -        else : -            message = json.dumps(message) - -        return message; - -    def decrypt(self, message): -        if self.cipher_key: -            message = self.pc.decrypt(self.cipher_key, message) - -        return message - - -    def publish( self, args ) : -        """ -        #** -        #* Publish -        #* -        #* Send a message to a channel. -        #* -        #* @param array args with channel and message. -        #* @return array success information. -        #** - -        ## Publish Example -        info = pubnub.publish({ -            'channel' : 'hello_world', -            'message' : { -                'some_text' : 'Hello my World' -            } -        }) -        print(info) - -        """ -        ## Fail if bad input. -        if not (args['channel'] and args['message']) : -            return [ 0, 'Missing Channel or Message' ] - -        ## Capture User Input -        channel = str(args['channel']) - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  - -        #message = json.dumps(args['message'], separators=(',',':')) -        message = self.encrypt(args['message']) - -        signature = self.sign(channel, message) - -        ## Send Message -        return self._request({"urlcomponents": [ -            'publish', -            self.publish_key, -            self.subscribe_key, -            signature, -            channel, -            '0', -            message -        ]}, callback) -     -    def presence( self, args ) : -        """ -        #** -        #* presence -        #* -        #* This is BLOCKING. -        #* Listen for presence events on a channel. -        #* -        #* @param array args with channel and callback. -        #* @return false on fail, array on success. -        #** - -        ## Presence Example -        def pres_event(message) : -            print(message) -            return True - -        pubnub.presence({ -            'channel'  : 'hello_world', -            'callback' : receive  -        }) -        """ - -        ## Fail if missing channel -        if not 'channel' in args : -            raise Exception('Missing Channel.') -            return False - -        ## Fail if missing callback -        if not 'callback' in args : -            raise Exception('Missing Callback.') -            return False - -        ## Capture User Input -        channel   = str(args['channel']) -        callback  = args['callback'] -        subscribe_key = args.get('subscribe_key') or self.subscribe_key -         -        return self.subscribe({'channel': channel+'-pnpres', 'subscribe_key':subscribe_key, 'callback': callback}) -     -     -    def here_now( self, args ) : -        """ -        #** -        #* Here Now -        #* -        #* Load current occupancy from a channel. -        #* -        #* @param array args with 'channel'. -        #* @return mixed false on fail, array on success. -        #* - -        ## Presence Example -        here_now = pubnub.here_now({ -            'channel' : 'hello_world', -        }) -        print(here_now['occupancy']) -        print(here_now['uuids']) - -        """ -        channel = str(args['channel']) - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None -         -        ## Fail if bad input. -        if not channel : -            raise Exception('Missing Channel') -            return False -         -        ## Get Presence Here Now -        return self._request({"urlcomponents": [ -            'v2','presence', -            'sub_key', self.subscribe_key, -            'channel', channel -        ]}, callback); -         -         -    def history( self, args ) : -        """ -        #** -        #* History -        #* -        #* Load history from a channel. -        #* -        #* @param array args with 'channel' and 'limit'. -        #* @return mixed false on fail, array on success. -        #* - -        ## History Example -        history = pubnub.history({ -            'channel' : 'hello_world', -            'limit'   : 1 -        }) -        print(history) - -        """ -        ## Capture User Input -        limit   = args.has_key('limit') and int(args['limit']) or 10 -        channel = str(args['channel']) - -        ## Fail if bad input. -        if not channel : -            raise Exception('Missing Channel') -            return False - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None - -        ## Get History -        return self._request({ "urlcomponents" : [ -            'history', -            self.subscribe_key, -            channel, -            '0', -            str(limit) -        ] }, callback); - -    def detailedHistory(self, args) : -        """ -        #** -        #* Detailed History -        #* -        #* Load Detailed history from a channel. -        #* -        #* @param array args with 'channel', optional: 'start', 'end', 'reverse', 'count' -        #* @return mixed false on fail, array on success. -        #* - -        ## History Example -        history = pubnub.detailedHistory({ -            'channel' : 'hello_world', -            'count'   : 5 -        }) -        print(history) - -        """ -        ## Capture User Input -        channel = str(args['channel']) - -        params = dict()  -        count = 100     -         -        if args.has_key('count'): -            count = int(args['count']) - -        params['count'] = str(count)     -         -        if args.has_key('reverse'): -            params['reverse'] = str(args['reverse']).lower() - -        if args.has_key('start'): -            params['start'] = str(args['start']) - -        if args.has_key('end'): -            params['end'] = str(args['end']) - -        ## Fail if bad input. -        if not channel : -            raise Exception('Missing Channel') -            return False - -        ## Capture Callback -        if args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  - -        ## Get History -        return self._request({ 'urlcomponents' : [ -            'v2', -            'history', -            'sub-key', -            self.subscribe_key, -            'channel', -            channel, -        ],'urlparams' : params }, callback=callback); - -    def time(self, args = None) : -        """ -        #** -        #* Time -        #* -        #* Timestamp from PubNub Cloud. -        #* -        #* @return int timestamp. -        #* - -        ## PubNub Server Time Example -        timestamp = pubnub.time() -        print(timestamp) - -        """ -        ## Capture Callback -        if args and args.has_key('callback') : -            callback = args['callback'] -        else : -            callback = None  -        time = self._request({'urlcomponents' : [ -            'time', -            '0' -        ]}, callback) -        if time != None: -            return time[0] - - -    def _encode( self, request ) : -        return [ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request] -     -    def getUrl(self,request): -        ## Build URL -        url = self.origin + '/' + "/".join([ -            "".join([ ' ~`!@#$%^&*()+=[]\\{}|;\':",./<>?'.find(ch) > -1 and -                hex(ord(ch)).replace( '0x', '%' ).upper() or -                ch for ch in list(bit) -            ]) for bit in request["urlcomponents"]]) -        if (request.has_key("urlparams")): -            url = url + '?' + "&".join([ x + "=" + y  for x,y in request["urlparams"].iteritems()]) -        return url - - -try: -    from hashlib import sha256 -    digestmod = sha256 -except ImportError: -    import Crypto.Hash.SHA256 as digestmod -    sha256 = digestmod.new -import hmac - -class PubnubCoreAsync(PubnubBase): - -    def start(self): pass  -    def stop(self):  pass -    def timeout( self, delay, callback ): -        pass - -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com', -        uuid = None -    ) : -        """ -        #** -        #* Pubnub -        #* -        #* Init the Pubnub Client API -        #* -        #* @param string publish_key required key to send messages. -        #* @param string subscribe_key required key to receive messages. -        #* @param string secret_key required key to sign messages. -        #* @param boolean ssl required for 2048 bit encrypted messages. -        #* @param string origin PUBNUB Server Origin. -        #** - -        ## Initiat Class -        pubnub = Pubnub( 'PUBLISH-KEY', 'SUBSCRIBE-KEY', 'SECRET-KEY', False ) - -        """ -        super(PubnubCoreAsync, self).__init__( -            publish_key=publish_key, -            subscribe_key=subscribe_key, -            secret_key=secret_key, -            cipher_key=cipher_key, -            ssl_on=ssl_on, -            origin=origin, -            UUID=uuid -        )         - -        self.subscriptions = {} -        self.timetoken     = 0 -        self.version       = '3.3.4' -        self.accept_encoding = 'gzip' - -    def subscribe( self, args ) : -        """ -        #** -        #* Subscribe -        #* -        #* This is NON-BLOCKING. -        #* Listen for a message on a channel. -        #* -        #* @param array args with channel and message. -        #* @return false on fail, array on success. -        #** - -        ## Subscribe Example -        def receive(message) : -            print(message) -            return True - -        ## On Connect Callback -        def connected() : -            pubnub.publish({ -                'channel' : 'hello_world', -                'message' : { 'some_var' : 'text' } -            }) - -        ## Subscribe -        pubnub.subscribe({ -            'channel'  : 'hello_world', -            'connect'  : connected, -            'callback' : receive -        }) - -        """ -        ## Fail if missing channel -        if not 'channel' in args : -            return 'Missing Channel.' - -        ## Fail if missing callback -        if not 'callback' in args : -            return 'Missing Callback.' - -        ## Capture User Input -        channel   = str(args['channel']) -        callback  = args['callback'] -        connectcb = args['connect'] - -        if 'errorback' in args: -            errorback = args['errorback'] -        else: -            errorback = lambda x: x - -        ## New Channel? -        if not (channel in self.subscriptions) : -            self.subscriptions[channel] = { -                'first'     : False, -                'connected' : False, -            } - -        ## Ensure Single Connection -        if self.subscriptions[channel]['connected'] : -            return "Already Connected" - -        self.subscriptions[channel]['connected'] = 1 -        ## SUBSCRIPTION RECURSION  -        def _subscribe(): -            ## STOP CONNECTION? -            if not self.subscriptions[channel]['connected']: -                return -           -            def sub_callback(response): -                if not self.subscriptions[channel]['first'] : -                    self.subscriptions[channel]['first'] = True -                    connectcb() - -                ## STOP CONNECTION? -                if not self.subscriptions[channel]['connected']: -                    return - - - -                ## PROBLEM? -                if not response: -                    def time_callback(_time): -                        if not _time: -                            self.timeout( 1, _subscribe ) -                            return errorback("Lost Network Connection") -                        else: -                            self.timeout( 1, _subscribe) - -                    ## ENSURE CONNECTED (Call Time Function) -                    return self.time({ 'callback' : time_callback }) - -                self.timetoken = response[1] -                _subscribe() - -                pc = PubnubCrypto() -                out = [] -                for message in response[0]: -                     callback(self.decrypt(message)) - -            ## CONNECT TO PUBNUB SUBSCRIBE SERVERS -            try: -                self._request( { "urlcomponents" : [ -                    'subscribe', -                    self.subscribe_key, -                    channel, -                    '0', -                    str(self.timetoken) -                ], "urlparams" : {"uuid":self.uuid} }, sub_callback ) -            except : -                self.timeout( 1, _subscribe) -                return - -        ## BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES) -        _subscribe() -    def unsubscribe( self, args ): -        channel = str(args['channel']) -        if not (channel in self.subscriptions): -            return False - -        ## DISCONNECT -        self.subscriptions[channel]['connected'] = 0 -        self.subscriptions[channel]['timetoken'] = 0 -        self.subscriptions[channel]['first']     = False - - -import tornado.httpclient - -try: -    from hashlib import sha256 -    digestmod = sha256 -except ImportError: -    import Crypto.Hash.SHA256 as digestmod -    sha256 = digestmod.new - -import hmac -import tornado.ioloop -from tornado.stack_context import ExceptionStackContext - -ioloop = tornado.ioloop.IOLoop.instance() - -class Pubnub(PubnubCoreAsync): - -    def stop(self): ioloop.stop() -    def start(self): ioloop.start() -    def timeout( self, delay, callback): -        ioloop.add_timeout( time.time()+float(delay), callback ) -         -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com' -    ) : -        super(Pubnub, self).__init__( -            publish_key=publish_key, -            subscribe_key=subscribe_key, -            secret_key=secret_key, -            cipher_key=cipher_key, -            ssl_on=ssl_on, -            origin=origin, -        )         -        self.headers = {} -        self.headers['User-Agent'] = 'Python-Tornado' -        self.headers['Accept-Encoding'] = self.accept_encoding -        self.headers['V'] = self.version -        self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) - -    def _request( self, request, callback ) : -        url = self.getUrl(request) -        ## Send Request Expecting JSON Response -        #print self.headers - -        request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, connect_timeout=10, request_timeout=310 ) - -        def responseCallback(response): -            def handle_exc(*args): -                return True -            if response.error is not None: -                with ExceptionStackContext(handle_exc): -                    response.rethrow() -            elif callback: -                callback(eval(response._get_body())) -         -        self.http.fetch( -            request, -            callback=responseCallback, -        ) - diff --git a/python-tornado/README b/python-tornado/README deleted file mode 100644 index d6eeebe..0000000 --- a/python-tornado/README +++ /dev/null @@ -1,108 +0,0 @@ -## --------------------------------------------------- -## -## YOU MUST HAVE A PUBNUB ACCOUNT TO USE THE API. -## http://www.pubnub.com/account -## -## ---------------------------------------------------- - -## ---------------------------------------------------- -## PubNub 3.1 Real-time Cloud Push API - PYTHON TORNADO -## ---------------------------------------------------- -## -## www.pubnub.com - PubNub Real-time Push Service in the Cloud.  -## http://github.com/pubnub/pubnub-api/tree/master/python-tornado/ -## -## PubNub is a Massively Scalable Real-time Service for Web and Mobile Games. -## This is a cloud-based service for broadcasting Real-time messages -## to thousands of web and mobile clients simultaneously. - -## ---------------------------------------------------- -## Third Party Libraries Dependency -## ---------------------------------------------------- -## You must download and install, -## -## 1. pyopenssl -## Download from https://launchpad.net/pyopenssl -## -## 2. pycrypto -## Download from https://github.com/dlitz/pycrypto OR -## from http://code.google.com/p/uploadprj/downloads/detail?name=pycrypto-2.3.win32-py2.7.zip&can=2&q - -## --------------- -## Python Push API -## --------------- -pubnub = Pubnub( -    "demo",  ## PUBLISH_KEY -    "demo",  ## SUBSCRIBE_KEY -    "demo",  ## SECRET_KEY -    "",  ## CIPHER_KEY (Cipher key is Optional) -     False   ## SSL_ON? -) - -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -## VERY IMPORTANT TO ADD THIS LINE AT THE VERY BOTTOM! -## -## tornado.ioloop.IOLoop.instance().start() ## IMPORTANT! -## - -## ----------------------------------------------------------------------- -## Subscribe Example -## ----------------------------------------------------------------------- - -def connected() : -    ## ----------------------------------------------------------------------- -    ## Publish Example -    ## ----------------------------------------------------------------------- -    def publish_complete(info): -        print(info) - -    pubnub.publish({ -        'channel' : "my-tornado-channel", -        'message' : { -            'some_text' : 'Hello World!' -        }, -        'callback' : publish_complete -    }) - -def message_received(message): -    print(message) - -pubnub.subscribe({ -    'channel'  : "my-tornado-channel", -    'connect'  : connected, -    'callback' : message_received -}) - -## ----------------------------------------------------------------------- -## Time Example -## ----------------------------------------------------------------------- -def time_complete(timestamp): -    print(timestamp) - -pubnub.time({ 'callback' : time_complete }) - -## ----------------------------------------------------------------------- -## History Example -## ----------------------------------------------------------------------- -def history_complete(messages): -    print(messages) - -pubnub.history( { -    'channel'  : "my-tornado-channel", -    'limit'    : 10, -    'callback' : history_complete -}) - -## ----------------------------------------------------------------------- -## UUID Example -## ----------------------------------------------------------------------- -uuid = pubnub.uuid() -print "UUID" -print uuid - -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/README.md b/python-tornado/README.md new file mode 100644 index 0000000..53aad32 --- /dev/null +++ b/python-tornado/README.md @@ -0,0 +1,105 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Tornado Client + +## IO Event Loop +Be sure to eventually start the event loop or PubNub won't run! + +``` +pubnub.start() +``` + +#### Import +``` +from Pubnub import PubnubTornado as Pubnub +``` + +#### Init +``` +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) +``` + +#### Publish Example +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) +``` + +#### Subscribe Example +``` +channel = 'hello_world' + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### History Example +``` +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### Here Now Example +``` +def callback(message): +    print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### Presence Example +``` +channel = 'hello_world' + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### Unsubscribe Example +``` +pubnub.unsubscribe(channel='hello_world') +``` + +#### IO Event Loop start +``` +pubnub.start() +``` + +## Contact support@pubnub.com for all questions diff --git a/python-tornado/examples/here-now-example.py b/python-tornado/examples/here-now-example.py deleted file mode 100644 index 85e3432..0000000 --- a/python-tornado/examples/here-now-example.py +++ /dev/null @@ -1,45 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - -import sys -import tornado -sys.path.append('..') -sys.path.append('../../common') -from Pubnub import Pubnub - -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' -subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or '' -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) -crazy  = 'hello_world' - -## ----------------------------------------------------------------------- -## History Example -## ----------------------------------------------------------------------- -def here_now_complete(messages): -    print(messages) -    pubnub.stop() - -pubnub.here_now( { -    'channel'  : crazy, -    'callback' : here_now_complete -}) - -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -pubnub.start() diff --git a/python-tornado/examples/here-now.py b/python-tornado/examples/here-now.py new file mode 100644 index 0000000..5c195f1 --- /dev/null +++ b/python-tornado/examples/here-now.py @@ -0,0 +1,33 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + + +import sys +from Pubnub import PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'hello_world' + + +# Asynchronous usage + +def callback(message): +    print(message) + +pubnub.here_now(channel, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/history-example.py b/python-tornado/examples/history-example.py deleted file mode 100644 index c1619f4..0000000 --- a/python-tornado/examples/history-example.py +++ /dev/null @@ -1,44 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.0 Real-time Push Cloud API -## ----------------------------------- - -import sys -import tornado -from Pubnub import Pubnub - -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' -subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or '' -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key, subscribe_key, secret_key,cipher_key, ssl_on ) -crazy  = 'hello_world' - -## ----------------------------------------------------------------------- -## History Example -## ----------------------------------------------------------------------- -def history_complete(messages): -    print(messages) -    tornado.ioloop.IOLoop.instance().stop() - -pubnub.history( { -   'channel'  : crazy, -   'limit'    : 10, -   'callback' : history_complete -}) - -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/history.py b/python-tornado/examples/history.py new file mode 100644 index 0000000..daf1c6e --- /dev/null +++ b/python-tornado/examples/history.py @@ -0,0 +1,33 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + + +import sys +from Pubnub import PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'a' + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/publish-example.py b/python-tornado/examples/publish-example.py deleted file mode 100644 index b9eaa15..0000000 --- a/python-tornado/examples/publish-example.py +++ /dev/null @@ -1,63 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - -import sys -import tornado -sys.path.append('../') -sys.path.append('../..') -sys.path.append('../../common') -from Pubnub import Pubnub - -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' -subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or 'demo' ##(Cipher key is Optional) -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key,cipher_key=cipher_key, ssl_on=ssl_on ) -#pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) -crazy  = 'hello_world' - -def publish_complete(info): -    print(info) - -## Publish string -pubnub.publish({ -    'channel' : crazy, -    'message' : 'Hello World!', -    'callback' : publish_complete -}) - -## Publish list -li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] -pubnub.publish({ -    'channel' : crazy, -    'message' : li, -    'callback' : publish_complete -}) - -def done_cb(info): -    publish_complete(info) -    tornado.ioloop.IOLoop.instance().stop() - -## Publish Dictionary Object -pubnub.publish({ -    'channel' : crazy, -    'message' : { 'some_key' : 'some_val' }, -    'callback' : done_cb -}) -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/publish.py b/python-tornado/examples/publish.py new file mode 100644 index 0000000..04e88fd --- /dev/null +++ b/python-tornado/examples/publish.py @@ -0,0 +1,34 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + + +import sys +from Pubnub import PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +channel = 'hello_world' +message = 'Hello World !!!' + +# Asynchronous usage + + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) + +pubnub.start() diff --git a/python-tornado/examples/subscribe-example.py b/python-tornado/examples/subscribe-example.py deleted file mode 100644 index dfe8010..0000000 --- a/python-tornado/examples/subscribe-example.py +++ /dev/null @@ -1,74 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - -import sys -import tornado -sys.path.append('../') -sys.path.append('../..') -from Pubnub import Pubnub - -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' -subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or 'demo' ##(Cipher key is Optional) -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key,cipher_key=cipher_key, ssl_on=ssl_on ) -#pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) -crazy  = 'hello_world' - -def connect_cb(): -    print 'Connect' - -def subscribe_result(response): -    print response - -pubnub.subscribe({ -    'channel' : crazy, -    'callback' : subscribe_result, -    'connect' : connect_cb  -}) -## ----------------------------------------------------------------------- -## Publish Example -## ----------------------------------------------------------------------- -''' -def publish_complete(info): -    print(info) - -## Publish string -pubnub.publish({ -    'channel' : crazy, -    'message' : 'Hello World!', -    'callback' : publish_complete -}) - -## Publish list -li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] -pubnub.publish({ -    'channel' : crazy, -    'message' : li, -    'callback' : publish_complete -}) - -## Publish Dictionary Object -pubnub.publish({ -    'channel' : crazy, -    'message' : { 'some_key' : 'some_val' }, -    'callback' : publish_complete -}) -''' -## ----------------------------------------------------------------------- -## IO Event Loop -## ----------------------------------------------------------------------- -tornado.ioloop.IOLoop.instance().start() diff --git a/python-tornado/examples/subscribe.py b/python-tornado/examples/subscribe.py new file mode 100644 index 0000000..72f0fc1 --- /dev/null +++ b/python-tornado/examples/subscribe.py @@ -0,0 +1,51 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + + +import sys +from Pubnub import PubnubTornado as Pubnub + +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, +                secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) + +channel = 'a' + + +# Asynchronous usage +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) + +pubnub.start() diff --git a/python-tornado/examples/uuid-example.py b/python-tornado/examples/uuid-example.py deleted file mode 100644 index f24671b..0000000 --- a/python-tornado/examples/uuid-example.py +++ /dev/null @@ -1,28 +0,0 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  -# coding=utf8 - -## PubNub Real-time Push APIs and Notifications Framework -## Copyright (c) 2010 Stephen Blum -## http://www.pubnub.com/ - -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - -import sys -import tornado -sys.path.append('../') -from Pubnub import Pubnub - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( "", "", "", False ) - -## ----------------------------------------------------------------------- -## UUID Example -## ----------------------------------------------------------------------- -uuid = pubnub.uuid() -print "UUID: " -print uuid - diff --git a/python-tornado/migration.md b/python-tornado/migration.md new file mode 100644 index 0000000..d5fd8f0 --- /dev/null +++ b/python-tornado/migration.md @@ -0,0 +1,205 @@ +## Contact support@pubnub.com for all questions + +#### [PubNub](http://www.pubnub.com) Real-time Data Network +##### Tornado Migration + +#### Import + +``` +# Pre 3.5: +from Pubnub import Pubnub + +# New in 3.5+ +from Pubnub import PubnubTornado as Pubnub + +``` + + +#### Init + +``` + +# Pre 3.5: +pubnub = Pubnub( +    "demo",  ## PUBLISH_KEY +    "demo",  ## SUBSCRIBE_KEY +     False   ## SSL_ON? +) + +# New in 3.5+ +pubnub = Pubnub(publish_key="demo", subscribe_key="demo", ssl_on=False) + +``` + +#### PUBLISH + +``` +channel = 'hello_world' +message = 'Hello World !!!' + +# Pre 3.5: +def callback(messages): +    print(messages) + +pubnub.publish( { +    'channel'  : channel, +    'message'    : message, +    'callback' : callback +}) + +# New in 3.5+ + +def callback(message): +    print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) + +``` + + +#### SUBSCRIBE + +``` + +# Listen for Messages + +channel = 'hello_world' + +# Pre 3.5: +def connected() : +    print('CONNECTED') + +def message_received(message): +    print(message) + +pubnub.subscribe({ +    'channel'  : channel, +    'connect'  : connected, +    'callback' : message_received +}) + +# New in 3.5+ + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + + +def connect(message): +    print("CONNECTED") + + +def reconnect(message): +    print("RECONNECTED") + + +def disconnect(message): +    print("DISCONNECTED") + + +pubnub.subscribe(channel, callback=callback, error=callback, +                 connect=connect, reconnect=reconnect, disconnect=disconnect) +``` + +#### Unsubscribe +Once subscribed, you can easily, gracefully, unsubscribe: + +``` +# Pre 3.5: +pubnub.unsubscribe({ +    'channel' : 'hello_world' +}) + +# New in 3.5+ + +pubnub.unsubscribe(channel='hello_world') +``` + +#### PRESENCE + +``` + +# Pre 3.5: +# + +# New in 3.5+ + +# Listen for Presence Event Messages + +channel = 'hello_world' + +def callback(message, channel): +    print(message) + + +def error(message): +    print("ERROR : " + str(message)) + +pubnub.presence(channel, callback=callback, error=callback) +``` + +#### HERE_NOW + +``` + +channel = 'hello_world' + +# Pre 3.5: +def callback(messages): +    print(messages) + +pubnub.here_now( { +    'channel'  : channel, +    'callback' : callback +}) + + +# New in 3.5+ + +# Get info on who is here right now! + + +def callback(message): +    print(message) + +pubnub.here_now(channel, callback=callback, error=callback) +``` + +#### HISTORY + +``` +channel = 'hello_world' + +# Pre 3.5: +def history_complete(messages): +    print(messages) + +pubnub.history( { +    'channel'  : channel, +    'limit'    : 2, +    'callback' : history_complete +}) + + +# New in 3.5+ + +def callback(message): +    print(message) + +pubnub.history(channel, count=2, callback=callback, error=callback) +``` + +#### IO Event Loop + +``` + +# Pre 3.5: +tornado.ioloop.IOLoop.instance().start() + +# New in 3.5+ +pubnub.start() +``` +## Contact support@pubnub.com for all questions diff --git a/python-tornado/tests/benchmark.py b/python-tornado/tests/benchmark.py index 9d1840e..748fe3b 100644 --- a/python-tornado/tests/benchmark.py +++ b/python-tornado/tests/benchmark.py @@ -12,10 +12,7 @@  import sys  import datetime  import tornado -sys.path.append('./') -sys.path.append('../') -sys.path.append('../common') -from Pubnub import Pubnub +from Pubnub import PubnubTwisted as Pubnub  publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo'  subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' diff --git a/python-tornado/tests/delivery.py b/python-tornado/tests/delivery.py index f3633e6..0181403 100644 --- a/python-tornado/tests/delivery.py +++ b/python-tornado/tests/delivery.py @@ -1,4 +1,4 @@ -## www.pubnub.com - PubNub Real-time push service in the cloud.  +## www.pubnub.com - PubNub Real-time push service in the cloud.  # coding=utf8  ## PubNub Real-time Push APIs and Notifications Framework @@ -14,98 +14,104 @@ import datetime  import time  import math -sys.path.append('../') -from Pubnub import Pubnub +from Pubnub import PubnubTwisted as Pubnub  ## -----------------------------------------------------------------------  ## Configuration  ## ----------------------------------------------------------------------- -publish_key   = len(sys.argv) > 1 and sys.argv[1] or 'demo' +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'  subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' -secret_key    = len(sys.argv) > 3 and sys.argv[3] or 'demo' -cipher_key    = len(sys.argv) > 4 and sys.argv[4] or 'demo' -ssl_on        = len(sys.argv) > 5 and bool(sys.argv[5]) or False -origin        = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False +origin = len(sys.argv) > 6 and sys.argv[6] or 'pubsub.pubnub.com'  ## -----------------------------------------------------------------------  ## Analytics  ## -----------------------------------------------------------------------  analytics = { -    'publishes'            : 0,   ## Total Send Requests -    'received'             : 0,   ## Total Received Messages (Deliveries) -    'queued'               : 0,   ## Total Unreceived Queue (UnDeliveries) -    'successful_publishes' : 0,   ## Confirmed Successful Publish Request -    'failed_publishes'     : 0,   ## Confirmed UNSuccessful Publish Request -    'failed_deliveries'    : 0,   ## (successful_publishes - received) -    'deliverability'       : 0    ## Percentage Delivery +    'publishes': 0,  # Total Send Requests +    'received': 0,  # Total Received Messages (Deliveries) +    'queued': 0,  # Total Unreceived Queue (UnDeliveries) +    'successful_publishes': 0,  # Confirmed Successful Publish Request +    'failed_publishes': 0,  # Confirmed UNSuccessful Publish Request +    'failed_deliveries': 0,  # (successful_publishes - received) +    'deliverability': 0  # Percentage Delivery  }  trips = { -    'last'    : None, -    'current' : None, -    'max'     : 0, -    'avg'     : 0 +    'last': None, +    'current': None, +    'max': 0, +    'avg': 0  }  ## -----------------------------------------------------------------------  ## Initiat Class  ## -----------------------------------------------------------------------  channel = 'deliverability-' + str(time.time()) -pubnub  = Pubnub( +pubnub = Pubnub(      publish_key,      subscribe_key, -    secret_key = secret_key, -    cipher_key = cipher_key, -    ssl_on = ssl_on, -    origin = origin +    secret_key=secret_key, +    cipher_key=cipher_key, +    ssl_on=ssl_on, +    origin=origin  )  ## -----------------------------------------------------------------------  ## BENCHMARK  ## ----------------------------------------------------------------------- -def publish_sent(info = None): -    if info and info[0]: analytics['successful_publishes']   += 1 -    else:                analytics['failed_publishes']       += 1 + + +def publish_sent(info=None): +    if info and info[0]: +        analytics['successful_publishes'] += 1 +    else: +        analytics['failed_publishes'] += 1      analytics['publishes'] += 1 -    analytics['queued']    += 1 +    analytics['queued'] += 1 + +    pubnub.timeout(send, 0.1) -    pubnub.timeout( send, 0.1 )  def send():      if analytics['queued'] > 100:          analytics['queued'] -= 10 -        return pubnub.timeout( send, 10 ) +        return pubnub.timeout(send, 10)      pubnub.publish({ -        'channel'  : channel, -        'callback' : publish_sent, -        'message'  : "1234567890" +        'channel': channel, +        'callback': publish_sent, +        'message': "1234567890"      }) +  def received(message): -    analytics['queued']   -= 1 +    analytics['queued'] -= 1      analytics['received'] += 1      current_trip = trips['current'] = str(datetime.datetime.now())[0:19] -    last_trip    = trips['last']    = str( +    last_trip = trips['last'] = str(          datetime.datetime.now() - datetime.timedelta(seconds=1)      )[0:19]      ## New Trip Span (1 Second) -    if not trips.has_key(current_trip) : +    if current_trip not in trips:          trips[current_trip] = 0          ## Average -        if trips.has_key(last_trip): +        if last_trip in trips:              trips['avg'] = (trips['avg'] + trips[last_trip]) / 2      ## Increment Trip Counter      trips[current_trip] = trips[current_trip] + 1      ## Update Max -    if trips[current_trip] > trips['max'] : +    if trips[current_trip] > trips['max']:          trips['max'] = trips[current_trip] +  def show_status():      ## Update Failed Deliveries      analytics['failed_deliveries'] = \ @@ -114,45 +120,46 @@ def show_status():      ## Update Deliverability      analytics['deliverability'] = ( -        float(analytics['received']) / \ +        float(analytics['received']) /          float(analytics['successful_publishes'] or 1.0)      ) * 100.0      ## Print Display -    print( ( -       "max:%(max)03d/sec  "                  + \ -       "avg:%(avg)03d/sec  "                  + \ -       "pubs:%(publishes)05d  "               + \ -       "received:%(received)05d  "            + \ -       "spub:%(successful_publishes)05d  "    + \ -       "fpub:%(failed_publishes)05d  "        + \ -       "failed:%(failed_deliveries)05d  "     + \ -       "queued:%(queued)03d  "                + \ -       "delivery:%(deliverability)03f%%  "    + \ -       "" -    ) % { -        'max'                  : trips['max'], -        'avg'                  : trips['avg'], -        'publishes'            : analytics['publishes'], -        'received'             : analytics['received'], -        'successful_publishes' : analytics['successful_publishes'], -        'failed_publishes'     : analytics['failed_publishes'], -        'failed_deliveries'    : analytics['failed_deliveries'], -        'publishes'            : analytics['publishes'], -        'deliverability'       : analytics['deliverability'], -        'queued'               : analytics['queued'] -    } ) -    pubnub.timeout( show_status, 1 ) +    print(( +          "max:%(max)03d/sec  " + +          "avg:%(avg)03d/sec  " + +          "pubs:%(publishes)05d  " + +          "received:%(received)05d  " + +          "spub:%(successful_publishes)05d  " + +          "fpub:%(failed_publishes)05d  " + +          "failed:%(failed_deliveries)05d  " + +          "queued:%(queued)03d  " + +          "delivery:%(deliverability)03f%%  " + +          "" +          ) % { +          'max': trips['max'], +          'avg': trips['avg'], +          'publishes': analytics['publishes'], +          'received': analytics['received'], +          'successful_publishes': analytics['successful_publishes'], +          'failed_publishes': analytics['failed_publishes'], +          'failed_deliveries': analytics['failed_deliveries'], +          'publishes': analytics['publishes'], +          'deliverability': analytics['deliverability'], +          'queued': analytics['queued'] +          }) +    pubnub.timeout(show_status, 1) +  def connected():      show_status() -    pubnub.timeout( send, 1 ) +    pubnub.timeout(send, 1) -print( "Connected: %s\n" % origin ) +print("Connected: %s\n" % origin)  pubnub.subscribe({ -    'channel'  : channel, -    'connect'  : connected, -    'callback' : received +    'channel': channel, +    'connect': connected, +    'callback': received  })  ## ----------------------------------------------------------------------- diff --git a/python-tornado/tests/subscribe-test.py b/python-tornado/tests/subscribe-test.py new file mode 100755 index 0000000..bcbbc7e --- /dev/null +++ b/python-tornado/tests/subscribe-test.py @@ -0,0 +1,154 @@ +## www.pubnub.com - PubNub Real-time push service in the cloud. +# coding=utf8 + +## PubNub Real-time Push APIs and Notifications Framework +## Copyright (c) 2010 Stephen Blum +## http://www.pubnub.com/ + +## ----------------------------------- +## PubNub 3.1 Real-time Push Cloud API +## ----------------------------------- + +import sys +import datetime +from Pubnub import PubnubTwisted as Pubnub +from functools import partial +from threading import current_thread +import threading +publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' +subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len(sys.argv) > 4 and sys.argv[4] or None +ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False + +## ----------------------------------------------------------------------- +## Initiate Pubnub State +## ----------------------------------------------------------------------- +#pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) +pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) +crazy = 'hello_world' + +current = -1 + +errors = 0 +received = 0 + +## ----------------------------------------------------------------------- +## Subscribe Example +## ----------------------------------------------------------------------- + + +def message_received(message): +    print(message) + + +def check_received(message): +    global current +    global errors +    global received +    print(message) +    print(current) +    if message <= current: +        print('ERROR') +        #sys.exit() +        errors += 1 +    else: +        received += 1 +    print('active thread count : ' + str(threading.activeCount())) +    print('errors = ' + str(errors)) +    print(current_thread().getName() + ' , ' + 'received = ' + str(received)) + +    if received != message: +        print('********** MISSED **************** ' + str(message - received)) +    current = message + + +def connected_test(ch): +    print('Connected ' + ch) + + +def connected(ch): +    pass + + +''' +pubnub.subscribe({ +    'channel'  : 'abcd1', +    'connect'  : connected, +    'callback' : message_received +}) +''' + + +def cb1(): +    pubnub.subscribe({ +        'channel': 'efgh1', +        'connect': connected, +        'callback': message_received +    }) + + +def cb2(): +    pubnub.subscribe({ +        'channel': 'dsm-test', +        'connect': connected_test, +        'callback': check_received +    }) + + +def cb3(): +    pubnub.unsubscribe({'channel': 'efgh1'}) + + +def cb4(): +    pubnub.unsubscribe({'channel': 'abcd1'}) + + +def subscribe(channel): +    pubnub.subscribe({ +        'channel': channel, +        'connect': connected, +        'callback': message_received +    }) + + +pubnub.timeout(15, cb1) + +pubnub.timeout(30, cb2) + + +pubnub.timeout(45, cb3) + +pubnub.timeout(60, cb4) + +#''' +for x in range(1, 1000): +    #print x +    def y(t): +        subscribe('channel-' + str(t)) + +    def z(t): +        pubnub.unsubscribe({'channel': 'channel-' + str(t)}) + +    pubnub.timeout(x + 5, partial(y, x)) +    pubnub.timeout(x + 25, partial(z, x)) +    x += 10 +#''' + +''' +for x in range(1,1000): +    def cb(r): print r , ' : ', threading.activeCount() +    def y(t): +        pubnub.publish({ +            'message' : t, +            'callback' : cb, +            'channel' : 'dsm-test' +        }) + + +    pubnub.timeout(x + 1, partial(y,x)) +    x += 1 +''' + + +pubnub.start() diff --git a/python-tornado/tests/test_grant_async.py b/python-tornado/tests/test_grant_async.py new file mode 100644 index 0000000..b51b275 --- /dev/null +++ b/python-tornado/tests/test_grant_async.py @@ -0,0 +1,359 @@ + + +from Pubnub import PubnubTornado as Pubnub +import time + +pubnub = Pubnub("demo","demo") +pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a",  +	"sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") + + + +# Grant permission read true, write true, on channel ( Async Mode ) +def test_1(): + +	def _callback(resp, ch= None): +		assert resp == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 1, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1}  +								} + +	def _error(response): +		assert False + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1, callback=_callback, error=_error) +							 + +# Grant permission read false, write false, on channel ( Async Mode ) +def test_2(): +	 +	def _callback(resp, ch=None): +		assert resp == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + +	def _error(response): +		assert False + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read True, write false, on channel ( Async Mode ) +def test_3(): + +	def _callback(resp, ch=None): +		assert resp == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 1, u'w': 0}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + +	def _error(response): +		assert False + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=False, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ) +def test_4(): + +	def _callback(resp, ch=None): +		assert resp == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 1} +								} + +	def _error(response): +		assert False + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=1, callback=_callback, error=_error) + + +# Grant permission read False, write True, on channel ( Async Mode ), TTL 10 +def test_5(): + +	def _callback(resp,ch=None): +		assert resp == { +									'message': u'Success', +									'payload': {u'auths': {u'abcd': {u'r': 0, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'user', u'channel': u'abcd', u'ttl': 10} +								} + + +	def _error(response): +		assert False + +	pubnub_pam.grant(channel="abcd", auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) + + +# Grant permission read False, write True, without channel ( Async Mode ), TTL 10 +def test_6(): +	def _callback(resp, ch=None): +		assert resp == { +										'message': u'Success', +										'payload': { u'r': 0, u'w': 1, +										u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +										u'level': u'subkey', u'ttl': 10} +									} + +	def _error(response): +		assert False + +	pubnub_pam.grant(auth_key="abcd", read=False, write=True, ttl=10, callback=_callback, error=_error) + + + +# Grant permission read False, write False, without channel ( Async Mode ) +def test_7(): + +	def _callback(resp, ch=None): +		assert resp == { +										'message': u'Success', +										'payload': { u'r': 0, u'w': 0, +										u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +										u'level': u'subkey', u'ttl': 1} +									} + +	def _error(response): +		resp['response'] = response + +	pubnub_pam.grant(auth_key="abcd", read=False, write=False, callback=_callback, error=_error) + + +# Complete flow , try publish on forbidden channel, grant permission to subkey and try again. ( Sync Mode) + +def test_8(): +	channel = "test_8-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +		def _cb2(resp, ch=None): +			assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +			def _cb3(resp, ch=None): +				assert resp[0] == 1 +			def _err3(resp): +				assert False + +			pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +		def _err2(resp): +			assert False + + +		pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) + + +# Complete flow , try publish on forbidden channel, grant permission to authkey and try again.  +# then revoke and try again +def test_9(): +	channel = "test_9-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +		def _cb2(resp, ch=None): +			assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 1, u'w': 1}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 10} +							} +			def _cb3(resp, ch=None): +				assert resp[0] == 1 +				def _cb4(resp, ch=None): +					assert resp == 		{ +								'message': u'Success', +								'payload': {u'auths': {auth_key : {u'r': 0, u'w': 0}}, +								u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +								u'level': u'user', u'channel': channel, u'ttl': 1} +							} + +					def _cb5(resp, ch=None): +						assert False +					def _err5(resp): +						assert resp['message'] == 'Forbidden' +						assert resp['payload'] == {u'channels': [channel]} + +					pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +				def _err4(resp): +					assert False +				pubnub_pam.revoke(channel=channel, auth_key=auth_key, callback=_cb4, error=_err4) +			def _err3(resp): +				assert False + +			pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +		def _err2(resp): +			assert False + + +		pubnub_pam.grant(channel=channel, read=True, write=True, auth_key=auth_key, ttl=10, callback=_cb2, error=_err2) + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) + + +# Complete flow , try publish on forbidden channel, grant permission channel level for subkey and try again. +# then revoke and try again +def test_10(): +	channel = "test_10-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +		def _cb2(resp, ch=None): +			assert resp == 		{ +									'message': u'Success', +									'payload': { u'channels': {channel: {u'r': 1, u'w': 1}}, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'channel', u'ttl': 10} +								} +			def _cb3(resp, ch=None): +				assert resp[0] == 1 +				def _cb4(resp, ch=None): +					assert resp == 		{ +												'message': u'Success', +												'payload': { u'channels': {channel : {u'r': 0, u'w': 0}}, +												u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +												u'level': u'channel', u'ttl': 1} +											} + +					def _cb5(resp, ch=None): +						assert False +					def _err5(resp): +						assert resp['message'] == 'Forbidden' +						assert resp['payload'] == {u'channels': [channel]} + +					pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +				def _err4(resp): +					assert False +				pubnub_pam.revoke(channel=channel, callback=_cb4, error=_err4) +			def _err3(resp): +				assert False + +			pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +		def _err2(resp): +			assert False + + +		pubnub_pam.grant(channel=channel, read=True, write=True, ttl=10, callback=_cb2, error=_err2) + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) + + + + + + +# Complete flow , try publish on forbidden channel, grant permission subkey level for subkey and try again. +# then revoke and try again +def test_11(): +	channel = "test_11-" + str(time.time()) +	message = "Hello World" +	auth_key = "auth-" + channel +	pubnub_pam.set_auth_key(auth_key) + +	def _cb1(resp, ch=None): +		assert False +	def _err1(resp): +		assert resp['message'] == 'Forbidden' +		assert resp['payload'] == {u'channels': [channel]} +		def _cb2(resp, ch=None): +			assert resp == 		{ +									'message': u'Success', +									'payload': { u'r': 1, u'w': 1, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 10} +								} +			def _cb3(resp, ch=None): +				assert resp[0] == 1 +				def _cb4(resp, ch=None): +					assert resp == 		{ +									'message': u'Success', +									'payload': {u'r': 0, u'w': 0, +									u'subscribe_key': u'sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe', +									u'level': u'subkey', u'ttl': 1} +								} + +					def _cb5(resp, ch=None): +						assert False +					def _err5(resp): +						assert resp['message'] == 'Forbidden' +						assert resp['payload'] == {u'channels': [channel]} + +					pubnub_pam.publish(channel=channel,message=message, callback=_cb5, error=_err5) +				def _err4(resp): +					assert False +				pubnub_pam.revoke(callback=_cb4, error=_err4) +			def _err3(resp): +				assert False + +			pubnub_pam.publish(channel=channel,message=message, callback=_cb3, error=_err3) +		def _err2(resp): +			assert False + + +		pubnub_pam.grant(read=True, write=True, ttl=10, callback=_cb2, error=_err2) + +	pubnub_pam.publish(channel=channel,message=message, callback=_cb1, error=_err1) + + +x = 5 +def run_test(t): +	global x +	x += 5 +	i = (x / 5) - 1 +	def _print(): +		print('Running test ' + str(i)) +	pubnub.timeout(x, _print) +	pubnub.timeout(x + 1,t) + +def stop(): +	pubnub.stop() + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + + +pubnub_pam.start() + + diff --git a/python-tornado/tests/test_publish_async.py b/python-tornado/tests/test_publish_async.py new file mode 100644 index 0000000..391297d --- /dev/null +++ b/python-tornado/tests/test_publish_async.py @@ -0,0 +1,304 @@ + + +from Pubnub import PubnubTwisted as Pubnub +import time + +pubnub = Pubnub("demo","demo") +pubnub_enc = Pubnub("demo", "demo", cipher_key="enigma") +pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a",  +	"sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") + + + +# Publish and receive string +def test_1(): + +	channel = "test_1-" + str(time.time()) +	message = "I am a string" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array +def test_2(): + +	channel = "test_2-" + str(time.time()) +	message = [1,2] + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive json object +def test_3(): + +	channel = "test_2-" + str(time.time()) +	message = { "a" : "b" } + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number +def test_4(): + +	channel = "test_2-" + str(time.time()) +	message = 100 + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number string +def test_5(): + +	channel = "test_5-" + str(time.time()) +	message = "100" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub.subscribe(channel, callback=_cb, connect=_connect, error=_error) + + +# Publish and receive string (Encryption enabled) +def test_6(): + +	channel = "test_6-" + str(time.time()) +	message = "I am a string" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array (Encryption enabled) +def test_7(): + +	channel = "test_7-" + str(time.time()) +	message = [1,2] + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive json object (Encryption enabled) +def test_8(): + +	channel = "test_8-" + str(time.time()) +	message = { "a" : "b" } + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number (Encryption enabled) +def test_9(): + +	channel = "test_9-" + str(time.time()) +	message = 100 + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive number string (Encryption enabled) +def test_10(): + +	channel = "test_10-" + str(time.time()) +	message = "100" + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive object string (Encryption enabled) +def test_11(): + +	channel = "test_11-" + str(time.time()) +	message = '{"a" : "b"}' + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +# Publish and receive array string (Encryption enabled) +def test_12(): + +	channel = "test_12-" + str(time.time()) +	message = '[1,2]' + +	def _cb(resp, ch=None): +		assert resp == message +		pubnub_enc.unsubscribe(channel) + +	def _connect(resp): +		def _cb1(resp,ch=None): +			assert resp[0] == 1 +		def _err1(resp): +			assert False +		pubnub_enc.publish(channel,message, callback=_cb1, error=_err1) + +	def _error(resp): +		assert False + +	pubnub_enc.subscribe(channel, callback=_cb, connect=_connect, error=_error) + +x = 5 +def run_test(t): +	global x +	x += 5 +	i = (x / 5) - 1 +	def _print(): +		print('Running test ' + str(i)) +	pubnub.timeout(x, _print) +	pubnub.timeout(x + 1,t) + +def stop(): +	pubnub.stop() + +run_test(test_1) +run_test(test_2) +run_test(test_3) +run_test(test_4) +run_test(test_5) +run_test(test_6) +run_test(test_7) +run_test(test_8) +run_test(test_9) +run_test(test_10) +run_test(test_11) +run_test(stop) + +pubnub_enc.start() diff --git a/python-tornado/tests/unit-tests.py b/python-tornado/tests/unit-tests.py deleted file mode 100644 index fdaa194..0000000 --- a/python-tornado/tests/unit-tests.py +++ /dev/null @@ -1,73 +0,0 @@ - -import sys - -sys.path.append('../../common') -sys.path.append('..') -sys.path.append('../common') -sys.path.append('.') - -from PubnubUnitTest import Suite -from Pubnub import Pubnub - -pubnub = Pubnub("demo","demo") - -tests_count = 1 + 2 -test_suite = Suite(pubnub,tests_count) - -tests = [] - - -def test_publish(): -	name = "Publish Test" -	def success(r): -		test_suite.test(r[0] == 1, name) - -	def fail(e): -		test_suite.test(False, msg , e) - - -	pubnub.publish({ -		'channel' : 'hello', -		'message' : 'hi', -		'callback' : success, -		'error' : fail -	}) -tests.append(test_publish) - - -def test_subscribe_publish(): -	channel = "hello" -	name = "Subscribe Publish Test" -	publish_msg = "This is Pubnub Python-Twisted" -	def connect(): -		def success(r): -			test_suite.test(r[0] == 1, name, "publish success") - -		def fail(e): -			test_suite.test(False, name , "Publish Failed", e) - -		pubnub.publish({ -			'channel' : channel, -			'message' : publish_msg, -			'callback' : success, -			'error' : fail -		}) - -	def callback(r): -		test_suite.test(r == publish_msg, name, "message received") - -	pubnub.subscribe({ -		'channel' : channel, -		'callback' : callback, -		'connect' : connect -	}) -tests.append(test_subscribe_publish) - - - - - -for t in tests: -	t() - -pubnub.start() diff --git a/python-tornado/unassembled/Platform.py b/python-tornado/unassembled/Platform.py deleted file mode 100644 index 62d3a26..0000000 --- a/python-tornado/unassembled/Platform.py +++ /dev/null @@ -1,66 +0,0 @@ -import tornado.httpclient - -try: -    from hashlib import sha256 -    digestmod = sha256 -except ImportError: -    import Crypto.Hash.SHA256 as digestmod -    sha256 = digestmod.new - -import hmac -import tornado.ioloop -from tornado.stack_context import ExceptionStackContext - -ioloop = tornado.ioloop.IOLoop.instance() - -class Pubnub(PubnubCoreAsync): - -    def stop(self): ioloop.stop() -    def start(self): ioloop.start() -    def timeout( self, delay, callback): -        ioloop.add_timeout( time.time()+float(delay), callback ) -         -    def __init__( -        self, -        publish_key, -        subscribe_key, -        secret_key = False, -        cipher_key = False, -        ssl_on = False, -        origin = 'pubsub.pubnub.com' -    ) : -        super(Pubnub, self).__init__( -            publish_key=publish_key, -            subscribe_key=subscribe_key, -            secret_key=secret_key, -            cipher_key=cipher_key, -            ssl_on=ssl_on, -            origin=origin, -        )         -        self.headers = {} -        self.headers['User-Agent'] = 'Python-Tornado' -        self.headers['Accept-Encoding'] = self.accept_encoding -        self.headers['V'] = self.version -        self.http = tornado.httpclient.AsyncHTTPClient(max_clients=1000) - -    def _request( self, request, callback ) : -        url = self.getUrl(request) -        ## Send Request Expecting JSON Response -        #print self.headers - -        request = tornado.httpclient.HTTPRequest( url, 'GET', self.headers, connect_timeout=10, request_timeout=310 ) - -        def responseCallback(response): -            def handle_exc(*args): -                return True -            if response.error is not None: -                with ExceptionStackContext(handle_exc): -                    response.rethrow() -            elif callback: -                callback(eval(response._get_body())) -         -        self.http.fetch( -            request, -            callback=responseCallback, -        ) - | 
