From 80edcffbfe140a6d19c65deca24e1ba1c0f49b99 Mon Sep 17 00:00:00 2001 From: Devendra Date: Mon, 24 Mar 2014 19:17:48 +0530 Subject: support for python3 --- python/examples/here-now-example.py | 4 ++-- python/examples/history-example.py | 1 + python/examples/publish-example.py | 3 +++ python/examples/subscribe-example.py | 5 +++-- 4 files changed, 9 insertions(+), 4 deletions(-) (limited to 'python/examples') diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py index d2ca9bd..b9f0b02 100644 --- a/python/examples/here-now-example.py +++ b/python/examples/here-now-example.py @@ -11,7 +11,7 @@ import sys sys.path.append('../') -from twisted.internet import reactor +sys.path.append('./') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' @@ -28,7 +28,7 @@ pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key, crazy = 'hello_world' def print_cb(message): - print message + print(message) pubnub.here_now( { 'channel' : crazy, diff --git a/python/examples/history-example.py b/python/examples/history-example.py index c7c9547..bf78c7d 100755 --- a/python/examples/history-example.py +++ b/python/examples/history-example.py @@ -1,5 +1,6 @@ import sys sys.path.append('../') +sys.path.append('./') from Pubnub import Pubnub ## Initiat Class diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index c97034b..55f19ea 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -1,3 +1,6 @@ +import sys +sys.path.append('.') +sys.path.append('..') from Pubnub import Pubnub ## Initiate Class diff --git a/python/examples/subscribe-example.py b/python/examples/subscribe-example.py index 14a43d9..a67a08f 100755 --- a/python/examples/subscribe-example.py +++ b/python/examples/subscribe-example.py @@ -1,5 +1,6 @@ import sys -sys.path.append('../') +sys.path.append('..') +sys.path.append('.') import threading import time import random @@ -59,7 +60,7 @@ publish() print("waiting for subscribes and presence") pres_thread.join() -print pubnub.here_now({'channel':channel}) +print(pubnub.here_now({'channel':channel})) sub_thread.join() -- cgit v1.2.3 From b8d1dd86a0d8c4261d4f3765f3ca227d7b555c84 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 25 Mar 2014 10:50:39 +0530 Subject: fixing encryption, and changing from urllib3 to urllib --- python/examples/publish-example.py | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) (limited to 'python/examples') diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index 55f19ea..31ae198 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -4,14 +4,40 @@ sys.path.append('..') from Pubnub import Pubnub ## Initiate Class -pubnub = Pubnub( publish_key='demo', subscribe_key='demo', ssl_on=False ) +pubnub = Pubnub( publish_key='demo', subscribe_key='demo', cipher_key='enigma', ssl_on=False ) +#pubnub = Pubnub( publish_key='demo', subscribe_key='demo', ssl_on=False ) ## Publish Example info = pubnub.publish({ - 'channel' : 'hello_world', + 'channel' : 'abcd', 'message' : { - 'some_text' : 'Hello my World' + 'iam' : 'object' } }) print(info) +info = pubnub.publish({ + 'channel' : 'abcd', + 'message' : "hi I am string" +}) +print(info) + +info = pubnub.publish({ + 'channel' : 'abcd', + 'message' : 1234 +}) +print(info) + +info = pubnub.publish({ + 'channel' : 'abcd', + 'message' : "1234" +}) +print(info) + +info = pubnub.publish({ + 'channel' : 'abcd', + 'message' : [ + 'i' , 'am', 'array' + ] +}) +print(info) -- cgit v1.2.3 From 150ae1566d813acbb773839e919db2c0f467931c Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 16 Apr 2014 00:00:40 +0530 Subject: adding code to support async and pam client capabilities with python v2 and v3 --- python/examples/publish-example.py | 87 ++++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 31 deletions(-) (limited to 'python/examples') diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index 31ae198..bb8b199 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -1,43 +1,68 @@ +## 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 -sys.path.append('.') -sys.path.append('..') +from twisted.internet import reactor +sys.path.append('../') +sys.path.append('../../') from Pubnub import Pubnub -## Initiate Class -pubnub = Pubnub( publish_key='demo', subscribe_key='demo', cipher_key='enigma', ssl_on=False ) -#pubnub = Pubnub( publish_key='demo', subscribe_key='demo', ssl_on=False ) +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 '' ##(Cipher key is Optional) +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' + +## ----------------------------------------------------------------------- ## Publish Example -info = pubnub.publish({ - 'channel' : 'abcd', - 'message' : { - 'iam' : 'object' - } -}) -print(info) +## ----------------------------------------------------------------------- +def publish_complete(info): + print(info) -info = pubnub.publish({ - 'channel' : 'abcd', - 'message' : "hi I am string" -}) -print(info) +def publish_error(info): + print('ERROR : ' + str(info)) -info = pubnub.publish({ - 'channel' : 'abcd', - 'message' : 1234 +## Publish string +pubnub.publish({ + 'channel' : crazy, + 'message' : 'Hello World!', + 'callback' : publish_complete, + 'error' : publish_error }) -print(info) -info = pubnub.publish({ - 'channel' : 'abcd', - 'message' : "1234" +## Publish list +li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + +pubnub.publish({ + 'channel' : crazy, + 'message' : li, + 'callback' : publish_complete, + 'error' : publish_error }) -print(info) -info = pubnub.publish({ - 'channel' : 'abcd', - 'message' : [ - 'i' , 'am', 'array' - ] +def done_cb(info): + publish_complete(info) + +pubnub.publish({ + 'channel' : crazy, + 'message' : { 'some_key' : 'some_val' }, + 'callback' : done_cb, + 'error' : publish_error }) -print(info) + + +pubnub.start() -- cgit v1.2.3 From 9dc2555746adf717da0db808f4096af2167a1580 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 17 Apr 2014 00:28:05 +0530 Subject: adding ver 1 of dev console --- python/examples/dev-console.py | 182 +++++++++++++++++++++++++++++++++++++ python/examples/publish-example.py | 5 +- 2 files changed, 185 insertions(+), 2 deletions(-) create mode 100755 python/examples/dev-console.py (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py new file mode 100755 index 0000000..372599a --- /dev/null +++ b/python/examples/dev-console.py @@ -0,0 +1,182 @@ +## 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 +from twisted.internet import reactor +sys.path.append('../') +sys.path.append('../../') +from Pubnub import Pubnub + +from optparse import OptionParser + + +parser = OptionParser() + +parser.add_option("--publish-key", + dest="publish_key", default="demo", + help="Publish Key ( default : 'demo' )") + +parser.add_option("--subscribe-key", + dest="subscribe_key", default="demo", + help="Subscribe Key ( default : 'demo' )") + +parser.add_option("--secret-key", + dest="secret_key", default="demo", + help="Secret Key ( default : 'demo' )") + +parser.add_option("--cipher-key", + dest="cipher_key", default="", + help="Cipher Key") + +parser.add_option("--auth-key", + dest="auth_key", default=None, + help="Auth Key") + +parser.add_option("--origin", + dest="origin", default="pubsub.pubnub.com", + help="Origin ( default: pubsub.pubnub.com )") + +parser.add_option("--ssl-on", + action="store_false", dest="ssl", default=False, + help="SSL") + +(options, args) = parser.parse_args() + +print options + +pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl) + + +class color: + PURPLE = '\033[95m' + CYAN = '\033[96m' + DARKCYAN = '\033[36m' + BLUE = '\033[94m' + GREEN = '\033[92m' + YELLOW = '\033[93m' + RED = '\033[91m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + END = '\033[0m' + + +def print_ok(msg): + print(color.GREEN + str(msg) + color.END) + +def print_error(msg): + print(color.RED + color.BOLD + str(msg) + color.END) + +def get_input(message, t=None): + while True: + try: + command = raw_input(message) + if t is not None: + command = t(command) + else: + command = eval("'" + command + "'") + return command + except ValueError: + print_error("Invalid input : " + command) + + + +def _publish_command_handler(): + + channel = get_input("[PUBLISH] Enter Channel Name ", str) + while True: + message = get_input("[PUBLISH] Enter Message ( QUIT for exit from publish mode ) ") + if message == 'QUIT' or message == 'quit': + return + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + pubnub.publish({ + 'channel' : channel, + 'message' : message, + 'callback' : _callback, + 'error' : _error + }) + + +def _subscribe_command_handler(): + channel = get_input("[SUBSCRIBE] Enter Channel Name ", str) + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + pubnub.subscribe({ + 'channel' : channel, + 'callback' : _callback, + 'error' : _error + }) + +def _grant_command_handler(): + pass + +def _revoke_command_handler(): + pass + +def _audit_command_handler(): + pass + +def _history_command_handler(): + pass + +def _here_now_command_handler(): + pass + + + +import threading + +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + try: + thread._Thread__stop() + except: + print(str(thread.getName()) + ' could not be terminated') + + +commands = [] +commands.append({"command" : "publish", "handler" : _publish_command_handler}) +commands.append({"command" : "subscribe", "handler" : _subscribe_command_handler}) +''' +commands.append({"command" : "here_now", "handler" : _here_now_command_handler}) +commands.append({"command" : "history", "handler" : _history_command_handler}) +commands.append({"command" : "grant", "handler" : _grant_command_handler}) +commands.append({"command" : "revoke", "handler" : _revoke_command_handler}) +commands.append({"command" : "audit", "handler" : _audit_command_handler}) +''' +# last command is quit. add new commands before this line +commands.append({"command" : "QUIT"}) + +def get_help(): + help = "" + for i,v in enumerate(commands): + help += "Enter " + str(i) + " for " + v['command'] + "\n" + return help + + +while True: + command = get_input(color.BLUE + get_help(), int) + + if command == len(commands) - 1: + kill_all_threads() + break + if command >= len(commands): + print_error("Invalid input " + str(command)) + continue + + commands[command]['handler']() + +#pubnub.start() diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index bb8b199..e632aef 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -19,12 +19,13 @@ 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 '' ##(Cipher key is Optional) -ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False +auth_key = len(sys.argv) > 5 and sys.argv[4] or 'abcd' ##(Cipher key is Optional) +ssl_on = len(sys.argv) > 6 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, cipher_key, auth_key, ssl_on ) crazy = 'hello_world' ## ----------------------------------------------------------------------- -- cgit v1.2.3 From 85416ee30a4f54183e2be30f9ef3cc1363f98c4d Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 17 Apr 2014 01:06:51 +0530 Subject: adding more options to dev console --- python/examples/dev-console.py | 65 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 7 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 372599a..33ec39f 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -78,10 +78,16 @@ def get_input(message, t=None): while True: try: command = raw_input(message) + if t is not None and t == bool: + if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]: + return True + else: + return False if t is not None: command = t(command) else: command = eval("'" + command + "'") + return command except ValueError: print_error("Invalid input : " + command) @@ -120,19 +126,65 @@ def _subscribe_command_handler(): }) def _grant_command_handler(): - pass + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + channel = get_input("[GRANT] Enter Channel Name ", str) + auth_key = get_input("[GRANT] Enter Auth Key ", str) + ttl = get_input("[GRANT] Enter ttl ", int) + read = get_input("[GRANT] Read ? ", bool) + write = get_input("[GRANT] Write ? ", bool) + pubnub.grant(channel, auth_key,read,write,ttl, _callback) def _revoke_command_handler(): - pass + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + channel = get_input("[REVOKE] Enter Channel Name ", str) + auth_key = get_input("[REVOKE] Enter Auth Key ", str) + ttl = get_input("[REVOKE] Enter ttl ", int) + + pubnub.revoke(channel, auth_key, ttl, _callback) def _audit_command_handler(): - pass + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + channel = get_input("[AUDIT] Enter Channel Name ", str) + auth_key = get_input("[AUDIT] Enter Auth Key ", str) + pubnub.audit(channel, auth_key, _callback) def _history_command_handler(): - pass + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + channel = get_input("[HISTORY] Enter Channel Name ", str) + count = get_input("[HISTORY] Enter Count ", int) + + pubnub.history({ + 'channel' : channel, + 'count' : count, + 'callback' : _callback, + 'error' : _error + }) + def _here_now_command_handler(): - pass + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + channel = get_input("[HERE NOW] Enter Channel Name ", str) + + pubnub.here_now({ + 'channel' : channel, + 'callback' : _callback, + 'error' : _error + }) @@ -150,13 +202,12 @@ def kill_all_threads(): commands = [] commands.append({"command" : "publish", "handler" : _publish_command_handler}) commands.append({"command" : "subscribe", "handler" : _subscribe_command_handler}) -''' commands.append({"command" : "here_now", "handler" : _here_now_command_handler}) commands.append({"command" : "history", "handler" : _history_command_handler}) commands.append({"command" : "grant", "handler" : _grant_command_handler}) commands.append({"command" : "revoke", "handler" : _revoke_command_handler}) commands.append({"command" : "audit", "handler" : _audit_command_handler}) -''' + # last command is quit. add new commands before this line commands.append({"command" : "QUIT"}) -- cgit v1.2.3 From 5d6a3e1356182663b03d62f9258d38459d49017e Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 18 Apr 2014 01:23:19 +0530 Subject: fixing wrong version detection with python 2.7 --- python/examples/dev-console.py | 1 - 1 file changed, 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 33ec39f..08e08d9 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -10,7 +10,6 @@ ## ----------------------------------- import sys -from twisted.internet import reactor sys.path.append('../') sys.path.append('../../') from Pubnub import Pubnub -- cgit v1.2.3 From 4926061ebebbc060d14feac9c9d6b13880205724 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 22 Apr 2014 23:12:05 +0530 Subject: improvements to dev console --- python/examples/dev-console.py | 49 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 9 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 08e08d9..532edbe 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -47,11 +47,15 @@ parser.add_option("--ssl-on", action="store_false", dest="ssl", default=False, help="SSL") +parser.add_option("--uuid", + dest="uuid", default=None, + help="UUID") + (options, args) = parser.parse_args() print options -pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl) +pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl, options.origin, options.uuid) class color: @@ -67,11 +71,19 @@ class color: END = '\033[0m' -def print_ok(msg): - print(color.GREEN + str(msg) + color.END) +def print_ok(msg, channel=None): + chstr = " [Channel : " + channel + "] " if channel is not None else "" + try: + print(color.GREEN + chstr + str(msg) + color.END) + except: + print(msg) -def print_error(msg): - print(color.RED + color.BOLD + str(msg) + color.END) +def print_error(msg, channel=None): + chstr = " [Channel : " + channel + "] " if channel is not None else "" + try: + print(color.RED + color.BOLD + chstr + str(msg) + color.END) + except: + print(msg) def get_input(message, t=None): while True: @@ -115,15 +127,27 @@ def _publish_command_handler(): def _subscribe_command_handler(): channel = get_input("[SUBSCRIBE] Enter Channel Name ", str) def _callback(r): - print_ok(r) + print_ok(r, channel) def _error(r): - print_error(r) + print_error(r, channel) pubnub.subscribe({ 'channel' : channel, 'callback' : _callback, 'error' : _error }) +def _unsubscribe_command_handler(): + channel = get_input("[UNSUBSCRIBE] Enter Channel Name ", str) + def _callback(r): + print_ok(r) + def _error(r): + print_error(r) + pubnub.unsubscribe({ + 'channel' : channel, + 'callback' : _callback, + 'error' : _error + }) + def _grant_command_handler(): def _callback(r): print_ok(r) @@ -201,6 +225,7 @@ def kill_all_threads(): commands = [] commands.append({"command" : "publish", "handler" : _publish_command_handler}) commands.append({"command" : "subscribe", "handler" : _subscribe_command_handler}) +commands.append({"command" : "unsubscribe", "handler" : _unsubscribe_command_handler}) commands.append({"command" : "here_now", "handler" : _here_now_command_handler}) commands.append({"command" : "history", "handler" : _history_command_handler}) commands.append({"command" : "grant", "handler" : _grant_command_handler}) @@ -212,14 +237,20 @@ commands.append({"command" : "QUIT"}) def get_help(): help = "" + help += "Channels currently subscribed to : " + help += str(pubnub.get_channel_array()) + help += "\n" for i,v in enumerate(commands): help += "Enter " + str(i) + " for " + v['command'] + "\n" return help while True: - command = get_input(color.BLUE + get_help(), int) - + try: + command = get_input(color.BLUE + get_help(), int) + except KeyboardInterrupt: + kill_all_threads() + break if command == len(commands) - 1: kill_all_threads() break -- cgit v1.2.3 From f1ce4ae3179d51e88aca266d107531209d2d98a2 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 22 Apr 2014 23:56:29 +0530 Subject: dev console improvements --- python/examples/dev-console.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 532edbe..52ed910 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -53,7 +53,7 @@ parser.add_option("--uuid", (options, args) = parser.parse_args() -print options +print(options) pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl, options.origin, options.uuid) @@ -88,7 +88,10 @@ def print_error(msg, channel=None): def get_input(message, t=None): while True: try: - command = raw_input(message) + try: + command = raw_input(message) + except NameError: + command = input(message) if t is not None and t == bool: if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]: return True @@ -218,8 +221,11 @@ def kill_all_threads(): if thread.isAlive(): try: thread._Thread__stop() - except: - print(str(thread.getName()) + ' could not be terminated') + except Exception as e: + pass + #print(e) + #thread.exit() + #print(str(thread.getName()) + ' could not be terminated') commands = [] -- cgit v1.2.3 From b2f1e0ed2337b61073a595eaf36afd718a21a3fe Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 02:10:55 +0530 Subject: fixing issues reported by Dara in dev console --- python/examples/dev-console.py | 55 ++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 26 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 52ed910..c4c6bc8 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -70,21 +70,37 @@ class color: UNDERLINE = '\033[4m' END = '\033[0m' +from datetime import datetime def print_ok(msg, channel=None): - chstr = " [Channel : " + channel + "] " if channel is not None else "" + chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END try: - print(color.GREEN + chstr + str(msg) + color.END) - except: + print(chstr + color.GREEN + str(msg) + color.END) + except Exception as e: print(msg) def print_error(msg, channel=None): - chstr = " [Channel : " + channel + "] " if channel is not None else "" + chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END try: - print(color.RED + color.BOLD + chstr + str(msg) + color.END) + print( chstr + color.RED + color.BOLD +str(msg) + color.END) except: print(msg) +import threading + +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + try: + thread._Thread__stop() + except Exception as e: + pass + #print(e) + #thread.exit() + #print(str(thread.getName()) + ' could not be terminated') + def get_input(message, t=None): while True: try: @@ -92,6 +108,8 @@ def get_input(message, t=None): command = raw_input(message) except NameError: command = input(message) + except KeyboardInterrupt: + return None if t is not None and t == bool: if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]: return True @@ -111,9 +129,11 @@ def get_input(message, t=None): def _publish_command_handler(): channel = get_input("[PUBLISH] Enter Channel Name ", str) + if channel is None: + return while True: - message = get_input("[PUBLISH] Enter Message ( QUIT for exit from publish mode ) ") - if message == 'QUIT' or message == 'quit': + message = get_input("[PUBLISH] Enter Message ( QUIT or CTRL-C for exit from publish mode ) ") + if message == 'QUIT' or message == 'quit' or message == None: return def _callback(r): print_ok(r) @@ -214,19 +234,6 @@ def _here_now_command_handler(): -import threading - -def kill_all_threads(): - for thread in threading.enumerate(): - if thread.isAlive(): - try: - thread._Thread__stop() - except Exception as e: - pass - #print(e) - #thread.exit() - #print(str(thread.getName()) + ' could not be terminated') - commands = [] commands.append({"command" : "publish", "handler" : _publish_command_handler}) @@ -252,12 +259,8 @@ def get_help(): while True: - try: - command = get_input(color.BLUE + get_help(), int) - except KeyboardInterrupt: - kill_all_threads() - break - if command == len(commands) - 1: + command = get_input(color.BLUE + get_help(), int) + if command == len(commands) - 1 or command is None: kill_all_threads() break if command >= len(commands): -- cgit v1.2.3 From 69240816755406b26b364f37ca521fdb269581d1 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 02:28:42 +0530 Subject: fixed error on missing channel --- python/examples/dev-console.py | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index c4c6bc8..adade8f 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -110,6 +110,12 @@ def get_input(message, t=None): command = input(message) except KeyboardInterrupt: return None + + command = command.strip() + + if command is None or len(command) == 0: + raise ValueError + if t is not None and t == bool: if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]: return True -- cgit v1.2.3 From fdb46e56fa6794940f9fbe51a2863d58e927e655 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 12:54:16 +0530 Subject: switching to positional arguments --- python/examples/dev-console.py | 34 +++++----------------------------- 1 file changed, 5 insertions(+), 29 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index adade8f..383fa68 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -145,12 +145,7 @@ def _publish_command_handler(): print_ok(r) def _error(r): print_error(r) - pubnub.publish({ - 'channel' : channel, - 'message' : message, - 'callback' : _callback, - 'error' : _error - }) + pubnub.publish(channel, message, _callback, _error) def _subscribe_command_handler(): @@ -159,11 +154,7 @@ def _subscribe_command_handler(): print_ok(r, channel) def _error(r): print_error(r, channel) - pubnub.subscribe({ - 'channel' : channel, - 'callback' : _callback, - 'error' : _error - }) + pubnub.subscribe(channel, _callback, _error) def _unsubscribe_command_handler(): channel = get_input("[UNSUBSCRIBE] Enter Channel Name ", str) @@ -171,11 +162,7 @@ def _unsubscribe_command_handler(): print_ok(r) def _error(r): print_error(r) - pubnub.unsubscribe({ - 'channel' : channel, - 'callback' : _callback, - 'error' : _error - }) + pubnub.unsubscribe(channel) def _grant_command_handler(): def _callback(r): @@ -217,12 +204,7 @@ def _history_command_handler(): channel = get_input("[HISTORY] Enter Channel Name ", str) count = get_input("[HISTORY] Enter Count ", int) - pubnub.history({ - 'channel' : channel, - 'count' : count, - 'callback' : _callback, - 'error' : _error - }) + pubnub.history(channel, count, callback=_callback, error=_error) def _here_now_command_handler(): @@ -232,13 +214,7 @@ def _here_now_command_handler(): print_error(r) channel = get_input("[HERE NOW] Enter Channel Name ", str) - pubnub.here_now({ - 'channel' : channel, - 'callback' : _callback, - 'error' : _error - }) - - + pubnub.here_now(channel, callback=_callback, error=_error) commands = [] -- cgit v1.2.3 From 09cd0c015ae276aa849297a6a976065b2b3f247b Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 14:03:13 +0530 Subject: modifying code for pep 8 compliance --- python/examples/dev-console.py | 106 +++++++++++++++++++++++------------ python/examples/here-now-example.py | 26 ++++----- python/examples/history-example.py | 7 +-- python/examples/publish-example.py | 52 +++++++++-------- python/examples/subscribe-example.py | 34 ++++++----- 5 files changed, 137 insertions(+), 88 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 383fa68..7814cef 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.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 @@ -55,41 +55,55 @@ parser.add_option("--uuid", print(options) -pubnub = Pubnub(options.publish_key, options.subscribe_key, options.secret_key, options.cipher_key, options.auth_key, options.ssl, options.origin, options.uuid) +pubnub = Pubnub(options.publish_key, + options.subscribe_key, + options.secret_key, + options.cipher_key, + options.auth_key, + options.ssl, + options.origin, + options.uuid) class color: - PURPLE = '\033[95m' - CYAN = '\033[96m' - DARKCYAN = '\033[36m' - BLUE = '\033[94m' - GREEN = '\033[92m' - YELLOW = '\033[93m' - RED = '\033[91m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' - END = '\033[0m' + PURPLE = '\033[95m' + CYAN = '\033[96m' + DARKCYAN = '\033[36m' + BLUE = '\033[94m' + GREEN = '\033[92m' + YELLOW = '\033[93m' + RED = '\033[91m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + END = '\033[0m' from datetime import datetime + def print_ok(msg, channel=None): - chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END - chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END + chstr = color.PURPLE + "[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + \ + "] " if channel is not None else "" + color.END try: - print(chstr + color.GREEN + str(msg) + color.END) + print(chstr + color.GREEN + str(msg) + color.END) except Exception as e: print(msg) + def print_error(msg, channel=None): - chstr = color.PURPLE + "[" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "] " + color.END - chstr += color.CYAN + "[Channel : " + channel + "] " if channel is not None else "" + color.END + chstr = color.PURPLE + "[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + \ + "] " if channel is not None else "" + color.END try: - print( chstr + color.RED + color.BOLD +str(msg) + color.END) + print(chstr + color.RED + color.BOLD + str(msg) + color.END) except: print(msg) import threading + def kill_all_threads(): for thread in threading.enumerate(): if thread.isAlive(): @@ -101,6 +115,7 @@ def kill_all_threads(): #thread.exit() #print(str(thread.getName()) + ' could not be terminated') + def get_input(message, t=None): while True: try: @@ -117,7 +132,8 @@ def get_input(message, t=None): raise ValueError if t is not None and t == bool: - if command in ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"]: + valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] + if command in valid: return True else: return False @@ -131,18 +147,20 @@ def get_input(message, t=None): print_error("Invalid input : " + command) - def _publish_command_handler(): channel = get_input("[PUBLISH] Enter Channel Name ", str) if channel is None: return while True: - message = get_input("[PUBLISH] Enter Message ( QUIT or CTRL-C for exit from publish mode ) ") - if message == 'QUIT' or message == 'quit' or message == None: - return + message = get_input("[PUBLISH] Enter Message \ + ( QUIT or CTRL-C for exit from publish mode ) ") + if message == 'QUIT' or message == 'quit' or message is None: + return + def _callback(r): print_ok(r) + def _error(r): print_error(r) pubnub.publish(channel, message, _callback, _error) @@ -150,23 +168,30 @@ def _publish_command_handler(): def _subscribe_command_handler(): channel = get_input("[SUBSCRIBE] Enter Channel Name ", str) + def _callback(r): print_ok(r, channel) + def _error(r): print_error(r, channel) pubnub.subscribe(channel, _callback, _error) + def _unsubscribe_command_handler(): channel = get_input("[UNSUBSCRIBE] Enter Channel Name ", str) + def _callback(r): print_ok(r) + def _error(r): print_error(r) pubnub.unsubscribe(channel) + def _grant_command_handler(): def _callback(r): print_ok(r) + def _error(r): print_error(r) channel = get_input("[GRANT] Enter Channel Name ", str) @@ -174,11 +199,13 @@ def _grant_command_handler(): ttl = get_input("[GRANT] Enter ttl ", int) read = get_input("[GRANT] Read ? ", bool) write = get_input("[GRANT] Write ? ", bool) - pubnub.grant(channel, auth_key,read,write,ttl, _callback) + pubnub.grant(channel, auth_key, read, write, ttl, _callback) + def _revoke_command_handler(): def _callback(r): print_ok(r) + def _error(r): print_error(r) channel = get_input("[REVOKE] Enter Channel Name ", str) @@ -187,18 +214,22 @@ def _revoke_command_handler(): pubnub.revoke(channel, auth_key, ttl, _callback) + def _audit_command_handler(): def _callback(r): print_ok(r) + def _error(r): print_error(r) channel = get_input("[AUDIT] Enter Channel Name ", str) auth_key = get_input("[AUDIT] Enter Auth Key ", str) pubnub.audit(channel, auth_key, _callback) + def _history_command_handler(): def _callback(r): print_ok(r) + def _error(r): print_error(r) channel = get_input("[HISTORY] Enter Channel Name ", str) @@ -210,6 +241,7 @@ def _history_command_handler(): def _here_now_command_handler(): def _callback(r): print_ok(r) + def _error(r): print_error(r) channel = get_input("[HERE NOW] Enter Channel Name ", str) @@ -218,28 +250,32 @@ def _here_now_command_handler(): commands = [] -commands.append({"command" : "publish", "handler" : _publish_command_handler}) -commands.append({"command" : "subscribe", "handler" : _subscribe_command_handler}) -commands.append({"command" : "unsubscribe", "handler" : _unsubscribe_command_handler}) -commands.append({"command" : "here_now", "handler" : _here_now_command_handler}) -commands.append({"command" : "history", "handler" : _history_command_handler}) -commands.append({"command" : "grant", "handler" : _grant_command_handler}) -commands.append({"command" : "revoke", "handler" : _revoke_command_handler}) -commands.append({"command" : "audit", "handler" : _audit_command_handler}) +commands.append({"command": "publish", "handler": _publish_command_handler}) +commands.append( + {"command": "subscribe", "handler": _subscribe_command_handler}) +commands.append( + {"command": "unsubscribe", "handler": _unsubscribe_command_handler}) +commands.append( + {"command": "here_now", "handler": _here_now_command_handler}) +commands.append({"command": "history", "handler": _history_command_handler}) +commands.append({"command": "grant", "handler": _grant_command_handler}) +commands.append({"command": "revoke", "handler": _revoke_command_handler}) +commands.append({"command": "audit", "handler": _audit_command_handler}) # last command is quit. add new commands before this line -commands.append({"command" : "QUIT"}) +commands.append({"command": "QUIT"}) + def get_help(): help = "" help += "Channels currently subscribed to : " help += str(pubnub.get_channel_array()) help += "\n" - for i,v in enumerate(commands): + for i, v in enumerate(commands): help += "Enter " + str(i) + " for " + v['command'] + "\n" return help - + while True: command = get_input(color.BLUE + get_help(), int) if command == len(commands) - 1 or command is None: diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py index b9f0b02..0888410 100644 --- a/python/examples/here-now-example.py +++ b/python/examples/here-now-example.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,24 +14,24 @@ sys.path.append('../') sys.path.append('./') from Pubnub import Pubnub -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 '' -ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False +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) -crazy = 'hello_world' +pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, + secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) +crazy = 'hello_world' + def print_cb(message): - print(message) + print(message) -pubnub.here_now( { - 'channel' : crazy, - 'callback' : print_cb +pubnub.here_now({ + 'channel': crazy, + 'callback': print_cb }) - diff --git a/python/examples/history-example.py b/python/examples/history-example.py index bf78c7d..b5cc1fd 100755 --- a/python/examples/history-example.py +++ b/python/examples/history-example.py @@ -4,12 +4,11 @@ sys.path.append('./') from Pubnub import Pubnub ## Initiat Class -pubnub = Pubnub( 'demo', 'demo', None, False ) +pubnub = Pubnub('demo', 'demo', None, False) ## History Example history = pubnub.history({ - 'channel' : 'hello_world', - 'limit' : 1 + 'channel': 'hello_world', + 'limit': 1 }) print(history) - diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index e632aef..ebf3c73 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.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 @@ -15,54 +15,62 @@ sys.path.append('../') sys.path.append('../../') from Pubnub import Pubnub -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 '' ##(Cipher key is Optional) -auth_key = len(sys.argv) > 5 and sys.argv[4] or 'abcd' ##(Cipher key is Optional) -ssl_on = len(sys.argv) > 6 and bool(sys.argv[5]) or False +secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' +cipher_key = len( + sys.argv) > 4 and sys.argv[4] or '' # (Cipher key is Optional) +auth_key = len( + sys.argv) > 5 and sys.argv[4] or 'abcd' # (Cipher key is Optional) +ssl_on = len(sys.argv) > 6 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- -pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, auth_key, ssl_on ) -crazy = 'hello_world' +pubnub = Pubnub( + publish_key, subscribe_key, secret_key, cipher_key, auth_key, ssl_on) +crazy = 'hello_world' ## ----------------------------------------------------------------------- ## Publish Example ## ----------------------------------------------------------------------- + + def publish_complete(info): print(info) + def publish_error(info): - print('ERROR : ' + str(info)) + print('ERROR : ' + str(info)) ## Publish string pubnub.publish({ - 'channel' : crazy, - 'message' : 'Hello World!', - 'callback' : publish_complete, - 'error' : publish_error + 'channel': crazy, + 'message': 'Hello World!', + 'callback': publish_complete, + 'error': publish_error }) ## Publish list -li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', + 'Saturday'] pubnub.publish({ - 'channel' : crazy, - 'message' : li, - 'callback' : publish_complete, - 'error' : publish_error + 'channel': crazy, + 'message': li, + 'callback': publish_complete, + 'error': publish_error }) + def done_cb(info): publish_complete(info) pubnub.publish({ - 'channel' : crazy, - 'message' : { 'some_key' : 'some_val' }, - 'callback' : done_cb, - 'error' : publish_error + 'channel': crazy, + 'message': {'some_key': 'some_val'}, + 'callback': done_cb, + 'error': publish_error }) diff --git a/python/examples/subscribe-example.py b/python/examples/subscribe-example.py index a67a08f..0a18899 100755 --- a/python/examples/subscribe-example.py +++ b/python/examples/subscribe-example.py @@ -8,48 +8,55 @@ import string from Pubnub import Pubnub ## Initiate Class -pubnub = Pubnub( 'demo', 'demo', None, False ) +pubnub = Pubnub('demo', 'demo', None, False) -print("My UUID is: "+pubnub.uuid) +print("My UUID is: " + pubnub.uuid) -channel = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(20)) +channel = ''.join( + random.choice(string.ascii_letters + string.digits) for x in range(20)) ## Subscribe Example -def receive(message) : + + +def receive(message): print(message) return False + def pres_event(message): print(message) return False + def subscribe(): print("Listening for messages on '%s' channel..." % channel) pubnub.subscribe({ - 'channel' : channel, - 'callback' : receive + 'channel': channel, + 'callback': receive }) + def presence(): print("Listening for presence events on '%s' channel..." % channel) pubnub.presence({ - 'channel' : channel, - 'callback' : pres_event + 'channel': channel, + 'callback': pres_event }) + def publish(): print("Publishing a test message on '%s' channel..." % channel) pubnub.publish({ - 'channel' : channel, - 'message' : { 'text':'foo bar' } + 'channel': channel, + 'message': {'text': 'foo bar'} }) pres_thread = threading.Thread(target=presence) -pres_thread.daemon=True +pres_thread.daemon = True pres_thread.start() sub_thread = threading.Thread(target=subscribe) -sub_thread.daemon=True +sub_thread.daemon = True sub_thread.start() time.sleep(3) @@ -60,7 +67,6 @@ publish() print("waiting for subscribes and presence") pres_thread.join() -print(pubnub.here_now({'channel':channel})) +print(pubnub.here_now({'channel': channel})) sub_thread.join() - -- cgit v1.2.3 From 1d97c69f186719fe007a4fa0033d39d9a68a4e43 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 14:13:37 +0530 Subject: modifying dev console to use new style classes --- python/examples/dev-console.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 7814cef..2e93c7e 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -55,17 +55,17 @@ parser.add_option("--uuid", print(options) -pubnub = Pubnub(options.publish_key, - options.subscribe_key, - options.secret_key, - options.cipher_key, - options.auth_key, - options.ssl, - options.origin, +pubnub = Pubnub(options.publish_key, + options.subscribe_key, + options.secret_key, + options.cipher_key, + options.auth_key, + options.ssl, + options.origin, options.uuid) -class color: +class color(object): PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' -- cgit v1.2.3 From f7b89bfafae34fa22509c1d1c59d1284ec62c5df Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 23 Apr 2014 21:35:06 +0530 Subject: exception handling changes --- python/examples/dev-console.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 2e93c7e..868ba7c 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -55,13 +55,13 @@ parser.add_option("--uuid", print(options) -pubnub = Pubnub(options.publish_key, - options.subscribe_key, - options.secret_key, - options.cipher_key, - options.auth_key, - options.ssl, - options.origin, +pubnub = Pubnub(options.publish_key, + options.subscribe_key, + options.secret_key, + options.cipher_key, + options.auth_key, + options.ssl, + options.origin, options.uuid) @@ -87,7 +87,7 @@ def print_ok(msg, channel=None): "] " if channel is not None else "" + color.END try: print(chstr + color.GREEN + str(msg) + color.END) - except Exception as e: + except UnicodeEncodeError as e: print(msg) @@ -98,7 +98,7 @@ def print_error(msg, channel=None): "] " if channel is not None else "" + color.END try: print(chstr + color.RED + color.BOLD + str(msg) + color.END) - except: + except UnicodeEncodeError as e: print(msg) import threading @@ -107,13 +107,7 @@ import threading def kill_all_threads(): for thread in threading.enumerate(): if thread.isAlive(): - try: - thread._Thread__stop() - except Exception as e: - pass - #print(e) - #thread.exit() - #print(str(thread.getName()) + ' could not be terminated') + thread._Thread__stop() def get_input(message, t=None): -- cgit v1.2.3 From 93379625e26c98a8cfab72c106ae40819843f956 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 24 Apr 2014 00:35:10 +0530 Subject: remove relative imports --- python/examples/dev-console.py | 2 -- python/examples/here-now-example.py | 2 -- python/examples/history-example.py | 2 -- python/examples/publish-example.py | 2 -- python/examples/subscribe-example.py | 2 -- 5 files changed, 10 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 868ba7c..6ff5209 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -10,8 +10,6 @@ ## ----------------------------------- import sys -sys.path.append('../') -sys.path.append('../../') from Pubnub import Pubnub from optparse import OptionParser diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py index 0888410..9bb448c 100644 --- a/python/examples/here-now-example.py +++ b/python/examples/here-now-example.py @@ -10,8 +10,6 @@ ## ----------------------------------- import sys -sys.path.append('../') -sys.path.append('./') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' diff --git a/python/examples/history-example.py b/python/examples/history-example.py index b5cc1fd..092c929 100755 --- a/python/examples/history-example.py +++ b/python/examples/history-example.py @@ -1,6 +1,4 @@ import sys -sys.path.append('../') -sys.path.append('./') from Pubnub import Pubnub ## Initiat Class diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index ebf3c73..69ea053 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -11,8 +11,6 @@ import sys from twisted.internet import reactor -sys.path.append('../') -sys.path.append('../../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' diff --git a/python/examples/subscribe-example.py b/python/examples/subscribe-example.py index 0a18899..0b1c949 100755 --- a/python/examples/subscribe-example.py +++ b/python/examples/subscribe-example.py @@ -1,6 +1,4 @@ import sys -sys.path.append('..') -sys.path.append('.') import threading import time import random -- cgit v1.2.3 From c98286f500b77dcf426367df0b688f536b77ea9b Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 24 Apr 2014 01:33:45 +0530 Subject: fixing imports --- python/examples/dev-console.py | 6 +----- python/examples/here-now-example.py | 5 +---- python/examples/history-example.py | 2 +- python/examples/publish-example.py | 7 +------ python/examples/subscribe-example.py | 2 +- 5 files changed, 5 insertions(+), 17 deletions(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 6ff5209..5bdbe8c 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -5,12 +5,8 @@ ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - import sys -from Pubnub import Pubnub +from Pubnub import PubnubAsync as Pubnub from optparse import OptionParser diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py index 9bb448c..0bc3015 100644 --- a/python/examples/here-now-example.py +++ b/python/examples/here-now-example.py @@ -5,12 +5,9 @@ ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- import sys -from Pubnub import Pubnub +from Pubnub import PubnubAsync 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/examples/history-example.py b/python/examples/history-example.py index 092c929..793c612 100755 --- a/python/examples/history-example.py +++ b/python/examples/history-example.py @@ -1,5 +1,5 @@ import sys -from Pubnub import Pubnub +from Pubnub import PubnubAsync as Pubnub ## Initiat Class pubnub = Pubnub('demo', 'demo', None, False) diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index 69ea053..1c57e4b 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -5,13 +5,8 @@ ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ -## ----------------------------------- -## PubNub 3.1 Real-time Push Cloud API -## ----------------------------------- - import sys -from twisted.internet import reactor -from Pubnub import Pubnub +from Pubnub import PubnubAsync 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/examples/subscribe-example.py b/python/examples/subscribe-example.py index 0b1c949..9c16bbe 100755 --- a/python/examples/subscribe-example.py +++ b/python/examples/subscribe-example.py @@ -3,7 +3,7 @@ import threading import time import random import string -from Pubnub import Pubnub +from Pubnub import PubnubAsync as Pubnub ## Initiate Class pubnub = Pubnub('demo', 'demo', None, False) -- cgit v1.2.3 From ad6a453a0f00d20f0668b17b61668cb7fa5ee4e4 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 03:26:09 +0530 Subject: v1 of console --- python/examples/console.py | 326 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 python/examples/console.py (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py new file mode 100644 index 0000000..bd364f7 --- /dev/null +++ b/python/examples/console.py @@ -0,0 +1,326 @@ +## 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 PubnubAsync as Pubnub +import threading +from datetime import datetime + +from cmd2 import Cmd, make_option, options, Cmd2TestCase +import optparse + + +of=sys.stdout + + +class color(object): + PURPLE = '\033[95m' + CYAN = '\033[96m' + DARKCYAN = '\033[36m' + BLUE = '\033[94m' + GREEN = '\033[92m' + YELLOW = '\033[93m' + RED = '\033[91m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + END = '\033[0m' + +def print_ok(msg, channel=None): + chstr = color.PURPLE + "[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + \ + "] " if channel is not None else "" + color.END + try: + print >>of, ("\n") + print >>of, (chstr + color.GREEN + str(msg) + color.END) + except UnicodeEncodeError as e: + print >>of, (msg) + +def print_error(msg, channel=None): + chstr = color.PURPLE + "[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] " + color.END + chstr += color.CYAN + "[Channel : " + channel + \ + "] " if channel is not None else "" + color.END + try: + print >>of, ("\n") + print >>of, (chstr + color.RED + color.BOLD + str(msg) + color.END) + except UnicodeEncodeError as e: + print >>of, (msg) + +class DefaultPubnub(object): + def handlerFunctionClosure(self,name): + def handlerFunction(*args,**kwargs): + print_error("Pubnub not initialized. Use init command to initialize") + return handlerFunction + def __getattr__(self,name): + return self.handlerFunctionClosure(name) + +pubnub=DefaultPubnub() + + + +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + thread._Thread__stop() + +def get_input(message, t=None): + while True: + try: + try: + command = raw_input(message) + except NameError: + command = input(message) + except KeyboardInterrupt: + return None + + command = command.strip() + + if command is None or len(command) == 0: + raise ValueError + + if t is not None and t == bool: + valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] + if command in valid: + return True + else: + return False + if t is not None: + command = t(command) + else: + command = eval("'" + command + "'") + + return command + except ValueError: + print_error("Invalid input : " + command) + +def _publish_command_handler(channel, message): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + pubnub.publish(channel, message, _callback, _error) + + +def _subscribe_command_handler(channel): + + def _callback(r): + print_ok(r, channel) + + def _error(r): + print_error(r, channel) + pubnub.subscribe(channel, _callback, _error) + + +def _unsubscribe_command_handler(channel): + + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + pubnub.unsubscribe(channel) + + +def _grant_command_handler(channel, auth_key, read, write, ttl): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + pubnub.grant(channel, auth_key, read, write, ttl, _callback) + + +def _revoke_command_handler(channel, auth_key, ttl): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + pubnub.revoke(channel, auth_key, ttl, _callback) + + +def _audit_command_handler(channel, auth_key): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + pubnub.audit(channel, auth_key, _callback) + + +def _history_command_handler(channel, count): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + pubnub.history(channel, count, callback=_callback, error=_error) + + +def _here_now_command_handler(channel): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + pubnub.here_now(channel, callback=_callback, error=_error) + + +class DevConsole(Cmd): + multilineCommands = ['orate'] + Cmd.shortcuts.update({'&': 'speak'}) + maxrepeats = 3 + Cmd.settable.append('maxrepeats') + + def __init__(self): + Cmd.__init__(self) + self.prompt = "(PubNub Console) > " + self.intro = "Welcome to PubNub Developer Console!" ## defaults to None + + def cmdloop(self): + try: + Cmd.cmdloop(self) + except KeyboardInterrupt as e: + self.cmdloop() + + + @options([make_option('-p', '--publish-key', action="store", default="demo", help="Publish Key"), + make_option('-s', '--subscribe-key', action="store", default="demo", help="Subscribe Key"), + make_option('-k', '--secret-key', action="store", default="demo", help="cipher Key"), + make_option('-c', '--cipher-key', action="store", default="", help="Secret Key"), + make_option('-a', '--auth-key', action="store", default=None, help="Auth Key"), + make_option('--ssl-on', dest='ssl', action='store_true', default=False, help="SSL Enabled ?"), + make_option('-o', '--origin', action="store", default="pubsub.pubnub.com", help="Origin"), + make_option('-u', '--uuid', action="store", default=None, help="UUID") + ]) + def do_init(self, command, opts): + global pubnub + pubnub = Pubnub(opts.publish_key, + opts.subscribe_key, + opts.secret_key, + opts.cipher_key, + opts.auth_key, + opts.ssl, + opts.origin, + opts.uuid) + + @options([make_option('-c', '--channel', action="store", help="Channel for here now data") + ]) + def do_here_now(self, command, opts): + + if opts.channel is None: + print_error("Missing channel") + return + + _here_now_command_handler(opts.channel) + + @options([make_option('-c', '--channel', action="store", help="Channel for history data"), + make_option('-n', '--count', action="store", default=5, help="Number of messages") + ]) + def do_history(self, command, opts): + + if opts.channel is None: + print_error("Missing channel") + return + + _history_command_handler(opts.channel, opts.count) + + + @options([make_option('-c', '--channel', action="store", help="Channel on which to publish"), + make_option('-m', '--message', action="store", help="Message to be published") + ]) + def do_publish(self, command, opts): + + if opts.channel is None: + print_error("Missing channel") + return + + if opts.message is None: + print_error("Missing message") + return + + _publish_command_handler(opts.channel,opts.message) + + @options([make_option('-c', '--channel', action="store", help="Channel on which to grant"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key"), + make_option('-r', '--read-enabled', dest='read', action='store_true', default=False, help="Read ?"), + make_option('-w', '--write-enabled', dest='write', action='store_true', default=False, help="Write ?"), + make_option('-t', '--ttl', action="store", default=5, help="TTL") + ]) + def do_grant(self, command, opts): + if opts.channel is None: + print_error("Missing channel") + return + + opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key + + _grant_command_handler(opts.channel,opts.auth_key, opts.read, opts.write, opts.ttl) + + @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key"), + make_option('-t', '--ttl', action="store", default=5, help="TTL") + ]) + def do_revoke(self, command, opts): + if opts.channel is None: + print_error("Missing channel") + return + + opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key + + _revoke_command_handler(opts.channel,opts.auth_key, opts.ttl) + + @options([make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key") + ]) + def do_audit(self, command, opts): + + opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key + + _audit_command_handler(opts.auth_key) + + + @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe") + ]) + def do_unsubscribe(self, command, opts): + if opts.channel is None: + print_error("Missing channel") + return + _unsubscribe_command_handler(opts.channel) + + + @options([make_option('-c', '--channel', action="store", help="Channel for subscribe") + ]) + def do_subscribe(self, command, opts): + + if opts is None: + print_error("Missing argument") + return + + if opts.channel is None: + print_error("Missing channel") + return + + _subscribe_command_handler(opts.channel) + + + +def main(): + app = DevConsole() + app.cmdloop() + +if __name__ == "__main__": + main() + -- cgit v1.2.3 From 9e4032331721539d2b1e74b87b86ac5c66ccc4af Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 10:54:36 +0530 Subject: more changes to new console --- python/examples/console.py | 78 ++++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 33 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index bd364f7..4dfd891 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -16,40 +16,29 @@ import optparse of=sys.stdout - -class color(object): - PURPLE = '\033[95m' - CYAN = '\033[96m' - DARKCYAN = '\033[36m' - BLUE = '\033[94m' - GREEN = '\033[92m' - YELLOW = '\033[93m' - RED = '\033[91m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' - END = '\033[0m' +color = Cmd() def print_ok(msg, channel=None): - chstr = color.PURPLE + "[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] " + color.END - chstr += color.CYAN + "[Channel : " + channel + \ - "] " if channel is not None else "" + color.END + chstr = color.colorize("[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] ","magenta") + chstr += color.colorize("[Channel : " + channel + \ + "] " if channel is not None else "", "cyan") try: - print >>of, ("\n") - print >>of, (chstr + color.GREEN + str(msg) + color.END) + print >>of, (chstr + color.colorize(str(msg),"green")) except UnicodeEncodeError as e: print >>of, (msg) + of.flush() def print_error(msg, channel=None): - chstr = color.PURPLE + "[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] " + color.END - chstr += color.CYAN + "[Channel : " + channel + \ - "] " if channel is not None else "" + color.END + chstr = color.colorize("[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + \ + "] " if channel is not None else "", "cyan") try: - print >>of, ("\n") - print >>of, (chstr + color.RED + color.BOLD + str(msg) + color.END) + print >>of, (chstr + color.colorize(color.colorize(str(msg),"red"),"bold")) except UnicodeEncodeError as e: print >>of, (msg) + of.flush() class DefaultPubnub(object): def handlerFunctionClosure(self,name): @@ -177,16 +166,16 @@ def _here_now_command_handler(channel): pubnub.here_now(channel, callback=_callback, error=_error) -class DevConsole(Cmd): - multilineCommands = ['orate'] - Cmd.shortcuts.update({'&': 'speak'}) - maxrepeats = 3 - Cmd.settable.append('maxrepeats') +class DevConsole(Cmd): + def __init__(self): Cmd.__init__(self) + global pubnub self.prompt = "(PubNub Console) > " self.intro = "Welcome to PubNub Developer Console!" ## defaults to None + self.default_channel = None + pubnub = Pubnub("demo", "demo") def cmdloop(self): try: @@ -215,10 +204,30 @@ class DevConsole(Cmd): opts.origin, opts.uuid) + + @options([make_option('-c', '--channel', action="store", help="Default Channel") + ]) + def do_set_default_channel(self, command, opts): + + if opts.channel is None: + print_error("Missing channel") + return + self.default_channel = opts.channel + + @options([make_option('-f', '--file', action="store", default="./pubnub-console.log", help="Output file") + ]) + def do_set_output_file(self, command, opts): + global of + try: + of = file(opts.file,'w+') + except IOError as e: + print_error("Could not set output file. " + e.reason) + + @options([make_option('-c', '--channel', action="store", help="Channel for here now data") ]) def do_here_now(self, command, opts): - + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -229,7 +238,7 @@ class DevConsole(Cmd): make_option('-n', '--count', action="store", default=5, help="Number of messages") ]) def do_history(self, command, opts): - + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -241,7 +250,7 @@ class DevConsole(Cmd): make_option('-m', '--message', action="store", help="Message to be published") ]) def do_publish(self, command, opts): - + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -260,6 +269,7 @@ class DevConsole(Cmd): make_option('-t', '--ttl', action="store", default=5, help="TTL") ]) def do_grant(self, command, opts): + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -274,6 +284,7 @@ class DevConsole(Cmd): make_option('-t', '--ttl', action="store", default=5, help="TTL") ]) def do_revoke(self, command, opts): + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -295,6 +306,7 @@ class DevConsole(Cmd): @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe") ]) def do_unsubscribe(self, command, opts): + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -304,7 +316,7 @@ class DevConsole(Cmd): @options([make_option('-c', '--channel', action="store", help="Channel for subscribe") ]) def do_subscribe(self, command, opts): - + opts.channel = self.default_channel if opts.channel is None else opts.channel if opts is None: print_error("Missing argument") return -- cgit v1.2.3 From 44aee82f3eadea1241ac4350b4f9f34daf58eb87 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 19:42:21 +0530 Subject: improvements to console --- python/examples/console.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 4dfd891..aa6fff3 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -12,7 +12,7 @@ from datetime import datetime from cmd2 import Cmd, make_option, options, Cmd2TestCase import optparse - +import json of=sys.stdout @@ -246,8 +246,7 @@ class DevConsole(Cmd): _history_command_handler(opts.channel, opts.count) - @options([make_option('-c', '--channel', action="store", help="Channel on which to publish"), - make_option('-m', '--message', action="store", help="Message to be published") + @options([make_option('-c', '--channel', action="store", help="Channel on which to publish") ]) def do_publish(self, command, opts): opts.channel = self.default_channel if opts.channel is None else opts.channel @@ -255,11 +254,16 @@ class DevConsole(Cmd): print_error("Missing channel") return - if opts.message is None: + if command is None: print_error("Missing message") return - _publish_command_handler(opts.channel,opts.message) + try: + message = json.loads(str(command)) + except ValueError as ve: + message = str(command) + + _publish_command_handler(opts.channel,message) @options([make_option('-c', '--channel', action="store", help="Channel on which to grant"), make_option('-a', '--auth-key', dest="auth_key", action="store", @@ -327,8 +331,6 @@ class DevConsole(Cmd): _subscribe_command_handler(opts.channel) - - def main(): app = DevConsole() app.cmdloop() -- cgit v1.2.3 From 2b72900bab9af06f37bd024c4aad8da3513a2430 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 20:15:55 +0530 Subject: clean exit on typing exit --- python/examples/console.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index aa6fff3..1694ba5 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -166,6 +166,12 @@ def _here_now_command_handler(channel): pubnub.here_now(channel, callback=_callback, error=_error) +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + thread._Thread__stop() + + class DevConsole(Cmd): @@ -177,11 +183,13 @@ class DevConsole(Cmd): self.default_channel = None pubnub = Pubnub("demo", "demo") - def cmdloop(self): + def cmdloop_with_keyboard_interrupt(self): try: - Cmd.cmdloop(self) - except KeyboardInterrupt as e: self.cmdloop() + except KeyboardInterrupt: + print 'KB KeyboardInterrupt' + sys.stdout.write('\n') + kill_all_threads() @options([make_option('-p', '--publish-key', action="store", default="demo", help="Publish Key"), @@ -331,9 +339,20 @@ class DevConsole(Cmd): _subscribe_command_handler(opts.channel) + def do_exit(self, args): + kill_all_threads() + return -1 + + def do_EOF(self, args): + kill_all_threads() + return self.do_exit(args) + + def handler(self, signum, frame): + kill_all_threads() + def main(): app = DevConsole() - app.cmdloop() + app.cmdloop_with_keyboard_interrupt() if __name__ == "__main__": main() -- cgit v1.2.3 From 7568c30242ae3a9f4163248a29a596fab5902601 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 23:46:57 +0530 Subject: adding sync async mode to console --- python/examples/console.py | 56 +++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 20 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 1694ba5..dd499c5 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -19,6 +19,8 @@ of=sys.stdout color = Cmd() def print_ok(msg, channel=None): + if msg is None: + return chstr = color.colorize("[" + datetime.now().strftime( '%Y-%m-%d %H:%M:%S') + "] ","magenta") chstr += color.colorize("[Channel : " + channel + \ @@ -30,6 +32,8 @@ def print_ok(msg, channel=None): of.flush() def print_error(msg, channel=None): + if msg is None: + return chstr = color.colorize("[" + datetime.now().strftime( '%Y-%m-%d %H:%M:%S') + "] ", "magenta") chstr += color.colorize("[Channel : " + channel + \ @@ -87,13 +91,13 @@ def get_input(message, t=None): except ValueError: print_error("Invalid input : " + command) -def _publish_command_handler(channel, message): +def _publish_command_handler(channel, message,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.publish(channel, message, _callback, _error) + print_ok(pubnub.publish(channel, message, _callback if async is True else None, _error if async is True else None)) def _subscribe_command_handler(channel): @@ -116,54 +120,54 @@ def _unsubscribe_command_handler(channel): pubnub.unsubscribe(channel) -def _grant_command_handler(channel, auth_key, read, write, ttl): +def _grant_command_handler(channel, auth_key, read, write, ttl,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.grant(channel, auth_key, read, write, ttl, _callback) + print_ok(pubnub.grant(channel, auth_key, read, write, ttl, _callback if async is True else None, _error if async is True else None)) -def _revoke_command_handler(channel, auth_key, ttl): +def _revoke_command_handler(channel, auth_key, ttl,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.revoke(channel, auth_key, ttl, _callback) + print_ok(pubnub.revoke(channel, auth_key, ttl, _callback if async is True else None, _error if async is True else None)) -def _audit_command_handler(channel, auth_key): +def _audit_command_handler(channel, auth_key,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.audit(channel, auth_key, _callback) + print_ok(pubnub.audit(channel, auth_key, _callback if async is True else None, _error if async is True else None)) -def _history_command_handler(channel, count): +def _history_command_handler(channel, count,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.history(channel, count, callback=_callback, error=_error) + print_ok(pubnub.history(channel, count, _callback if async is True else None, _error if async is True else None)) -def _here_now_command_handler(channel): +def _here_now_command_handler(channel,async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.here_now(channel, callback=_callback, error=_error) + print_ok(pubnub.here_now(channel, _callback if async is True else None, _error if async is True else None)) def kill_all_threads(): @@ -181,13 +185,13 @@ class DevConsole(Cmd): self.prompt = "(PubNub Console) > " self.intro = "Welcome to PubNub Developer Console!" ## defaults to None self.default_channel = None + self.async = False pubnub = Pubnub("demo", "demo") def cmdloop_with_keyboard_interrupt(self): try: self.cmdloop() except KeyboardInterrupt: - print 'KB KeyboardInterrupt' sys.stdout.write('\n') kill_all_threads() @@ -213,6 +217,13 @@ class DevConsole(Cmd): opts.uuid) + def do_set_sync(self, command): + self.async = False + + def do_set_async(self, command): + self.async = True + + @options([make_option('-c', '--channel', action="store", help="Default Channel") ]) def do_set_default_channel(self, command, opts): @@ -240,7 +251,7 @@ class DevConsole(Cmd): print_error("Missing channel") return - _here_now_command_handler(opts.channel) + _here_now_command_handler(opts.channel,async=self.async) @options([make_option('-c', '--channel', action="store", help="Channel for history data"), make_option('-n', '--count', action="store", default=5, help="Number of messages") @@ -251,7 +262,7 @@ class DevConsole(Cmd): print_error("Missing channel") return - _history_command_handler(opts.channel, opts.count) + _history_command_handler(opts.channel, opts.count,async=self.async) @options([make_option('-c', '--channel', action="store", help="Channel on which to publish") @@ -271,7 +282,7 @@ class DevConsole(Cmd): except ValueError as ve: message = str(command) - _publish_command_handler(opts.channel,message) + _publish_command_handler(opts.channel,message,async=self.async) @options([make_option('-c', '--channel', action="store", help="Channel on which to grant"), make_option('-a', '--auth-key', dest="auth_key", action="store", @@ -288,7 +299,7 @@ class DevConsole(Cmd): opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key - _grant_command_handler(opts.channel,opts.auth_key, opts.read, opts.write, opts.ttl) + _grant_command_handler(opts.channel,opts.auth_key, opts.read, opts.write, opts.ttl,async=self.async) @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), make_option('-a', '--auth-key', dest="auth_key", action="store", @@ -303,16 +314,21 @@ class DevConsole(Cmd): opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key - _revoke_command_handler(opts.channel,opts.auth_key, opts.ttl) + _revoke_command_handler(opts.channel,opts.auth_key, opts.ttl,async=self.async) - @options([make_option('-a', '--auth-key', dest="auth_key", action="store", + @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", help="Auth Key") ]) def do_audit(self, command, opts): + opts.channel = self.default_channel if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key - _audit_command_handler(opts.auth_key) + _audit_command_handler(opts.channel, opts.auth_key,async=self.async) @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe") -- cgit v1.2.3 From 03eedf317ae660893f61bb919b48289b0bf971f3 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 25 Apr 2014 23:56:15 +0530 Subject: changing history to get_history --- python/examples/console.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index dd499c5..225c7eb 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -256,7 +256,7 @@ class DevConsole(Cmd): @options([make_option('-c', '--channel', action="store", help="Channel for history data"), make_option('-n', '--count', action="store", default=5, help="Number of messages") ]) - def do_history(self, command, opts): + def do_get_history(self, command, opts): opts.channel = self.default_channel if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") -- cgit v1.2.3 From 769c3a908890a15c8f5e08cd651e1120194c2e74 Mon Sep 17 00:00:00 2001 From: Devendra Date: Sat, 26 Apr 2014 00:23:30 +0530 Subject: save history to file --- python/examples/console.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 225c7eb..8a3ab3b 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -14,6 +14,22 @@ from cmd2 import Cmd, make_option, options, Cmd2TestCase import optparse import json +import atexit +import os +import readline +import rlcompleter + +historyPath = os.path.expanduser("~/.pubnub_console_history") + +def save_history(historyPath=historyPath): + import readline + readline.write_history_file(historyPath) + +if os.path.exists(historyPath): + readline.read_history_file(historyPath) + +atexit.register(save_history) + of=sys.stdout color = Cmd() -- cgit v1.2.3 From d703c34d918a75a4d5a984143c8fbd5049931b1a Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 29 Apr 2014 03:11:45 +0530 Subject: adding start console script and helper files --- python/examples/config | 9 +++++++++ python/examples/console-help.txt | 34 ++++++++++++++++++++++++++++++++++ python/examples/console.py | 4 ++++ python/examples/start-console.sh | 8 ++++++++ 4 files changed, 55 insertions(+) create mode 100644 python/examples/config create mode 100644 python/examples/console-help.txt create mode 100644 python/examples/start-console.sh (limited to 'python/examples') diff --git a/python/examples/config b/python/examples/config new file mode 100644 index 0000000..1c73645 --- /dev/null +++ b/python/examples/config @@ -0,0 +1,9 @@ +sessionname pubnub-console +screen -t output tail -f ./pubnub-console.log +split +focus down +screen -t console python console.py "set_output_file" +split -v +focus down +screen -t help vi ./console-help.txt +focus up diff --git a/python/examples/console-help.txt b/python/examples/console-help.txt new file mode 100644 index 0000000..55debd2 --- /dev/null +++ b/python/examples/console-help.txt @@ -0,0 +1,34 @@ +********************** HELP ****************************** + +TO EXIT . Ctrl-A \ followed by y +TO MOVE BETWEEN PANES . Ctrl-A TAB + +********************************************************** + +PUBLISH + +Usage: publish [options] arg + +Options: + -h, --help show this help message and exit + -c CHANNEL, --channel=CHANNEL + Channel on which to publish + +Examples: + (1) publish -c hello_world hi how r u + (2) pub -c hello_world [1,2] + + + +SUBSCRIBE + +Usage: subscribe [options] arg + +Options: + -h, --help show this help message and exit + -c CHANNEL, --channel=CHANNEL + Channel for subscribe + +Examples: + (1) subscribe -c hello_world + (2) sub -c hello_world \ No newline at end of file diff --git a/python/examples/console.py b/python/examples/console.py index 8a3ab3b..e96b4e5 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -5,6 +5,7 @@ ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ + import sys from Pubnub import PubnubAsync as Pubnub import threading @@ -19,6 +20,9 @@ import os import readline import rlcompleter +if sys.argv[0] == "screen": + print "screen" + historyPath = os.path.expanduser("~/.pubnub_console_history") def save_history(historyPath=historyPath): diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh new file mode 100644 index 0000000..df4fd6e --- /dev/null +++ b/python/examples/start-console.sh @@ -0,0 +1,8 @@ +if ! type "screen" > /dev/null; then + echo "[ERROR] Screen is not installed. Please install screen to use this utility ." + exit +fi +rm ./pubnub-console.log +touch ./pubnub-console.log +set PYTHONPATH=../.. +screen -c config -- cgit v1.2.3 From 8395a9a3922e345608aa1e49b4aa27b9d5927a0d Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 30 Apr 2014 00:43:56 +0530 Subject: making tweaks to run on osx --- python/examples/config | 2 +- python/examples/config_osx | 8 ++++++++ python/examples/start-console.sh | 10 +++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 python/examples/config_osx (limited to 'python/examples') diff --git a/python/examples/config b/python/examples/config index 1c73645..f35134f 100644 --- a/python/examples/config +++ b/python/examples/config @@ -5,5 +5,5 @@ focus down screen -t console python console.py "set_output_file" split -v focus down -screen -t help vi ./console-help.txt +screen -t help vi -R ./console-help.txt focus up diff --git a/python/examples/config_osx b/python/examples/config_osx new file mode 100644 index 0000000..cdb186c --- /dev/null +++ b/python/examples/config_osx @@ -0,0 +1,8 @@ +sessionname pubnub-console +screen -t help vi -R ./console-help.txt +split +focus down +screen -t output tail -f ./pubnub-console.log +split +focus down +screen -t console python console.py "set_output_file" diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh index df4fd6e..e842427 100644 --- a/python/examples/start-console.sh +++ b/python/examples/start-console.sh @@ -1,3 +1,4 @@ +#!/bin/bash if ! type "screen" > /dev/null; then echo "[ERROR] Screen is not installed. Please install screen to use this utility ." exit @@ -5,4 +6,11 @@ fi rm ./pubnub-console.log touch ./pubnub-console.log set PYTHONPATH=../.. -screen -c config +screen -X -S pubnub-console quit 2>&1 > /dev/null +OS="`uname`" +case $OS in + 'darwin') + screen -c config_osx + ;; + *) screen -c config;; +esac -- cgit v1.2.3 From e2ccbc05b6ed2696dd8d2d2134b2023c528e1b70 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 30 Apr 2014 00:59:26 +0530 Subject: fixing start script for osx --- python/examples/start-console.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python/examples') diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh index e842427..2df3f77 100644 --- a/python/examples/start-console.sh +++ b/python/examples/start-console.sh @@ -9,8 +9,8 @@ set PYTHONPATH=../.. screen -X -S pubnub-console quit 2>&1 > /dev/null OS="`uname`" case $OS in - 'darwin') + [dD]'arwin') screen -c config_osx ;; - *) screen -c config;; + *) screen -c config ;; esac -- cgit v1.2.3 From 10f345fcf4edb489cf9b86039c030baa62a6881c Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 30 Apr 2014 17:14:09 +0530 Subject: adding persistent connectino support --- python/examples/publish-example.py | 40 +++++++------------------------------- 1 file changed, 7 insertions(+), 33 deletions(-) (limited to 'python/examples') diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py index 1c57e4b..78b7f36 100755 --- a/python/examples/publish-example.py +++ b/python/examples/publish-example.py @@ -21,7 +21,7 @@ ssl_on = len(sys.argv) > 6 and bool(sys.argv[5]) or False ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub( - publish_key, subscribe_key, secret_key, cipher_key, auth_key, ssl_on) + publish_key, subscribe_key, secret_key, cipher_key, auth_key, ssl_on, pooling=True) crazy = 'hello_world' ## ----------------------------------------------------------------------- @@ -36,35 +36,9 @@ def publish_complete(info): def publish_error(info): print('ERROR : ' + str(info)) -## Publish string -pubnub.publish({ - 'channel': crazy, - 'message': 'Hello World!', - 'callback': publish_complete, - 'error': publish_error -}) - -## Publish list -li = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', - 'Saturday'] - -pubnub.publish({ - 'channel': crazy, - 'message': li, - 'callback': publish_complete, - 'error': publish_error -}) - - -def done_cb(info): - publish_complete(info) - -pubnub.publish({ - 'channel': crazy, - 'message': {'some_key': 'some_val'}, - 'callback': done_cb, - 'error': publish_error -}) - - -pubnub.start() +import time +start = time.time() +for i in range(1,100): + print pubnub.publish(crazy, 'hello world-' + str(i)) +end = time.time() +print(end - start); -- cgit v1.2.3 From 06511b3849e80cb5692ed92f7da31043c85556a0 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 1 May 2014 00:14:25 +0530 Subject: more chagnes to console --- python/examples/console.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index e96b4e5..240e5c0 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -202,11 +202,12 @@ class DevConsole(Cmd): def __init__(self): Cmd.__init__(self) global pubnub - self.prompt = "(PubNub Console) > " - self.intro = "Welcome to PubNub Developer Console!" ## defaults to None + self.intro = "For Help type ? or help . To quit/exit type exit" ## defaults to None self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") + self.prompt = "(PubNub Console) [" + color.colorize(pubnub.get_origin(),"blue") + "] > " + def cmdloop_with_keyboard_interrupt(self): try: @@ -235,12 +236,17 @@ class DevConsole(Cmd): opts.ssl, opts.origin, opts.uuid) + self.prompt = "(PubNub Console) [" + color.colorize(pubnub.get_origin(),"blue") + "] > " def do_set_sync(self, command): + """unset_async + Unset Async mode""" self.async = False def do_set_async(self, command): + """set_async + Set Async mode""" self.async = True @@ -361,7 +367,9 @@ class DevConsole(Cmd): _unsubscribe_command_handler(opts.channel) - @options([make_option('-c', '--channel', action="store", help="Channel for subscribe") + @options([make_option('-c', '--channel', action="store", help="Channel for subscribe"), + make_option('-g', '--get-channel-list', action="store_true", dest="get", + default=False, help="Get susbcribed channel list") ]) def do_subscribe(self, command, opts): opts.channel = self.default_channel if opts.channel is None else opts.channel @@ -369,11 +377,11 @@ class DevConsole(Cmd): print_error("Missing argument") return - if opts.channel is None: - print_error("Missing channel") - return + if opts.channel is not None: + _subscribe_command_handler(opts.channel) - _subscribe_command_handler(opts.channel) + if opts.get is True: + print_ok(pubnub.get_channel_array()) def do_exit(self, args): kill_all_threads() -- cgit v1.2.3 From 8a642ab92c537c84960ef3943b34aac95bc39121 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 2 May 2014 01:58:21 +0530 Subject: modifications for susbcribe loop events, connect, disconnect, reconnect --- python/examples/console.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 240e5c0..fd9ebf4 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -127,7 +127,17 @@ def _subscribe_command_handler(channel): def _error(r): print_error(r, channel) - pubnub.subscribe(channel, _callback, _error) + + def _disconnect(r): + print_error("DISCONNECTED", channel) + + def _reconnect(r): + print_error("RECONNECTED", channel) + + def _connect(r): + print_error("CONNECTED", channel) + + pubnub.subscribe(channel, _callback, _error,connect=_connect, disconnect=_disconnect, reconnect=_reconnect) def _unsubscribe_command_handler(channel): -- cgit v1.2.3 From ca29b41c781c3a9861141811b208432fbda8aa0a Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 2 May 2014 20:19:57 +0530 Subject: enahancements to dev console --- python/examples/console.py | 50 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index fd9ebf4..d43ee80 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -129,13 +129,13 @@ def _subscribe_command_handler(channel): print_error(r, channel) def _disconnect(r): - print_error("DISCONNECTED", channel) + print_error("DISCONNECTED", r) def _reconnect(r): - print_error("RECONNECTED", channel) + print_error("RECONNECTED", r) def _connect(r): - print_error("CONNECTED", channel) + print_error("CONNECTED", r) pubnub.subscribe(channel, _callback, _error,connect=_connect, disconnect=_disconnect, reconnect=_reconnect) @@ -216,16 +216,47 @@ class DevConsole(Cmd): self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") - self.prompt = "(PubNub Console) [" + color.colorize(pubnub.get_origin(),"blue") + "] > " + self.prompt = self.get_prompt() + + def get_channel_origin(self): + cho = " [" + channels = pubnub.get_channel_array() + channels_str = ",".join(channels) + if len(channels) > 3: + cho += ",".join(channels[:3]) + " " + str(len(channels) - 3) + " more..." + else: + cho += ",".join(channels) + + if len(channels) > 0: + cho = color.colorize(cho,"bold") + "@" + + return cho + color.colorize(pubnub.get_origin(),"blue") + "] > " + + def get_prompt(self): + prompt = color.colorize("[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] ", "magenta") + if self.default_channel is not None and len(self.default_channel) > 0: + prompt += " [default channel: " + color.colorize(self.default_channel,"bold") + "]" + + prompt += self.get_channel_origin() + return prompt + + def precmd(self, line): + self.prompt = self.get_prompt() + return line + + def emptyline(self): + print('empty line') + self.prompt = get_date() + " [" + color.colorize(pubnub.get_origin(),"blue") + "] > " def cmdloop_with_keyboard_interrupt(self): try: self.cmdloop() - except KeyboardInterrupt: - sys.stdout.write('\n') - kill_all_threads() - + except KeyboardInterrupt as e: + pass + sys.stdout.write('\n') + kill_all_threads() @options([make_option('-p', '--publish-key', action="store", default="demo", help="Publish Key"), make_option('-s', '--subscribe-key', action="store", default="demo", help="Subscribe Key"), @@ -268,6 +299,7 @@ class DevConsole(Cmd): print_error("Missing channel") return self.default_channel = opts.channel + self.prompt = self.get_prompt() @options([make_option('-f', '--file', action="store", default="./pubnub-console.log", help="Output file") ]) @@ -375,6 +407,7 @@ class DevConsole(Cmd): print_error("Missing channel") return _unsubscribe_command_handler(opts.channel) + self.prompt = self.get_prompt() @options([make_option('-c', '--channel', action="store", help="Channel for subscribe"), @@ -392,6 +425,7 @@ class DevConsole(Cmd): if opts.get is True: print_ok(pubnub.get_channel_array()) + self.prompt = self.get_prompt() def do_exit(self, args): kill_all_threads() -- cgit v1.2.3 From e0207efea24574bc6dac3e0aadb2d53cebe2a307 Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 2 May 2014 22:45:17 +0530 Subject: console enhancements --- python/examples/console.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index d43ee80..3041a02 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -122,11 +122,11 @@ def _publish_command_handler(channel, message,async=False): def _subscribe_command_handler(channel): - def _callback(r): - print_ok(r, channel) + def _callback(r,ch): + print_ok(r, ch) - def _error(r): - print_error(r, channel) + def _error(r,ch=None): + print_error(r, ch if ch is not None else channel) def _disconnect(r): print_error("DISCONNECTED", r) -- cgit v1.2.3 From 57d27fe29751f9cbd14a26d2a4ee8402168bfe8b Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 2 May 2014 23:14:10 +0530 Subject: fixing start-console.sh --- python/examples/start-console.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh index 2df3f77..128a20e 100644 --- a/python/examples/start-console.sh +++ b/python/examples/start-console.sh @@ -5,7 +5,7 @@ if ! type "screen" > /dev/null; then fi rm ./pubnub-console.log touch ./pubnub-console.log -set PYTHONPATH=../.. +export PYTHONPATH=../.. screen -X -S pubnub-console quit 2>&1 > /dev/null OS="`uname`" case $OS in -- cgit v1.2.3 From fc9ef45293540a2a5ff8f6dde5481442f4349f0c Mon Sep 17 00:00:00 2001 From: Devendra Date: Sat, 3 May 2014 00:23:55 +0530 Subject: adding virtualenv creation and installation of dependencies to start-console --- python/examples/start-console.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) mode change 100644 => 100755 python/examples/start-console.sh (limited to 'python/examples') diff --git a/python/examples/start-console.sh b/python/examples/start-console.sh old mode 100644 new mode 100755 index 128a20e..a928cb3 --- a/python/examples/start-console.sh +++ b/python/examples/start-console.sh @@ -1,4 +1,26 @@ #!/bin/bash + +#!/bin/bash -e + +BASEDIR=. + +if [ ! -d "$BASEDIR/ve" ]; then + virtualenv -q $BASEDIR/ve --no-site-packages + $BASEDIR/ve/bin/activate + echo "Virtualenv created." +fi + +chmod 755 $BASEDIR/ve/bin/activate +$BASEDIR/ve/bin/activate + +if [ ! -f "$BASEDIR/ve/updated" -o $BASEDIR/requirements.pip -nt $BASEDIR/ve/updated ]; then + pip install -r $BASEDIR/requirements.pip -E $BASEDIR/ve + touch $BASEDIR/ve/updated + echo "Requirements installed." +fi + + + if ! type "screen" > /dev/null; then echo "[ERROR] Screen is not installed. Please install screen to use this utility ." exit -- cgit v1.2.3 From ab0597888580855ae8b75ad346a9d20b76027af9 Mon Sep 17 00:00:00 2001 From: Devendra Date: Sat, 3 May 2014 00:29:22 +0530 Subject: adding requirements.pip --- python/examples/requirements.pip | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 python/examples/requirements.pip (limited to 'python/examples') diff --git a/python/examples/requirements.pip b/python/examples/requirements.pip new file mode 100644 index 0000000..738c606 --- /dev/null +++ b/python/examples/requirements.pip @@ -0,0 +1,3 @@ +pycrypto==2.6.1 +cmd2==0.6.7 +requests==2.2.1 -- cgit v1.2.3 From 2c4281c1ac254bd3915b44820f7d39c0ab0b1721 Mon Sep 17 00:00:00 2001 From: Devendra Date: Sun, 4 May 2014 23:25:22 +0530 Subject: adding help message --- python/examples/console-help.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/console-help.txt b/python/examples/console-help.txt index 55debd2..abe92c8 100644 --- a/python/examples/console-help.txt +++ b/python/examples/console-help.txt @@ -1,6 +1,9 @@ ********************** HELP ****************************** -TO EXIT . Ctrl-A \ followed by y +TO EXIT : +Ctrl-A \ followed by y ( on linux ) +Ctrl-A Ctrl-\ followed by y ( on mac osx ) + TO MOVE BETWEEN PANES . Ctrl-A TAB ********************************************************** -- cgit v1.2.3 From 3b60b175b085fbf474ca34069025f04633aa072e Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 6 May 2014 14:20:16 +0530 Subject: console.py --- python/examples/console.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 3041a02..8f87a31 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -140,14 +140,20 @@ def _subscribe_command_handler(channel): pubnub.subscribe(channel, _callback, _error,connect=_connect, disconnect=_disconnect, reconnect=_reconnect) -def _unsubscribe_command_handler(channel): +def _unsubscribe_command_handler(channels): def _callback(r): print_ok(r) def _error(r): print_error(r) - pubnub.unsubscribe(channel) + if not isinstance(channels,list): + ch = [] + ch.append(channels) + channels = ch + + for channel in channels: + pubnub.unsubscribe(channel) def _grant_command_handler(channel, auth_key, read, write, ttl,async=False): @@ -230,7 +236,9 @@ class DevConsole(Cmd): if len(channels) > 0: cho = color.colorize(cho,"bold") + "@" - return cho + color.colorize(pubnub.get_origin(),"blue") + "] > " + origin = pubnub.get_origin().split("://")[1] + origin += color.colorize(" (SSL)","green") if pubnub.get_origin().split("://")[0] == "https" else "" + return cho + color.colorize(origin,"blue") + "] > " def get_prompt(self): @@ -277,7 +285,7 @@ class DevConsole(Cmd): opts.ssl, opts.origin, opts.uuid) - self.prompt = "(PubNub Console) [" + color.colorize(pubnub.get_origin(),"blue") + "] > " + self.prompt = self.get_prompt() def do_set_sync(self, command): @@ -399,10 +407,14 @@ class DevConsole(Cmd): _audit_command_handler(opts.channel, opts.auth_key,async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe") + @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe"), + make_option('-a', '--all', action="store_true", dest="all", + default=False, help="Unsubscribe from all channels") ]) def do_unsubscribe(self, command, opts): opts.channel = self.default_channel if opts.channel is None else opts.channel + if (opts.all is True): + opts.channel = pubnub.get_channel_array() if opts.channel is None: print_error("Missing channel") return -- cgit v1.2.3 From cc39ff042c3c7c7d35819e33a5d4d58acdf89b67 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 6 May 2014 15:03:54 +0530 Subject: additions to console --- python/examples/console.py | 47 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 8f87a31..1f25eb6 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -212,6 +212,14 @@ def kill_all_threads(): thread._Thread__stop() +def get_date(full=False): + if full is True: + return color.colorize("[" + datetime.now().strftime( + '%Y-%m-%d %H:%M:%S') + "] ", "magenta") + else: + return color.colorize("[" + datetime.now().strftime( + '%H:%M:%S') + "] ", "magenta") + class DevConsole(Cmd): @@ -222,14 +230,18 @@ class DevConsole(Cmd): self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") + self.full_date = False + self.channel_truncation = 3 self.prompt = self.get_prompt() + def get_channel_origin(self): cho = " [" channels = pubnub.get_channel_array() channels_str = ",".join(channels) - if len(channels) > 3: - cho += ",".join(channels[:3]) + " " + str(len(channels) - 3) + " more..." + sl = self.channel_truncation + if len(channels) > 0 and sl > 0: + cho += ",".join(channels[:int(sl)]) + " " + str(len(channels) - int(sl)) + " more..." else: cho += ",".join(channels) @@ -242,8 +254,8 @@ class DevConsole(Cmd): def get_prompt(self): - prompt = color.colorize("[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] ", "magenta") + prompt = get_date(self.full_date) + if self.default_channel is not None and len(self.default_channel) > 0: prompt += " [default channel: " + color.colorize(self.default_channel,"bold") + "]" @@ -298,6 +310,33 @@ class DevConsole(Cmd): Set Async mode""" self.async = True + @options([make_option('-n', '--count', action="store", default=3, help="Number of channels on prompt") + ]) + def do_set_channel_truncation(self, command, opts): + """set_channel_truncation + Set Channel Truncation""" + + self.channel_truncation = opts.count + + self.prompt = self.get_prompt() + + def do_unset_channel_truncation(self, command): + """unset_channel_truncation + Unset Channel Truncation""" + self.channel_truncation = 0 + self.prompt = self.get_prompt() + + def do_set_full_date(self, command): + """do_set_full_date + Set Full Date""" + self.full_date = True + self.prompt = self.get_prompt() + + def do_unset_full_date(self, command): + """do_unset_full_date + Unset Full Date""" + self.full_date = False + self.prompt = self.get_prompt() @options([make_option('-c', '--channel', action="store", help="Default Channel") ]) -- cgit v1.2.3 From cf1021b3671fb7537ad7b3a4d577ef0fcace694a Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 6 May 2014 16:43:09 +0530 Subject: modifying examples --- python/examples/here-now-example.py | 32 ----------------- python/examples/here-now.py | 36 +++++++++++++++++++ python/examples/history-example.py | 12 ------- python/examples/history.py | 34 ++++++++++++++++++ python/examples/publish-example.py | 44 ----------------------- python/examples/publish.py | 37 +++++++++++++++++++ python/examples/subscribe-example.py | 70 ------------------------------------ python/examples/subscribe.py | 46 ++++++++++++++++++++++++ 8 files changed, 153 insertions(+), 158 deletions(-) delete mode 100644 python/examples/here-now-example.py create mode 100644 python/examples/here-now.py delete mode 100755 python/examples/history-example.py create mode 100644 python/examples/history.py delete mode 100755 python/examples/publish-example.py create mode 100644 python/examples/publish.py delete mode 100755 python/examples/subscribe-example.py create mode 100644 python/examples/subscribe.py (limited to 'python/examples') diff --git a/python/examples/here-now-example.py b/python/examples/here-now-example.py deleted file mode 100644 index 0bc3015..0000000 --- a/python/examples/here-now-example.py +++ /dev/null @@ -1,32 +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/ - - -import sys -from Pubnub import PubnubAsync 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) -crazy = 'hello_world' - - -def print_cb(message): - print(message) - -pubnub.here_now({ - 'channel': crazy, - 'callback': print_cb -}) diff --git a/python/examples/here-now.py b/python/examples/here-now.py new file mode 100644 index 0000000..f573389 --- /dev/null +++ b/python/examples/here-now.py @@ -0,0 +1,36 @@ +## 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 PubnubAsync 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' + + + +# Synchronous usage + +print pubnub.here_now(channel) + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.here_now(channel, callback=callback, error=callback) diff --git a/python/examples/history-example.py b/python/examples/history-example.py deleted file mode 100755 index 793c612..0000000 --- a/python/examples/history-example.py +++ /dev/null @@ -1,12 +0,0 @@ -import sys -from Pubnub import PubnubAsync as Pubnub - -## Initiat Class -pubnub = Pubnub('demo', 'demo', None, False) - -## History Example -history = pubnub.history({ - 'channel': 'hello_world', - 'limit': 1 -}) -print(history) diff --git a/python/examples/history.py b/python/examples/history.py new file mode 100644 index 0000000..3d6addf --- /dev/null +++ b/python/examples/history.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 PubnubAsync 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' + +# Synchronous usage + +print pubnub.history(channel, count=2) + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.history(channel, count=2 , callback=callback, error=callback) diff --git a/python/examples/publish-example.py b/python/examples/publish-example.py deleted file mode 100755 index 78b7f36..0000000 --- a/python/examples/publish-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/ - -import sys -from Pubnub import PubnubAsync 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 '' # (Cipher key is Optional) -auth_key = len( - sys.argv) > 5 and sys.argv[4] or 'abcd' # (Cipher key is Optional) -ssl_on = len(sys.argv) > 6 and bool(sys.argv[5]) or False - -## ----------------------------------------------------------------------- -## Initiate Pubnub State -## ----------------------------------------------------------------------- -pubnub = Pubnub( - publish_key, subscribe_key, secret_key, cipher_key, auth_key, ssl_on, pooling=True) -crazy = 'hello_world' - -## ----------------------------------------------------------------------- -## Publish Example -## ----------------------------------------------------------------------- - - -def publish_complete(info): - print(info) - - -def publish_error(info): - print('ERROR : ' + str(info)) - -import time -start = time.time() -for i in range(1,100): - print pubnub.publish(crazy, 'hello world-' + str(i)) -end = time.time() -print(end - start); diff --git a/python/examples/publish.py b/python/examples/publish.py new file mode 100644 index 0000000..029c17a --- /dev/null +++ b/python/examples/publish.py @@ -0,0 +1,37 @@ +## 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 PubnubAsync 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 !!!' + + + +# Synchronous usage + +print pubnub.publish(channel, message) + +# Asynchronous usage + +def callback(message): + print(message) + +pubnub.publish(channel, message, callback=callback, error=callback) diff --git a/python/examples/subscribe-example.py b/python/examples/subscribe-example.py deleted file mode 100755 index 9c16bbe..0000000 --- a/python/examples/subscribe-example.py +++ /dev/null @@ -1,70 +0,0 @@ -import sys -import threading -import time -import random -import string -from Pubnub import PubnubAsync as Pubnub - -## Initiate Class -pubnub = Pubnub('demo', 'demo', None, False) - -print("My UUID is: " + pubnub.uuid) - -channel = ''.join( - random.choice(string.ascii_letters + string.digits) for x in range(20)) - -## Subscribe Example - - -def receive(message): - print(message) - return False - - -def pres_event(message): - print(message) - return False - - -def subscribe(): - print("Listening for messages on '%s' channel..." % channel) - pubnub.subscribe({ - 'channel': channel, - 'callback': receive - }) - - -def presence(): - print("Listening for presence events on '%s' channel..." % channel) - pubnub.presence({ - 'channel': channel, - 'callback': pres_event - }) - - -def publish(): - print("Publishing a test message on '%s' channel..." % channel) - pubnub.publish({ - 'channel': channel, - 'message': {'text': 'foo bar'} - }) - -pres_thread = threading.Thread(target=presence) -pres_thread.daemon = True -pres_thread.start() - -sub_thread = threading.Thread(target=subscribe) -sub_thread.daemon = True -sub_thread.start() - -time.sleep(3) - -publish() - - -print("waiting for subscribes and presence") -pres_thread.join() - -print(pubnub.here_now({'channel': channel})) - -sub_thread.join() diff --git a/python/examples/subscribe.py b/python/examples/subscribe.py new file mode 100644 index 0000000..a410297 --- /dev/null +++ b/python/examples/subscribe.py @@ -0,0 +1,46 @@ +## 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 PubnubAsync 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) -- cgit v1.2.3 From 338ffccb4d6603a8af5951dda6fd1e1dd11473f9 Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 6 May 2014 20:04:19 +0530 Subject: changes for python 3 compatibility --- python/examples/console.py | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 1f25eb6..084c49a 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -20,9 +20,6 @@ import os import readline import rlcompleter -if sys.argv[0] == "screen": - print "screen" - historyPath = os.path.expanduser("~/.pubnub_console_history") def save_history(historyPath=historyPath): @@ -38,6 +35,34 @@ of=sys.stdout color = Cmd() +stop = None + +def stop_2(th): + th._Thread__stop() + +def stop_3(th): + th._stop() + +def print_console_2(of,message): + print >>of, message + +def print_console_3(of,message): + of.write(message) + of.write("\n") + +print_console = None + +if type(sys.version_info) is tuple: + print_console = print_console_2 + stop = stop_2 +else: + if sys.version_info.major == 2: + print_console = print_console_2 + stop = stop_2 + else: + print_console = print_console_3 + stop = stop_3 + def print_ok(msg, channel=None): if msg is None: return @@ -46,9 +71,9 @@ def print_ok(msg, channel=None): chstr += color.colorize("[Channel : " + channel + \ "] " if channel is not None else "", "cyan") try: - print >>of, (chstr + color.colorize(str(msg),"green")) + print_console(of, (chstr + color.colorize(str(msg),"green"))) except UnicodeEncodeError as e: - print >>of, (msg) + print_console(of, (msg)) of.flush() def print_error(msg, channel=None): @@ -59,9 +84,9 @@ def print_error(msg, channel=None): chstr += color.colorize("[Channel : " + channel + \ "] " if channel is not None else "", "cyan") try: - print >>of, (chstr + color.colorize(color.colorize(str(msg),"red"),"bold")) + print_console(of, (chstr + color.colorize(color.colorize(str(msg),"red"),"bold"))) except UnicodeEncodeError as e: - print >>of, (msg) + print_console(of, (msg)) of.flush() class DefaultPubnub(object): @@ -79,7 +104,7 @@ pubnub=DefaultPubnub() def kill_all_threads(): for thread in threading.enumerate(): if thread.isAlive(): - thread._Thread__stop() + stop(thread) def get_input(message, t=None): while True: @@ -209,7 +234,7 @@ def _here_now_command_handler(channel,async=False): def kill_all_threads(): for thread in threading.enumerate(): if thread.isAlive(): - thread._Thread__stop() + stop(thread) def get_date(full=False): @@ -240,7 +265,7 @@ class DevConsole(Cmd): channels = pubnub.get_channel_array() channels_str = ",".join(channels) sl = self.channel_truncation - if len(channels) > 0 and sl > 0: + if len(channels) > int(sl) and int(sl) > 0: cho += ",".join(channels[:int(sl)]) + " " + str(len(channels) - int(sl)) + " more..." else: cho += ",".join(channels) -- cgit v1.2.3 From 1b49e712e12ba833f460324b95969b162d464edf Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 7 May 2014 12:13:17 +0530 Subject: console changes and pep8 compliance --- python/examples/console.py | 38 +++++++++++++++++++++----------------- python/examples/here-now.py | 3 +-- python/examples/history.py | 5 +++-- python/examples/publish.py | 7 +++---- python/examples/subscribe.py | 11 +++++++---- 5 files changed, 35 insertions(+), 29 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 084c49a..342c70f 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -37,12 +37,16 @@ color = Cmd() stop = None +full_date = False + def stop_2(th): th._Thread__stop() def stop_3(th): th._stop() + + def print_console_2(of,message): print >>of, message @@ -63,11 +67,20 @@ else: print_console = print_console_3 stop = stop_3 + +def get_date(): + if full_date is True: + return color.colorize(datetime.now().strftime( + '%Y-%m-%d %H:%M:%S'), "magenta") + else: + return color.colorize(datetime.now().strftime( + '%H:%M:%S'), "magenta") + + def print_ok(msg, channel=None): if msg is None: return - chstr = color.colorize("[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] ","magenta") + chstr = color.colorize("[" + get_date() + "] ","magenta") chstr += color.colorize("[Channel : " + channel + \ "] " if channel is not None else "", "cyan") try: @@ -79,8 +92,7 @@ def print_ok(msg, channel=None): def print_error(msg, channel=None): if msg is None: return - chstr = color.colorize("[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] ", "magenta") + chstr = color.colorize("[" + get_date() + "] ", "magenta") chstr += color.colorize("[Channel : " + channel + \ "] " if channel is not None else "", "cyan") try: @@ -237,15 +249,6 @@ def kill_all_threads(): stop(thread) -def get_date(full=False): - if full is True: - return color.colorize("[" + datetime.now().strftime( - '%Y-%m-%d %H:%M:%S') + "] ", "magenta") - else: - return color.colorize("[" + datetime.now().strftime( - '%H:%M:%S') + "] ", "magenta") - - class DevConsole(Cmd): def __init__(self): @@ -255,7 +258,6 @@ class DevConsole(Cmd): self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") - self.full_date = False self.channel_truncation = 3 self.prompt = self.get_prompt() @@ -279,7 +281,7 @@ class DevConsole(Cmd): def get_prompt(self): - prompt = get_date(self.full_date) + prompt = "[" + get_date() + "]" if self.default_channel is not None and len(self.default_channel) > 0: prompt += " [default channel: " + color.colorize(self.default_channel,"bold") + "]" @@ -352,15 +354,17 @@ class DevConsole(Cmd): self.prompt = self.get_prompt() def do_set_full_date(self, command): + global full_date """do_set_full_date Set Full Date""" - self.full_date = True + full_date = True self.prompt = self.get_prompt() def do_unset_full_date(self, command): + global full_date """do_unset_full_date Unset Full Date""" - self.full_date = False + full_date = False self.prompt = self.get_prompt() @options([make_option('-c', '--channel', action="store", help="Default Channel") diff --git a/python/examples/here-now.py b/python/examples/here-now.py index f573389..d03a110 100644 --- a/python/examples/here-now.py +++ b/python/examples/here-now.py @@ -23,13 +23,12 @@ pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, channel = 'hello_world' - # Synchronous usage - print pubnub.here_now(channel) # Asynchronous usage + def callback(message): print(message) diff --git a/python/examples/history.py b/python/examples/history.py index 3d6addf..7f7466b 100644 --- a/python/examples/history.py +++ b/python/examples/history.py @@ -20,7 +20,7 @@ ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) -channel = 'a' +channel = 'a' # Synchronous usage @@ -28,7 +28,8 @@ print pubnub.history(channel, count=2) # Asynchronous usage + def callback(message): print(message) -pubnub.history(channel, count=2 , callback=callback, error=callback) +pubnub.history(channel, count=2, callback=callback, error=callback) diff --git a/python/examples/publish.py b/python/examples/publish.py index 029c17a..a1b913b 100644 --- a/python/examples/publish.py +++ b/python/examples/publish.py @@ -20,17 +20,16 @@ ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- 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 !!!' - +channel = 'hello_world' +message = 'Hello World !!!' # Synchronous usage - print pubnub.publish(channel, message) # Asynchronous usage + def callback(message): print(message) diff --git a/python/examples/subscribe.py b/python/examples/subscribe.py index a410297..6cf93b1 100644 --- a/python/examples/subscribe.py +++ b/python/examples/subscribe.py @@ -21,26 +21,29 @@ ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) -channel = 'a' - +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.subscribe(channel, callback=callback, error=callback, + connect=connect, reconnect=reconnect, disconnect=disconnect) -- cgit v1.2.3 From 4ab1fa41e1a10efc88909bceb78222ffb406145a Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 7 May 2014 13:01:21 +0530 Subject: pep 8 compliance --- python/examples/console.py | 314 +++++++++++++++++++++++++++------------------ 1 file changed, 188 insertions(+), 126 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 342c70f..674b6d4 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -22,6 +22,7 @@ import rlcompleter historyPath = os.path.expanduser("~/.pubnub_console_history") + def save_history(historyPath=historyPath): import readline readline.write_history_file(historyPath) @@ -31,7 +32,7 @@ if os.path.exists(historyPath): atexit.register(save_history) -of=sys.stdout +of = sys.stdout color = Cmd() @@ -39,18 +40,20 @@ stop = None full_date = False + def stop_2(th): th._Thread__stop() + def stop_3(th): th._stop() +def print_console_2(of, message): + print >>of, message -def print_console_2(of,message): - print >>of, message -def print_console_3(of,message): +def print_console_3(of, message): of.write(message) of.write("\n") @@ -72,45 +75,49 @@ def get_date(): if full_date is True: return color.colorize(datetime.now().strftime( '%Y-%m-%d %H:%M:%S'), "magenta") - else: + else: return color.colorize(datetime.now().strftime( - '%H:%M:%S'), "magenta") + '%H:%M:%S'), "magenta") def print_ok(msg, channel=None): if msg is None: return - chstr = color.colorize("[" + get_date() + "] ","magenta") - chstr += color.colorize("[Channel : " + channel + \ - "] " if channel is not None else "", "cyan") + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") try: - print_console(of, (chstr + color.colorize(str(msg),"green"))) + print_console(of, (chstr + color.colorize(str(msg), "green"))) except UnicodeEncodeError as e: print_console(of, (msg)) of.flush() + def print_error(msg, channel=None): if msg is None: return chstr = color.colorize("[" + get_date() + "] ", "magenta") - chstr += color.colorize("[Channel : " + channel + \ - "] " if channel is not None else "", "cyan") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") try: - print_console(of, (chstr + color.colorize(color.colorize(str(msg),"red"),"bold"))) + print_console(of, (chstr + color.colorize(color.colorize( + str(msg), "red"), "bold"))) except UnicodeEncodeError as e: print_console(of, (msg)) of.flush() + class DefaultPubnub(object): - def handlerFunctionClosure(self,name): - def handlerFunction(*args,**kwargs): - print_error("Pubnub not initialized. Use init command to initialize") + def handlerFunctionClosure(self, name): + def handlerFunction(*args, **kwargs): + print_error("Pubnub not initialized." + + "Use init command to initialize") return handlerFunction - def __getattr__(self,name): - return self.handlerFunctionClosure(name) -pubnub=DefaultPubnub() + def __getattr__(self, name): + return self.handlerFunctionClosure(name) +pubnub = DefaultPubnub() def kill_all_threads(): @@ -118,6 +125,7 @@ def kill_all_threads(): if thread.isAlive(): stop(thread) + def get_input(message, t=None): while True: try: @@ -148,21 +156,24 @@ def get_input(message, t=None): except ValueError: print_error("Invalid input : " + command) -def _publish_command_handler(channel, message,async=False): + +def _publish_command_handler(channel, message, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.publish(channel, message, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.publish(channel, message, + _callback if async is True else None, + _error if async is True else None)) def _subscribe_command_handler(channel): - def _callback(r,ch): + def _callback(r, ch): print_ok(r, ch) - def _error(r,ch=None): + def _error(r, ch=None): print_error(r, ch if ch is not None else channel) def _disconnect(r): @@ -174,7 +185,8 @@ def _subscribe_command_handler(channel): def _connect(r): print_error("CONNECTED", r) - pubnub.subscribe(channel, _callback, _error,connect=_connect, disconnect=_disconnect, reconnect=_reconnect) + pubnub.subscribe(channel, _callback, _error, connect=_connect, + disconnect=_disconnect, reconnect=_reconnect) def _unsubscribe_command_handler(channels): @@ -184,7 +196,7 @@ def _unsubscribe_command_handler(channels): def _error(r): print_error(r) - if not isinstance(channels,list): + if not isinstance(channels, list): ch = [] ch.append(channels) channels = ch @@ -193,54 +205,64 @@ def _unsubscribe_command_handler(channels): pubnub.unsubscribe(channel) -def _grant_command_handler(channel, auth_key, read, write, ttl,async=False): +def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.grant(channel, auth_key, read, write, ttl, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.grant(channel, auth_key, + read, write, ttl, + _callback if async is True else None, + _error if async is True else None)) -def _revoke_command_handler(channel, auth_key, ttl,async=False): +def _revoke_command_handler(channel, auth_key, ttl, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.revoke(channel, auth_key, ttl, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.revoke(channel, auth_key, ttl, + _callback if async is True else None, + _error if async is True else None)) -def _audit_command_handler(channel, auth_key,async=False): +def _audit_command_handler(channel, auth_key, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.audit(channel, auth_key, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.audit(channel, auth_key, + _callback if async is True else None, + _error if async is True else None)) -def _history_command_handler(channel, count,async=False): +def _history_command_handler(channel, count, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.history(channel, count, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.history(channel, count, + _callback if async is True else None, + _error if async is True else None)) -def _here_now_command_handler(channel,async=False): +def _here_now_command_handler(channel, async=False): def _callback(r): print_ok(r) def _error(r): print_error(r) - print_ok(pubnub.here_now(channel, _callback if async is True else None, _error if async is True else None)) + print_ok(pubnub.here_now(channel, _callback if async is True else None, + _error if async is True else None)) def kill_all_threads(): @@ -250,42 +272,44 @@ def kill_all_threads(): class DevConsole(Cmd): - + def __init__(self): Cmd.__init__(self) global pubnub - self.intro = "For Help type ? or help . To quit/exit type exit" ## defaults to None + self.intro = "For Help type ? or help . " + + "To quit/exit type exit" self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") self.channel_truncation = 3 self.prompt = self.get_prompt() - def get_channel_origin(self): cho = " [" channels = pubnub.get_channel_array() channels_str = ",".join(channels) sl = self.channel_truncation if len(channels) > int(sl) and int(sl) > 0: - cho += ",".join(channels[:int(sl)]) + " " + str(len(channels) - int(sl)) + " more..." + cho += ",".join(channels[:int(sl)]) + " " + str( + len(channels) - int(sl)) + " more..." else: cho += ",".join(channels) if len(channels) > 0: - cho = color.colorize(cho,"bold") + "@" + cho = color.colorize(cho, "bold") + "@" origin = pubnub.get_origin().split("://")[1] - origin += color.colorize(" (SSL)","green") if pubnub.get_origin().split("://")[0] == "https" else "" - return cho + color.colorize(origin,"blue") + "] > " - + origin += color.colorize(" (SSL)", "green") if pubnub.get_origin( + ).split("://")[0] == "https" else "" + return cho + color.colorize(origin, "blue") + "] > " def get_prompt(self): prompt = "[" + get_date() + "]" if self.default_channel is not None and len(self.default_channel) > 0: - prompt += " [default channel: " + color.colorize(self.default_channel,"bold") + "]" - + prompt += " [default channel: " + color.colorize( + self.default_channel, "bold") + "]" + prompt += self.get_channel_origin() return prompt @@ -295,7 +319,8 @@ class DevConsole(Cmd): def emptyline(self): print('empty line') - self.prompt = get_date() + " [" + color.colorize(pubnub.get_origin(),"blue") + "] > " + self.prompt = get_date() + " [" + color.colorize( + pubnub.get_origin(), "blue") + "] > " def cmdloop_with_keyboard_interrupt(self): try: @@ -305,28 +330,35 @@ class DevConsole(Cmd): sys.stdout.write('\n') kill_all_threads() - @options([make_option('-p', '--publish-key', action="store", default="demo", help="Publish Key"), - make_option('-s', '--subscribe-key', action="store", default="demo", help="Subscribe Key"), - make_option('-k', '--secret-key', action="store", default="demo", help="cipher Key"), - make_option('-c', '--cipher-key', action="store", default="", help="Secret Key"), - make_option('-a', '--auth-key', action="store", default=None, help="Auth Key"), - make_option('--ssl-on', dest='ssl', action='store_true', default=False, help="SSL Enabled ?"), - make_option('-o', '--origin', action="store", default="pubsub.pubnub.com", help="Origin"), - make_option('-u', '--uuid', action="store", default=None, help="UUID") - ]) + @options([make_option('-p', '--publish-key', action="store", + default="demo", help="Publish Key"), + make_option('-s', '--subscribe-key', action="store", + default="demo", help="Subscribe Key"), + make_option('-k', '--secret-key', action="store", + default="demo", help="cipher Key"), + make_option('-c', '--cipher-key', action="store", + default="", help="Secret Key"), + make_option('-a', '--auth-key', action="store", + default=None, help="Auth Key"), + make_option('--ssl-on', dest='ssl', action='store_true', + default=False, help="SSL Enabled ?"), + make_option('-o', '--origin', action="store", + default="pubsub.pubnub.com", help="Origin"), + make_option('-u', '--uuid', action="store", + default=None, help="UUID") + ]) def do_init(self, command, opts): global pubnub pubnub = Pubnub(opts.publish_key, - opts.subscribe_key, - opts.secret_key, - opts.cipher_key, - opts.auth_key, - opts.ssl, - opts.origin, - opts.uuid) + opts.subscribe_key, + opts.secret_key, + opts.cipher_key, + opts.auth_key, + opts.ssl, + opts.origin, + opts.uuid) self.prompt = self.get_prompt() - def do_set_sync(self, command): """unset_async Unset Async mode""" @@ -337,8 +369,9 @@ class DevConsole(Cmd): Set Async mode""" self.async = True - @options([make_option('-n', '--count', action="store", default=3, help="Number of channels on prompt") - ]) + @options([make_option('-n', '--count', action="store", + default=3, help="Number of channels on prompt") + ]) def do_set_channel_truncation(self, command, opts): """set_channel_truncation Set Channel Truncation""" @@ -367,8 +400,9 @@ class DevConsole(Cmd): full_date = False self.prompt = self.get_prompt() - @options([make_option('-c', '--channel', action="store", help="Default Channel") - ]) + @options([make_option('-c', '--channel', + action="store", help="Default Channel") + ]) def do_set_default_channel(self, command, opts): if opts.channel is None: @@ -377,42 +411,48 @@ class DevConsole(Cmd): self.default_channel = opts.channel self.prompt = self.get_prompt() - @options([make_option('-f', '--file', action="store", default="./pubnub-console.log", help="Output file") - ]) + @options([make_option('-f', '--file', action="store", + default="./pubnub-console.log", help="Output file") + ]) def do_set_output_file(self, command, opts): global of try: - of = file(opts.file,'w+') + of = file(opts.file, 'w+') except IOError as e: print_error("Could not set output file. " + e.reason) - - @options([make_option('-c', '--channel', action="store", help="Channel for here now data") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel for here now data") + ]) def do_here_now(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return - _here_now_command_handler(opts.channel,async=self.async) + _here_now_command_handler(opts.channel, async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel for history data"), - make_option('-n', '--count', action="store", default=5, help="Number of messages") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel for history data"), + make_option('-n', '--count', action="store", + default=5, help="Number of messages") + ]) def do_get_history(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return - _history_command_handler(opts.channel, opts.count,async=self.async) - + _history_command_handler(opts.channel, opts.count, async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel on which to publish") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel on which to publish") + ]) def do_publish(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return @@ -426,61 +466,81 @@ class DevConsole(Cmd): except ValueError as ve: message = str(command) - _publish_command_handler(opts.channel,message,async=self.async) - - @options([make_option('-c', '--channel', action="store", help="Channel on which to grant"), - make_option('-a', '--auth-key', dest="auth_key", action="store", - help="Auth Key"), - make_option('-r', '--read-enabled', dest='read', action='store_true', default=False, help="Read ?"), - make_option('-w', '--write-enabled', dest='write', action='store_true', default=False, help="Write ?"), - make_option('-t', '--ttl', action="store", default=5, help="TTL") - ]) + _publish_command_handler(opts.channel, message, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel on which to grant"), + make_option('-a', '--auth-key', dest="auth_key", + action="store", + help="Auth Key"), + make_option('-r', '--read-enabled', dest='read', + action='store_true', + default=False, help="Read ?"), + make_option('-w', '--write-enabled', dest='write', + action='store_true', + default=False, help="Write ?"), + make_option('-t', '--ttl', action="store", + default=5, help="TTL") + ]) def do_grant(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return - opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key - _grant_command_handler(opts.channel,opts.auth_key, opts.read, opts.write, opts.ttl,async=self.async) + _grant_command_handler(opts.channel, opts.auth_key, + opts.read, opts.write, + opts.ttl, async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), - make_option('-a', '--auth-key', dest="auth_key", action="store", - help="Auth Key"), - make_option('-t', '--ttl', action="store", default=5, help="TTL") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key"), + make_option('-t', '--ttl', action="store", + default=5, help="TTL") + ]) def do_revoke(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return - opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key - _revoke_command_handler(opts.channel,opts.auth_key, opts.ttl,async=self.async) + _revoke_command_handler( + opts.channel, opts.auth_key, opts.ttl, async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), - make_option('-a', '--auth-key', dest="auth_key", action="store", - help="Auth Key") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key") + ]) def do_audit(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts.channel is None: print_error("Missing channel") return - opts.auth_key = pubnub.auth_key if opts.auth_key is None else opts.auth_key - - _audit_command_handler(opts.channel, opts.auth_key,async=self.async) + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key + _audit_command_handler(opts.channel, opts.auth_key, async=self.async) - @options([make_option('-c', '--channel', action="store", help="Channel for unsubscribe"), - make_option('-a', '--all', action="store_true", dest="all", - default=False, help="Unsubscribe from all channels") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel for unsubscribe"), + make_option('-a', '--all', action="store_true", dest="all", + default=False, help="Unsubscribe from all channels") + ]) def do_unsubscribe(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if (opts.all is True): opts.channel = pubnub.get_channel_array() if opts.channel is None: @@ -489,13 +549,15 @@ class DevConsole(Cmd): _unsubscribe_command_handler(opts.channel) self.prompt = self.get_prompt() - - @options([make_option('-c', '--channel', action="store", help="Channel for subscribe"), - make_option('-g', '--get-channel-list', action="store_true", dest="get", - default=False, help="Get susbcribed channel list") - ]) + @options([make_option('-c', '--channel', action="store", + help="Channel for subscribe"), + make_option('-g', '--get-channel-list', action="store_true", + dest="get", + default=False, help="Get susbcribed channel list") + ]) def do_subscribe(self, command, opts): - opts.channel = self.default_channel if opts.channel is None else opts.channel + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel if opts is None: print_error("Missing argument") return @@ -518,10 +580,10 @@ class DevConsole(Cmd): def handler(self, signum, frame): kill_all_threads() + def main(): app = DevConsole() app.cmdloop_with_keyboard_interrupt() - -if __name__ == "__main__": - main() +if __name__ == "__main__": + main() -- cgit v1.2.3 From 8e3ee358718686a2292b555e1184eb817b2a051a Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 7 May 2014 17:16:11 +0530 Subject: added presence option to subscribe command --- python/examples/console.py | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 674b6d4..3d7ba38 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -203,6 +203,7 @@ def _unsubscribe_command_handler(channels): for channel in channels: pubnub.unsubscribe(channel) + pubnub.unsubscribe(channel + '-pnpres') def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): @@ -271,13 +272,23 @@ def kill_all_threads(): stop(thread) -class DevConsole(Cmd): +def get_channel_array(): + channels = pubnub.get_channel_array() + + for channel in channels: + if "-pnpres" in channel: + i = channels.index(channel.split("-pnpres")[0]) + channels[i] = channels[i] + color.colorize("(P)", "blue") + channels.remove(channel) + return channels + +class DevConsole(Cmd): def __init__(self): Cmd.__init__(self) global pubnub - self.intro = "For Help type ? or help . " + - "To quit/exit type exit" + self.intro = "For Help type ? or help . " + \ + "To quit/exit type exit" self.default_channel = None self.async = False pubnub = Pubnub("demo", "demo") @@ -286,7 +297,7 @@ class DevConsole(Cmd): def get_channel_origin(self): cho = " [" - channels = pubnub.get_channel_array() + channels = get_channel_array() channels_str = ",".join(channels) sl = self.channel_truncation if len(channels) > int(sl) and int(sl) > 0: @@ -318,7 +329,6 @@ class DevConsole(Cmd): return line def emptyline(self): - print('empty line') self.prompt = get_date() + " [" + color.colorize( pubnub.get_origin(), "blue") + "] > " @@ -553,7 +563,10 @@ class DevConsole(Cmd): help="Channel for subscribe"), make_option('-g', '--get-channel-list', action="store_true", dest="get", - default=False, help="Get susbcribed channel list") + default=False, help="Get susbcribed channel list"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Presence events ?") ]) def do_subscribe(self, command, opts): opts.channel = self.default_channel \ @@ -565,8 +578,11 @@ class DevConsole(Cmd): if opts.channel is not None: _subscribe_command_handler(opts.channel) + if opts.presence is True: + _subscribe_command_handler(opts.channel + '-pnpres') + if opts.get is True: - print_ok(pubnub.get_channel_array()) + print_ok(get_channel_array()) self.prompt = self.get_prompt() def do_exit(self, args): -- cgit v1.2.3 From 20f55f6d739451629c4d918319362962bee5a141 Mon Sep 17 00:00:00 2001 From: Devendra Date: Wed, 7 May 2014 18:21:27 +0530 Subject: adding presence channel option to grant and revoke --- python/examples/console.py | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 3d7ba38..7798340 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -328,9 +328,8 @@ class DevConsole(Cmd): self.prompt = self.get_prompt() return line - def emptyline(self): - self.prompt = get_date() + " [" + color.colorize( - pubnub.get_origin(), "blue") + "] > " + #def emptyline(self): + # self.prompt = self.get_prompt() def cmdloop_with_keyboard_interrupt(self): try: @@ -490,7 +489,10 @@ class DevConsole(Cmd): action='store_true', default=False, help="Write ?"), make_option('-t', '--ttl', action="store", - default=5, help="TTL") + default=5, help="TTL"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Grant on presence channel ?") ]) def do_grant(self, command, opts): opts.channel = self.default_channel \ @@ -506,12 +508,20 @@ class DevConsole(Cmd): opts.read, opts.write, opts.ttl, async=self.async) + if opts.presence is True: + _grant_command_handler(opts.channel + '-pnpres', opts.auth_key, + opts.read, opts.write, + opts.ttl, async=self.async) + @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), make_option('-a', '--auth-key', dest="auth_key", action="store", help="Auth Key"), make_option('-t', '--ttl', action="store", - default=5, help="TTL") + default=5, help="TTL"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Revoke on presence channel ?") ]) def do_revoke(self, command, opts): opts.channel = self.default_channel \ @@ -526,6 +536,11 @@ class DevConsole(Cmd): _revoke_command_handler( opts.channel, opts.auth_key, opts.ttl, async=self.async) + if opts.presence is True: + _revoke_command_handler( + opts.channel + '-pnpres', opts.auth_key, + opts.ttl, async=self.async) + @options([make_option('-c', '--channel', action="store", help="Channel on which to revoke"), make_option('-a', '--auth-key', dest="auth_key", action="store", @@ -589,12 +604,12 @@ class DevConsole(Cmd): kill_all_threads() return -1 - def do_EOF(self, args): - kill_all_threads() - return self.do_exit(args) + #def do_EOF(self, args): + # kill_all_threads() + # return self.do_exit(args) - def handler(self, signum, frame): - kill_all_threads() + #def handler(self, signum, frame): + # kill_all_threads() def main(): -- cgit v1.2.3 From 09dbc7589b35963be1835ed58dcfd09d4d5c3ccc Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 8 May 2014 04:08:48 +0530 Subject: adding packaging for pushing to pip --- .../dist/pubnub-console-3.5.0-beta.tar.gz | Bin 0 -> 4627 bytes python/examples/pubnub-console/pubnub-console | 622 +++++++++++++++++++++ python/examples/pubnub-console/setup.py | 26 + 3 files changed, 648 insertions(+) create mode 100644 python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz create mode 100644 python/examples/pubnub-console/pubnub-console create mode 100644 python/examples/pubnub-console/setup.py (limited to 'python/examples') diff --git a/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz b/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz new file mode 100644 index 0000000..39540f6 Binary files /dev/null and b/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz differ diff --git a/python/examples/pubnub-console/pubnub-console b/python/examples/pubnub-console/pubnub-console new file mode 100644 index 0000000..a12c77f --- /dev/null +++ b/python/examples/pubnub-console/pubnub-console @@ -0,0 +1,622 @@ +#!/usr/bin/env python + +## 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 PubnubAsync as Pubnub +import threading +from datetime import datetime + +from cmd2 import Cmd, make_option, options, Cmd2TestCase +import optparse +import json + +import atexit +import os +import readline +import rlcompleter + +historyPath = os.path.expanduser("~/.pubnub_console_history") + + +def save_history(historyPath=historyPath): + import readline + readline.write_history_file(historyPath) + +if os.path.exists(historyPath): + readline.read_history_file(historyPath) + +atexit.register(save_history) + +of = sys.stdout + +color = Cmd() + +stop = None + +full_date = False + + +def stop_2(th): + th._Thread__stop() + + +def stop_3(th): + th._stop() + + +def print_console_2(of, message): + print >>of, message + + +def print_console_3(of, message): + of.write(message) + of.write("\n") + +print_console = None + +if type(sys.version_info) is tuple: + print_console = print_console_2 + stop = stop_2 +else: + if sys.version_info.major == 2: + print_console = print_console_2 + stop = stop_2 + else: + print_console = print_console_3 + stop = stop_3 + + +def get_date(): + if full_date is True: + return color.colorize(datetime.now().strftime( + '%Y-%m-%d %H:%M:%S'), "magenta") + else: + return color.colorize(datetime.now().strftime( + '%H:%M:%S'), "magenta") + + +def print_ok(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + color.colorize(str(msg), "green"))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + of.flush() + + +def print_error(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + color.colorize(color.colorize( + str(msg), "red"), "bold"))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + of.flush() + + +class DefaultPubnub(object): + def handlerFunctionClosure(self, name): + def handlerFunction(*args, **kwargs): + print_error("Pubnub not initialized." + + "Use init command to initialize") + return handlerFunction + + def __getattr__(self, name): + return self.handlerFunctionClosure(name) + +pubnub = DefaultPubnub() + + +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + stop(thread) + + +def get_input(message, t=None): + while True: + try: + try: + command = raw_input(message) + except NameError: + command = input(message) + except KeyboardInterrupt: + return None + + command = command.strip() + + if command is None or len(command) == 0: + raise ValueError + + if t is not None and t == bool: + valid = ["True", "true", "1", 1, "y", "Y", "yes", "Yes", "YES"] + if command in valid: + return True + else: + return False + if t is not None: + command = t(command) + else: + command = eval("'" + command + "'") + + return command + except ValueError: + print_error("Invalid input : " + command) + + +def _publish_command_handler(channel, message, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + print_ok(pubnub.publish(channel, message, + _callback if async is True else None, + _error if async is True else None)) + + +def _subscribe_command_handler(channel): + + def _callback(r, ch): + print_ok(r, ch) + + def _error(r, ch=None): + print_error(r, ch if ch is not None else channel) + + def _disconnect(r): + print_error("DISCONNECTED", r) + + def _reconnect(r): + print_error("RECONNECTED", r) + + def _connect(r): + print_error("CONNECTED", r) + + pubnub.subscribe(channel, _callback, _error, connect=_connect, + disconnect=_disconnect, reconnect=_reconnect) + + +def _unsubscribe_command_handler(channels): + + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + if not isinstance(channels, list): + ch = [] + ch.append(channels) + channels = ch + + for channel in channels: + pubnub.unsubscribe(channel) + pubnub.unsubscribe(channel + '-pnpres') + + +def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + print_ok(pubnub.grant(channel, auth_key, + read, write, ttl, + _callback if async is True else None, + _error if async is True else None)) + + +def _revoke_command_handler(channel, auth_key, ttl, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + print_ok(pubnub.revoke(channel, auth_key, ttl, + _callback if async is True else None, + _error if async is True else None)) + + +def _audit_command_handler(channel, auth_key, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + print_ok(pubnub.audit(channel, auth_key, + _callback if async is True else None, + _error if async is True else None)) + + +def _history_command_handler(channel, count, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + print_ok(pubnub.history(channel, count, + _callback if async is True else None, + _error if async is True else None)) + + +def _here_now_command_handler(channel, async=False): + def _callback(r): + print_ok(r) + + def _error(r): + print_error(r) + + print_ok(pubnub.here_now(channel, _callback if async is True else None, + _error if async is True else None)) + + +def kill_all_threads(): + for thread in threading.enumerate(): + if thread.isAlive(): + stop(thread) + + +def get_channel_array(): + channels = pubnub.get_channel_array() + + for channel in channels: + if "-pnpres" in channel: + i = channels.index(channel.split("-pnpres")[0]) + channels[i] = channels[i] + color.colorize("(P)", "blue") + channels.remove(channel) + return channels + + +class DevConsole(Cmd): + def __init__(self): + Cmd.__init__(self) + global pubnub + self.intro = "For Help type ? or help . " + \ + "To quit/exit type exit" + self.default_channel = None + self.async = False + pubnub = Pubnub("demo", "demo") + self.channel_truncation = 3 + self.prompt = self.get_prompt() + + def get_channel_origin(self): + cho = " [" + channels = get_channel_array() + channels_str = ",".join(channels) + sl = self.channel_truncation + if len(channels) > int(sl) and int(sl) > 0: + cho += ",".join(channels[:int(sl)]) + " " + str( + len(channels) - int(sl)) + " more..." + else: + cho += ",".join(channels) + + if len(channels) > 0: + cho = color.colorize(cho, "bold") + "@" + + origin = pubnub.get_origin().split("://")[1] + origin += color.colorize(" (SSL)", "green") if pubnub.get_origin( + ).split("://")[0] == "https" else "" + return cho + color.colorize(origin, "blue") + "] > " + + def get_prompt(self): + prompt = "[" + get_date() + "]" + + if self.default_channel is not None and len(self.default_channel) > 0: + prompt += " [default channel: " + color.colorize( + self.default_channel, "bold") + "]" + + prompt += self.get_channel_origin() + return prompt + + def precmd(self, line): + self.prompt = self.get_prompt() + return line + + #def emptyline(self): + # self.prompt = self.get_prompt() + + def cmdloop_with_keyboard_interrupt(self): + try: + self.cmdloop() + except KeyboardInterrupt as e: + pass + sys.stdout.write('\n') + kill_all_threads() + + @options([make_option('-p', '--publish-key', action="store", + default="demo", help="Publish Key"), + make_option('-s', '--subscribe-key', action="store", + default="demo", help="Subscribe Key"), + make_option('-k', '--secret-key', action="store", + default="demo", help="cipher Key"), + make_option('-c', '--cipher-key', action="store", + default="", help="Secret Key"), + make_option('-a', '--auth-key', action="store", + default=None, help="Auth Key"), + make_option('--ssl-on', dest='ssl', action='store_true', + default=False, help="SSL Enabled ?"), + make_option('-o', '--origin', action="store", + default="pubsub.pubnub.com", help="Origin"), + make_option('-u', '--uuid', action="store", + default=None, help="UUID") + ]) + def do_init(self, command, opts): + global pubnub + pubnub = Pubnub(opts.publish_key, + opts.subscribe_key, + opts.secret_key, + opts.cipher_key, + opts.auth_key, + opts.ssl, + opts.origin, + opts.uuid) + self.prompt = self.get_prompt() + + def do_set_sync(self, command): + """unset_async + Unset Async mode""" + self.async = False + + def do_set_async(self, command): + """set_async + Set Async mode""" + self.async = True + + @options([make_option('-n', '--count', action="store", + default=3, help="Number of channels on prompt") + ]) + def do_set_channel_truncation(self, command, opts): + """set_channel_truncation + Set Channel Truncation""" + + self.channel_truncation = opts.count + + self.prompt = self.get_prompt() + + def do_unset_channel_truncation(self, command): + """unset_channel_truncation + Unset Channel Truncation""" + self.channel_truncation = 0 + self.prompt = self.get_prompt() + + def do_set_full_date(self, command): + global full_date + """do_set_full_date + Set Full Date""" + full_date = True + self.prompt = self.get_prompt() + + def do_unset_full_date(self, command): + global full_date + """do_unset_full_date + Unset Full Date""" + full_date = False + self.prompt = self.get_prompt() + + @options([make_option('-c', '--channel', + action="store", help="Default Channel") + ]) + def do_set_default_channel(self, command, opts): + + if opts.channel is None: + print_error("Missing channel") + return + self.default_channel = opts.channel + self.prompt = self.get_prompt() + + @options([make_option('-f', '--file', action="store", + default="./pubnub-console.log", help="Output file") + ]) + def do_set_output_file(self, command, opts): + global of + try: + of = file(opts.file, 'w+') + except IOError as e: + print_error("Could not set output file. " + e.reason) + + @options([make_option('-c', '--channel', action="store", + help="Channel for here now data") + ]) + def do_here_now(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + _here_now_command_handler(opts.channel, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel for history data"), + make_option('-n', '--count', action="store", + default=5, help="Number of messages") + ]) + def do_get_history(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + _history_command_handler(opts.channel, opts.count, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel on which to publish") + ]) + def do_publish(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + if command is None: + print_error("Missing message") + return + + try: + message = json.loads(str(command)) + except ValueError as ve: + message = str(command) + + _publish_command_handler(opts.channel, message, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel on which to grant"), + make_option('-a', '--auth-key', dest="auth_key", + action="store", + help="Auth Key"), + make_option('-r', '--read-enabled', dest='read', + action='store_true', + default=False, help="Read ?"), + make_option('-w', '--write-enabled', dest='write', + action='store_true', + default=False, help="Write ?"), + make_option('-t', '--ttl', action="store", + default=5, help="TTL"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Grant on presence channel ?") + ]) + def do_grant(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key + + _grant_command_handler(opts.channel, opts.auth_key, + opts.read, opts.write, + opts.ttl, async=self.async) + + if opts.presence is True: + _grant_command_handler(opts.channel + '-pnpres', opts.auth_key, + opts.read, opts.write, + opts.ttl, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key"), + make_option('-t', '--ttl', action="store", + default=5, help="TTL"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Revoke on presence channel ?") + ]) + def do_revoke(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key + + _revoke_command_handler( + opts.channel, opts.auth_key, opts.ttl, async=self.async) + + if opts.presence is True: + _revoke_command_handler( + opts.channel + '-pnpres', opts.auth_key, + opts.ttl, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel on which to revoke"), + make_option('-a', '--auth-key', dest="auth_key", action="store", + help="Auth Key") + ]) + def do_audit(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts.channel is None: + print_error("Missing channel") + return + + opts.auth_key = pubnub.auth_key \ + if opts.auth_key is None else opts.auth_key + + _audit_command_handler(opts.channel, opts.auth_key, async=self.async) + + @options([make_option('-c', '--channel', action="store", + help="Channel for unsubscribe"), + make_option('-a', '--all', action="store_true", dest="all", + default=False, help="Unsubscribe from all channels") + ]) + def do_unsubscribe(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if (opts.all is True): + opts.channel = pubnub.get_channel_array() + if opts.channel is None: + print_error("Missing channel") + return + _unsubscribe_command_handler(opts.channel) + self.prompt = self.get_prompt() + + @options([make_option('-c', '--channel', action="store", + help="Channel for subscribe"), + make_option('-g', '--get-channel-list', action="store_true", + dest="get", + default=False, help="Get susbcribed channel list"), + make_option('-p', '--presence', action="store_true", + dest="presence", + default=False, help="Presence events ?") + ]) + def do_subscribe(self, command, opts): + opts.channel = self.default_channel \ + if opts.channel is None else opts.channel + if opts is None: + print_error("Missing argument") + return + + if opts.channel is not None: + _subscribe_command_handler(opts.channel) + + if opts.presence is True: + _subscribe_command_handler(opts.channel + '-pnpres') + + if opts.get is True: + print_ok(get_channel_array()) + self.prompt = self.get_prompt() + + def do_exit(self, args): + kill_all_threads() + return -1 + + #def do_EOF(self, args): + # kill_all_threads() + # return self.do_exit(args) + + #def handler(self, signum, frame): + # kill_all_threads() + + +def main(): + app = DevConsole() + app.cmdloop_with_keyboard_interrupt() + +if __name__ == "__main__": + main() diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py new file mode 100644 index 0000000..1ef09be --- /dev/null +++ b/python/examples/pubnub-console/setup.py @@ -0,0 +1,26 @@ +from setuptools import setup, find_packages + +setup( + name='pubnub-console', + version='3.5.0-beta', + description='PubNub Developer Console', + author='Stephen Blum', + author_email='support@pubnub.com', + url='http://pubnub.s3.amazonaws.com/pip/pubnub-3.3.5.tar.gz', + scripts=['pubnub-console'], + license='MIT', + classifiers=( + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Programming Language :: Python', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Topic :: Internet :: WWW/HTTP', + 'Topic :: Software Development :: Libraries :: Python Modules', + ), + install_requires=[ + 'pubnub==3.5.0-beta', + 'cmd2>=0.6.7', + ], + zip_safe=False, +) -- cgit v1.2.3 From 1607828ef5d2ef6c3ce357f83f53ea109be02182 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 8 May 2014 04:12:28 +0530 Subject: updating package urls --- .../dist/pubnub-console-3.5.0-beta.tar.gz | Bin 4627 -> 4647 bytes python/examples/pubnub-console/setup.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz b/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz index 39540f6..278e9fa 100644 Binary files a/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz and b/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz differ diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py index 1ef09be..d46314e 100644 --- a/python/examples/pubnub-console/setup.py +++ b/python/examples/pubnub-console/setup.py @@ -6,7 +6,7 @@ setup( description='PubNub Developer Console', author='Stephen Blum', author_email='support@pubnub.com', - url='http://pubnub.s3.amazonaws.com/pip/pubnub-3.3.5.tar.gz', + url='https://github.com/pubnub/python/raw/async/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz', scripts=['pubnub-console'], license='MIT', classifiers=( -- cgit v1.2.3 From 9dda9200997330b686bdb26495bed1023a1d8f7e Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 15 May 2014 12:06:49 +0530 Subject: adding sync and async tests for grant and revoke --- python/examples/console.py | 2 +- python/examples/here-now.py | 2 +- python/examples/history.py | 2 +- python/examples/publish.py | 2 +- python/examples/pubnub-console/pubnub-console | 2 +- python/examples/subscribe.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 7798340..5d74517 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -7,7 +7,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +from Pubnub import Pubnub import threading from datetime import datetime diff --git a/python/examples/here-now.py b/python/examples/here-now.py index d03a110..9640cc5 100644 --- a/python/examples/here-now.py +++ b/python/examples/here-now.py @@ -7,7 +7,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +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' diff --git a/python/examples/history.py b/python/examples/history.py index 7f7466b..603a0f8 100644 --- a/python/examples/history.py +++ b/python/examples/history.py @@ -7,7 +7,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +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' diff --git a/python/examples/publish.py b/python/examples/publish.py index a1b913b..594e7c4 100644 --- a/python/examples/publish.py +++ b/python/examples/publish.py @@ -7,7 +7,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +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' diff --git a/python/examples/pubnub-console/pubnub-console b/python/examples/pubnub-console/pubnub-console index a12c77f..7276fb9 100644 --- a/python/examples/pubnub-console/pubnub-console +++ b/python/examples/pubnub-console/pubnub-console @@ -9,7 +9,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +from Pubnub import Pubnub import threading from datetime import datetime diff --git a/python/examples/subscribe.py b/python/examples/subscribe.py index 6cf93b1..9b8b223 100644 --- a/python/examples/subscribe.py +++ b/python/examples/subscribe.py @@ -7,7 +7,7 @@ import sys -from Pubnub import PubnubAsync as Pubnub +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' -- cgit v1.2.3 From 26aca4f6f2c6167d5a83be83d1185c54522834e8 Mon Sep 17 00:00:00 2001 From: Devendra Date: Thu, 22 May 2014 20:42:40 +0530 Subject: removing requirement of adding channel for grant and audit --- python/examples/console.py | 9 --------- 1 file changed, 9 deletions(-) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 5d74517..6147d21 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -497,9 +497,6 @@ class DevConsole(Cmd): def do_grant(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key @@ -526,9 +523,6 @@ class DevConsole(Cmd): def do_revoke(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key @@ -549,9 +543,6 @@ class DevConsole(Cmd): def do_audit(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key -- cgit v1.2.3 From b60f421b301abf348ab887991809966bbb66087c Mon Sep 17 00:00:00 2001 From: Devendra Date: Fri, 23 May 2014 20:52:10 +0530 Subject: adding success message after unsubscribe --- python/examples/console.py | 1 + 1 file changed, 1 insertion(+) (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index 6147d21..f67e168 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -204,6 +204,7 @@ def _unsubscribe_command_handler(channels): for channel in channels: pubnub.unsubscribe(channel) pubnub.unsubscribe(channel + '-pnpres') + print_ok('Unsubscribed from : ' + str(channels)) def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): -- cgit v1.2.3 From 75033e11a429b52b0366d63bdd8f81b795a7145d Mon Sep 17 00:00:00 2001 From: Devendra Date: Sun, 15 Jun 2014 10:23:16 +0530 Subject: fixing customer issue, making changes to dev console to print pretty --- python/examples/console.py | 111 +++++++++++++++++---- .../dist/pubnub-console-3.5.0-beta.tar.gz | Bin 4647 -> 0 bytes python/examples/pubnub-console/setup.py | 5 +- 3 files changed, 97 insertions(+), 19 deletions(-) delete mode 100644 python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz (limited to 'python/examples') diff --git a/python/examples/console.py b/python/examples/console.py index f67e168..bf82b5f 100644 --- a/python/examples/console.py +++ b/python/examples/console.py @@ -20,6 +20,17 @@ import os import readline import rlcompleter +import pygments +from pygments.lexers import JsonLexer +from pygments.formatters import TerminalFormatter + +lexer = JsonLexer() +formatter = TerminalFormatter() +def highlight(msg): + return pygments.highlight(msg, lexer, formatter) + + + historyPath = os.path.expanduser("~/.pubnub_console_history") @@ -79,8 +90,7 @@ def get_date(): return color.colorize(datetime.now().strftime( '%H:%M:%S'), "magenta") - -def print_ok(msg, channel=None): +def print_ok_normal(msg, channel=None): if msg is None: return chstr = color.colorize("[" + get_date() + "] ", "magenta") @@ -90,10 +100,11 @@ def print_ok(msg, channel=None): print_console(of, (chstr + color.colorize(str(msg), "green"))) except UnicodeEncodeError as e: print_console(of, (msg)) + of.flush() -def print_error(msg, channel=None): +def print_error_normal(msg, channel=None): if msg is None: return chstr = color.colorize("[" + get_date() + "] ", "magenta") @@ -106,6 +117,37 @@ def print_error(msg, channel=None): print_console(of, (msg)) of.flush() +def print_ok_pretty(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + highlight(json.dumps(msg, indent=2)))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + + of.flush() + + +def print_error_pretty(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + color.colorize(color.colorize( + "ERROR: ", "red"), "bold") + + highlight(json.dumps(msg, indent=2)))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + of.flush() + +print_ok = print_ok_pretty +print_error = print_error_pretty + class DefaultPubnub(object): def handlerFunctionClosure(self, name): @@ -295,6 +337,15 @@ class DevConsole(Cmd): pubnub = Pubnub("demo", "demo") self.channel_truncation = 3 self.prompt = self.get_prompt() + self.publish_key = "demo" + self.subscribe_key = "demo" + self.origin = "pubsub.pubnub.com" + self.auth_key = None + self.cipher_key = None + self.secret_key = "demo" + self.ssl = False + self.uuid = None + self.disable_pretty = False def get_channel_origin(self): cho = " [" @@ -341,34 +392,60 @@ class DevConsole(Cmd): kill_all_threads() @options([make_option('-p', '--publish-key', action="store", - default="demo", help="Publish Key"), + default=None, help="Publish Key"), make_option('-s', '--subscribe-key', action="store", - default="demo", help="Subscribe Key"), + default=None, help="Subscribe Key"), make_option('-k', '--secret-key', action="store", - default="demo", help="cipher Key"), + default=None, help="cipher Key"), make_option('-c', '--cipher-key', action="store", - default="", help="Secret Key"), + default=None, help="Secret Key"), make_option('-a', '--auth-key', action="store", default=None, help="Auth Key"), make_option('--ssl-on', dest='ssl', action='store_true', default=False, help="SSL Enabled ?"), make_option('-o', '--origin', action="store", - default="pubsub.pubnub.com", help="Origin"), + default=None, help="Origin"), make_option('-u', '--uuid', action="store", - default=None, help="UUID") + default=None, help="UUID"), + make_option('--disable-pretty-print', dest='disable_pretty', action='store_true', + default=False, help="Disable Pretty Print ?") ]) def do_init(self, command, opts): global pubnub - pubnub = Pubnub(opts.publish_key, - opts.subscribe_key, - opts.secret_key, - opts.cipher_key, - opts.auth_key, - opts.ssl, - opts.origin, - opts.uuid) + global print_ok + global print_error + global print_ok_normal + global print_error_normal + global print_error_pretty + global print_ok_pretty + + self.publish_key = opts.publish_key if opts.publish_key is not None else self.publish_key + self.subscribe_key = opts.subscribe_key if opts.subscribe_key is not None else self.subscribe_key + self.secret_key = opts.secret_key if opts.secret_key is not None else self.secret_key + self.cipher_key = opts.cipher_key if opts.cipher_key is not None else self.cipher_key + self.auth_key = opts.auth_key if opts.auth_key is not None else self.auth_key + self.origin = opts.origin if opts.origin is not None else self.origin + self.uuid = opts.uuid if opts.uuid is not None else self.uuid + self.ssl = opts.ssl if opts.ssl is not None else self.ssl + self.disable_pretty = opts.disable_pretty if opts.disable_pretty is not None else self.disable_pretty + + pubnub = Pubnub(self.publish_key, + self.subscribe_key, + self.secret_key, + self.cipher_key, + self.auth_key, + self.ssl, + self.origin, + self.uuid) self.prompt = self.get_prompt() + if opts.disable_pretty is True: + print_ok = print_ok_normal + print_error = print_error_normal + else: + print_ok = print_ok_pretty + print_error = print_error_pretty + def do_set_sync(self, command): """unset_async Unset Async mode""" diff --git a/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz b/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz deleted file mode 100644 index 278e9fa..0000000 Binary files a/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz and /dev/null differ diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py index d46314e..e5a06ad 100644 --- a/python/examples/pubnub-console/setup.py +++ b/python/examples/pubnub-console/setup.py @@ -2,11 +2,11 @@ from setuptools import setup, find_packages setup( name='pubnub-console', - version='3.5.0-beta', + version='3.5.0-beta-1', description='PubNub Developer Console', author='Stephen Blum', author_email='support@pubnub.com', - url='https://github.com/pubnub/python/raw/async/python/examples/pubnub-console/dist/pubnub-console-3.5.0-beta.tar.gz', + url='http://pubnub.com', scripts=['pubnub-console'], license='MIT', classifiers=( @@ -21,6 +21,7 @@ setup( install_requires=[ 'pubnub==3.5.0-beta', 'cmd2>=0.6.7', + 'pygments >= 1.6' ], zip_safe=False, ) -- cgit v1.2.3 From 019d8f390dc6472a223e6ab9b2f159cd1cd20e4e Mon Sep 17 00:00:00 2001 From: Devendra Date: Sun, 15 Jun 2014 10:29:47 +0530 Subject: dev console modifications --- python/examples/pubnub-console/pubnub-console | 123 ++++++++++++++++++++------ 1 file changed, 95 insertions(+), 28 deletions(-) (limited to 'python/examples') diff --git a/python/examples/pubnub-console/pubnub-console b/python/examples/pubnub-console/pubnub-console index 7276fb9..bf82b5f 100644 --- a/python/examples/pubnub-console/pubnub-console +++ b/python/examples/pubnub-console/pubnub-console @@ -1,5 +1,3 @@ -#!/usr/bin/env python - ## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 @@ -22,6 +20,17 @@ import os import readline import rlcompleter +import pygments +from pygments.lexers import JsonLexer +from pygments.formatters import TerminalFormatter + +lexer = JsonLexer() +formatter = TerminalFormatter() +def highlight(msg): + return pygments.highlight(msg, lexer, formatter) + + + historyPath = os.path.expanduser("~/.pubnub_console_history") @@ -81,8 +90,7 @@ def get_date(): return color.colorize(datetime.now().strftime( '%H:%M:%S'), "magenta") - -def print_ok(msg, channel=None): +def print_ok_normal(msg, channel=None): if msg is None: return chstr = color.colorize("[" + get_date() + "] ", "magenta") @@ -92,10 +100,11 @@ def print_ok(msg, channel=None): print_console(of, (chstr + color.colorize(str(msg), "green"))) except UnicodeEncodeError as e: print_console(of, (msg)) + of.flush() -def print_error(msg, channel=None): +def print_error_normal(msg, channel=None): if msg is None: return chstr = color.colorize("[" + get_date() + "] ", "magenta") @@ -108,6 +117,37 @@ def print_error(msg, channel=None): print_console(of, (msg)) of.flush() +def print_ok_pretty(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + highlight(json.dumps(msg, indent=2)))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + + of.flush() + + +def print_error_pretty(msg, channel=None): + if msg is None: + return + chstr = color.colorize("[" + get_date() + "] ", "magenta") + chstr += color.colorize("[Channel : " + channel + + "] " if channel is not None else "", "cyan") + try: + print_console(of, (chstr + color.colorize(color.colorize( + "ERROR: ", "red"), "bold") + + highlight(json.dumps(msg, indent=2)))) + except UnicodeEncodeError as e: + print_console(of, (msg)) + of.flush() + +print_ok = print_ok_pretty +print_error = print_error_pretty + class DefaultPubnub(object): def handlerFunctionClosure(self, name): @@ -206,6 +246,7 @@ def _unsubscribe_command_handler(channels): for channel in channels: pubnub.unsubscribe(channel) pubnub.unsubscribe(channel + '-pnpres') + print_ok('Unsubscribed from : ' + str(channels)) def _grant_command_handler(channel, auth_key, read, write, ttl, async=False): @@ -296,6 +337,15 @@ class DevConsole(Cmd): pubnub = Pubnub("demo", "demo") self.channel_truncation = 3 self.prompt = self.get_prompt() + self.publish_key = "demo" + self.subscribe_key = "demo" + self.origin = "pubsub.pubnub.com" + self.auth_key = None + self.cipher_key = None + self.secret_key = "demo" + self.ssl = False + self.uuid = None + self.disable_pretty = False def get_channel_origin(self): cho = " [" @@ -342,34 +392,60 @@ class DevConsole(Cmd): kill_all_threads() @options([make_option('-p', '--publish-key', action="store", - default="demo", help="Publish Key"), + default=None, help="Publish Key"), make_option('-s', '--subscribe-key', action="store", - default="demo", help="Subscribe Key"), + default=None, help="Subscribe Key"), make_option('-k', '--secret-key', action="store", - default="demo", help="cipher Key"), + default=None, help="cipher Key"), make_option('-c', '--cipher-key', action="store", - default="", help="Secret Key"), + default=None, help="Secret Key"), make_option('-a', '--auth-key', action="store", default=None, help="Auth Key"), make_option('--ssl-on', dest='ssl', action='store_true', default=False, help="SSL Enabled ?"), make_option('-o', '--origin', action="store", - default="pubsub.pubnub.com", help="Origin"), + default=None, help="Origin"), make_option('-u', '--uuid', action="store", - default=None, help="UUID") + default=None, help="UUID"), + make_option('--disable-pretty-print', dest='disable_pretty', action='store_true', + default=False, help="Disable Pretty Print ?") ]) def do_init(self, command, opts): global pubnub - pubnub = Pubnub(opts.publish_key, - opts.subscribe_key, - opts.secret_key, - opts.cipher_key, - opts.auth_key, - opts.ssl, - opts.origin, - opts.uuid) + global print_ok + global print_error + global print_ok_normal + global print_error_normal + global print_error_pretty + global print_ok_pretty + + self.publish_key = opts.publish_key if opts.publish_key is not None else self.publish_key + self.subscribe_key = opts.subscribe_key if opts.subscribe_key is not None else self.subscribe_key + self.secret_key = opts.secret_key if opts.secret_key is not None else self.secret_key + self.cipher_key = opts.cipher_key if opts.cipher_key is not None else self.cipher_key + self.auth_key = opts.auth_key if opts.auth_key is not None else self.auth_key + self.origin = opts.origin if opts.origin is not None else self.origin + self.uuid = opts.uuid if opts.uuid is not None else self.uuid + self.ssl = opts.ssl if opts.ssl is not None else self.ssl + self.disable_pretty = opts.disable_pretty if opts.disable_pretty is not None else self.disable_pretty + + pubnub = Pubnub(self.publish_key, + self.subscribe_key, + self.secret_key, + self.cipher_key, + self.auth_key, + self.ssl, + self.origin, + self.uuid) self.prompt = self.get_prompt() + if opts.disable_pretty is True: + print_ok = print_ok_normal + print_error = print_error_normal + else: + print_ok = print_ok_pretty + print_error = print_error_pretty + def do_set_sync(self, command): """unset_async Unset Async mode""" @@ -499,9 +575,6 @@ class DevConsole(Cmd): def do_grant(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key @@ -528,9 +601,6 @@ class DevConsole(Cmd): def do_revoke(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key @@ -551,9 +621,6 @@ class DevConsole(Cmd): def do_audit(self, command, opts): opts.channel = self.default_channel \ if opts.channel is None else opts.channel - if opts.channel is None: - print_error("Missing channel") - return opts.auth_key = pubnub.auth_key \ if opts.auth_key is None else opts.auth_key -- cgit v1.2.3 From ac1ea5ddff5aa8615788ab784656b44d6a664100 Mon Sep 17 00:00:00 2001 From: Devendra Date: Sun, 15 Jun 2014 10:38:53 +0530 Subject: adding interpreter header --- python/examples/pubnub-console/pubnub-console | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python/examples') diff --git a/python/examples/pubnub-console/pubnub-console b/python/examples/pubnub-console/pubnub-console index bf82b5f..058253f 100644 --- a/python/examples/pubnub-console/pubnub-console +++ b/python/examples/pubnub-console/pubnub-console @@ -1,3 +1,5 @@ +#!/usr/bin/python + ## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 -- cgit v1.2.3 From 43162745c37f1e3f8f6b9c102f685a765f7fbc49 Mon Sep 17 00:00:00 2001 From: Devendra Date: Sun, 15 Jun 2014 10:44:12 +0530 Subject: changing dependencies --- python/examples/pubnub-console/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py index e5a06ad..c08be33 100644 --- a/python/examples/pubnub-console/setup.py +++ b/python/examples/pubnub-console/setup.py @@ -19,7 +19,7 @@ setup( 'Topic :: Software Development :: Libraries :: Python Modules', ), install_requires=[ - 'pubnub==3.5.0-beta', + 'pubnub==3.5.0-beta-1', 'cmd2>=0.6.7', 'pygments >= 1.6' ], -- cgit v1.2.3 From 819dbedf0904b81e866ea6d27219608167d8b8ca Mon Sep 17 00:00:00 2001 From: Devendra Date: Mon, 16 Jun 2014 23:40:07 +0530 Subject: version changes --- python/examples/pubnub-console/setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python/examples') diff --git a/python/examples/pubnub-console/setup.py b/python/examples/pubnub-console/setup.py index c08be33..a9fa506 100644 --- a/python/examples/pubnub-console/setup.py +++ b/python/examples/pubnub-console/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name='pubnub-console', - version='3.5.0-beta-1', + version='3.5.0', description='PubNub Developer Console', author='Stephen Blum', author_email='support@pubnub.com', @@ -19,7 +19,7 @@ setup( 'Topic :: Software Development :: Libraries :: Python Modules', ), install_requires=[ - 'pubnub==3.5.0-beta-1', + 'pubnub>=3.5.0', 'cmd2>=0.6.7', 'pygments >= 1.6' ], -- cgit v1.2.3 From 30202de8be4ba24f4fba8dda4b3f28f6ee6600aa Mon Sep 17 00:00:00 2001 From: Devendra Date: Tue, 17 Jun 2014 00:58:40 +0530 Subject: readme changes --- python/examples/dev-console.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python/examples') diff --git a/python/examples/dev-console.py b/python/examples/dev-console.py index 5bdbe8c..134d2e7 100755 --- a/python/examples/dev-console.py +++ b/python/examples/dev-console.py @@ -6,7 +6,7 @@ ## http://www.pubnub.com/ import sys -from Pubnub import PubnubAsync as Pubnub +from Pubnub import Pubnub from optparse import OptionParser -- cgit v1.2.3