Skip to content

Commit

Permalink
added better error handeling for PubNub Python API.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenlb committed Mar 24, 2012
1 parent 21679be commit dfd5944
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 71 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -18,7 +18,8 @@ The current version number for communication with PubNub Cloud is `3.1`.

- Twitter: http://twitter.com/PubNub
- Website: http://www.pubnub.com
- Videos: http://www.youtube.com/playlist?p=PLF0BA2B6DAAF4FBBF
- YouTube: http://www.youtube.com/playlist?p=PLF0BA2B6DAAF4FBBF
- Vimeo: https://vimeo.com/pubnub
- Socket.IO: https://github.com/pubnub/pubnub-api/tree/master/socket.io
- Showcase: http://www.pubnub.com/blog
- Interview: http://techzinglive.com/?p=227
Expand Down
76 changes: 17 additions & 59 deletions python/Pubnub.py
Expand Up @@ -9,10 +9,8 @@
## PubNub 3.0 Real-time Push Cloud API
## -----------------------------------

try:
import json
except ImportError:
import simplejson as json
try: import json
except ImportError: import simplejson as json

import time
import hashlib
Expand Down Expand Up @@ -80,8 +78,7 @@ def publish( self, args ) :
"""
## Fail if bad input.
if not (args['channel'] and args['message']) :
print('Missing Channel or Message')
return False
return [ 0, 'Missing Channel or Message' ]

## Capture User Input
channel = args['channel']
Expand All @@ -99,11 +96,6 @@ def publish( self, args ) :
else :
signature = '0'

## Fail if message too long.
if len(message) > self.limit :
print('Message TOO LONG (' + str(self.limit) + ' LIMIT)')
return [ 0, 'Message Too Long.' ]

## Send Message
return self._request([
'publish',
Expand Down Expand Up @@ -139,14 +131,15 @@ def receive(message) :
})
"""

## Fail if missing channel
if not 'channel' in args :
print('Missing Channel.')
raise Exception('Missing Channel.')
return False

## Fail if missing callback
if not 'callback' in args :
print('Missing Callback.')
raise Exception('Missing Callback.')
return False

## Capture User Input
Expand All @@ -157,7 +150,6 @@ def receive(message) :
while True :

timetoken = 'timetoken' in args and args['timetoken'] or 0

try :
## Wait for Message
response = self._request([
Expand Down Expand Up @@ -185,6 +177,7 @@ def receive(message) :

return True


def history( self, args ) :
"""
#**
Expand All @@ -210,7 +203,7 @@ def history( self, args ) :

## Fail if bad input.
if not channel :
print('Missing Channel')
raise Exception('Missing Channel')
return False

## Get History
Expand All @@ -222,42 +215,6 @@ def history( self, args ) :
str(limit)
]);

def analytics( self, args ) :
"""
#**
#* Analytics
#*
#* Channel Analytics.
#*
#* @return dictionary keyed by datetimes
#*
## Channel Analytics Example
analytics = pubnub.analytics({
'channel' : 'channel-name-here', ## Leave blank for all channels
'limit' : 100, ## aggregation range
'ago' : 0, ## minutes ago to look backward
'duration' : 100 ## minutes offset
})
print(analytics)
"""

## Capture User Input
channel = args.has_key('channel') and args['channel'] or ''
limit = args.has_key('limit') and int(args['limit']) or 100
ago = args.has_key('ago') and int(args['ago']) or 0
duration = args.has_key('duration') and int(args['duration']) or 100
protocol = self.ssl and 'https' or 'http'

return self._request( ['&'.join([
'analytics-channel?sub-key=' + self.subscribe_key,
'pub-key=' + self.publish_key,
'channel=' + ''.join(self._encode([channel])),
'limit=' + str(limit),
'ago=' + str(ago),
'duration=' + str(duration)
])], protocol + '://pubnub-prod.appspot.com', False )

def time(self) :
"""
Expand All @@ -279,13 +236,15 @@ def time(self) :
'0'
])[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 _request( self, request, origin = None, encode = True ) :
## Build URL
url = (origin or self.origin) + '/' + "/".join(
Expand All @@ -294,12 +253,11 @@ def _request( self, request, origin = None, encode = True ) :

## Send Request Expecting JSONP Response
try:
# timeout added in 2.6
usock = urllib2.urlopen( url, None, 200 )
except TypeError:
usock = urllib2.urlopen( url, None )

response = usock.read()
usock.close()
try: usock = urllib2.urlopen( url, None, 200 )
except TypeError: usock = urllib2.urlopen( url, None )
response = usock.read()
usock.close()
return json.loads( response )
except:
return None

return json.loads( response )
11 changes: 0 additions & 11 deletions python/unit-test.py
Expand Up @@ -62,17 +62,6 @@ def test( trial, name ) :
timestamp = pubnub.time()
test( timestamp > 0, 'PubNub Server Time: ' + str(timestamp) )

## -----------------------------------------------------------------------
## Channel Analytics Example
## -----------------------------------------------------------------------
analytics = pubnub.analytics({
'channel' : 'channel-name-here', ## Leave blank for all channels
'limit' : 100, ## aggregation range
'ago' : 0, ## minutes ago to look backward
'duratoin' : 100 ## minutes offset
})
test( analytics.has_key('results'), 'PubNub Channel Analytics' )

## -----------------------------------------------------------------------
## Subscribe Example
## -----------------------------------------------------------------------
Expand Down

0 comments on commit dfd5944

Please sign in to comment.