class RemotePubNub(): def __init__(self, PUBNUB_PUBLISH_KEY="demo", PUBNUB_SUBSCRIBE_KEY="demo", queue=None): self.pubnub = Pubnub(publish_key=PUBNUB_PUBLISH_KEY, subscribe_key=PUBNUB_SUBSCRIBE_KEY) self.queue = queue def get_queue(self): return self.queue def publish(self, channel, message): self.pubnub.publish(channel, message) #logging.info("message published") def subscribe(self, channel): self.pubnub.subscribe( channel, callback=self.parse_command, error=self.sub_error, connect=self.sub_connect, disconnect=self.sub_disconnect) def parse_command(self, message, channel): if self.queue is not None: print message self.queue.put(message) def sub_error(message): logging.ERROR(message) def sub_connect(self, channel): message = 'Connected to: %s' % channel logging.info(message) def sub_disconnect(self, message): logging.info(message)
def push(cls, channel, message_dict): pubnub = Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, SECRET_KEY, False ) info = pubnub.publish({ 'channel' : channel, 'message' : json.dumps(message_dict) }) return info
def run(self, channel, latency, bufferSize): self.mutex = Lock() self.outqueuebuffers = {} self.outbuffers = {} self.senders = {} self.channels = None self.channel = channel self.buffer_size = bufferSize self.timestamp_buffer = [None] * self.buffer_size self.debug = False self.index = 0 self.offset = None self.latency = latency self.setupDone = False self.channel_count = 0 pubnub = Pubnub("pub-c-e655613e-f776-4301-9f29-f71edbcd6559", "sub-c-2eafcf66-c636-11e3-8dcd-02ee2ddab7fe", "sec-c-ZjUwZDgzMTItYzE2Mi00ZGYyLTg2NGMtNmE5N2Q3MGI0MTli", False) self.m = MQTT() broker = config.mqtt['Broker'] print("Connecting to broker: " + broker) self.m.connect(broker) while(True): pubnub.subscribe({ 'channel': self.channel, 'callback': self.setData })
def post_save(cls, sender, document, **kwargs): cfg = current_app.config pubnub = Pubnub( publish_key=cfg["PUBNUB_PUB_KEY"], subscribe_key=cfg["PUBNUB_SUB_KEY"], ssl_on=False, ) pubnub.publish(channel="globaldisaster", message=json.dumps(document.asdict()))
def main(): resetAVR() print("Establishing Connections...") pubnub = Pubnub(publish_key = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96', subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f', uuid = "pi") channel = 'leap2pi' GPIO.output(4, False) def _connect(m): print("Connected to PubNub!") GPIO.output(4, True) def _reconnect(m): print("Reconnected to PubNub!") GPIO.output(4, True) def _disconnect(m): print("Disconnected from PubNub!") GPIO.output(4, False) def _callback(m,n): left_byte = 0 right_byte = 0 # ==============================Left Hand============================== left_hand = m.get("left_hand",{}) if left_hand != {}: left_byte = handleLeft(left_hand) #print(left_hand) # ==============================Right Hand============================= right_hand = m.get("right_hand",{}) if right_hand != {}: right_byte= handleRight(right_hand) #print(right_hand) byte = left_byte | right_byte #print(byte) #====send i2c=====# try: bus.write_byte(0x47,byte) except IOError: print("Error!!!!") resetAVR() bus.write_byte(0x47,byte) #Catch and Print Error def _error(m): GPIO.output(4, False) print(m) #Subscribe to subchannel, set callback function to _callback and set error fucntion to _error pubnub.subscribe(channels=channel, callback=_callback, error=_error, connect=_connect, reconnect=_reconnect, disconnect=_disconnect)
def startStockPicker(server,port): global globalQueueRef #Step 1 - Initialize MongoDB & PubNub Connection mongoconn = pymongo.MongoClient(server,port) db = mongoconn.stockdb coll = db.stockcollection #Setup index on time to fetch the latest update coll.create_index([('time',DESCENDING)]) #YOUR PUBNUB KEYS - Replace the publish_key and subscriber_key below with your own keys pubnub = Pubnub(publish_key="<your publish key>",subscribe_key="<your subscribe key>") #Step 2 - Check and define the metadata ( index names ) metaDataInit(coll) #Step 3 - Set the parameters , max periodicity , random range updateTime = 10 #Max ten seconds for every price update numOfItems = 4 #Four indices to manage random.seed() #Step 4 - Setup the Queue and ClientListener Thread clientQueue = Queue() clientListener = ClientListenerThread(server,port,clientQueue,pubnub) clientListener.start() globalQueueRef = clientQueue #Step 5 - Setup PubNub Subscription for client requests pubnub.subscribe("stockhistory", historyCallback,historyError) #Step 6 - Start the stock picking loop while True: #Step 6.1 - Wait for random time time.sleep(random.randint(1,updateTime)) #Step 6.2 - Wake up and update the stock price for one of the index newPriceData = getUpdatedPrice(coll) #Step 6.3 - Update the new price in DB print "New Price Update " + str(newPriceData) coll.insert(newPriceData) #Step 6.4 - Publish over Pubnub , stockdata channel broadcastData = { 'name' : newPriceData['name'], 'value' : newPriceData['value'], 'change' : newPriceData['change'], 'time' : newPriceData['time'], } pubnub.publish('stockdata',json.dumps(broadcastData))
class pubnubmessager(Observer): def __init__(self): self.pn = Pubnub(config.pubnub_pubkey, config.pubnub_subkey) print("Started") def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice): if profit > config.profit_thresh and perc > config.perc_thresh: message = "profit: %f USD with volume: %f BTC - buy at %.4f (%s) sell at %.4f (%s) ~%.2f%%" % (profit, volume, buyprice, kask, sellprice, kbid, perc) self.pn.publish({'channel' : config.pubnub_topic, 'message' :{ 'msg' : message}})
def push_cbk(sender, **kwargs): istance = kwargs.get('instance') if istance: print "Account balance: %s" % istance.balance pubnub = Pubnub(publish_key='pub-ed4e8fc6-b324-426c-8697-ec763129b026', subscribe_key='sub-31c9765c-c453-11e1-b76c-1b01c696dab3', ssl_on=True) info = pubnub.publish({'channel' : istance.notif_channel, 'message' : 'Current balance ' + unicode(istance.balance) }) print info
def startStockPicker(server,port): global globalQueueRef global graph #Step 1 - Initialize MongoDB & PubNub Connection # py2neo.set_auth_token('%s:%s' % (NEO_HOST, NEO_PORT), NEO_AUTH_TOKEN) graph = Graph('%s://%s:%s@%s:%s/db/data/' % (NEO_PROTOCOL, NEO_USER, NEO_PASSWORD, NEO_HOST, NEO_PORT)) #YOUR PUBNUB KEYS - Replace the publish_key and subscriber_key below with your own keys pubnub = Pubnub(publish_key="<your pub key>",subscribe_key="<your sub key>") #Step 2 - Check and define the metadata ( index names ) metaDataInit() #Step 3 - Set the parameters , max periodicity , random range updateTime = 10 #Max ten seconds for every price update numOfItems = 4 #Four indices to manage random.seed() #Step 4 - Setup the Queue and ClientListener Thread clientQueue = Queue() clientListener = ClientListenerThread(server,port,clientQueue,pubnub) clientListener.start() globalQueueRef = clientQueue #Step 5 - Setup PubNub Subscription for client requests pubnub.subscribe("stockhistory", historyCallback,historyError) #Step 6 - Start the stock picking loop while True: #Step 6.1 - Wait for random time time.sleep(random.randint(1,updateTime)) #Step 6.2 - Wake up and update the stock price for one of the index newPriceData = getUpdatedPrice() #Step 6.3 - Update the new price in DB print "New Price Update " + str(newPriceData) #Step 6.4 - Publish over Pubnub , stockdata channel broadcastData = { 'name' : newPriceData['name'], 'value' : newPriceData['value'], 'change' : newPriceData['change'], 'time' : newPriceData['time'], } pubnub.publish('stockdata',json.dumps(broadcastData))
class pinterest(object): def __init__(self, publish_key, subscribe_key): self.publish_key = publish_key self.subscribe_key = subscribe_key self.pubnub = Pubnub( 'pub-c-6f928209-b8a8-4131-9749-7470ead38747', 'sub-c-6d212f32-404e-11e4-a498-02ee2ddab7fe', None, False) def send(self, channel, message): # Sending message on the channel self.pubnub.publish({ 'channel' : channel, 'message' : message})
def init(func): global pubnub global pubnub_freeboard global message_cb try: message_cb = func log.info("pubnub SUBSCRIBE") pubnub = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, cipher_key=CHIPER_KEY, ssl_on=True) pubnub.subscribe(CHANNEL, callback=pubnub_message_cb, error=pubnub_error_cb, connect=pubnub_connect_cb, reconnect=pubnub_reconnect_cb, disconnect=pubnub_disconnect_cb) pubnub_freeboard = Pubnub(publish_key=PUB_KEY, subscribe_key=SUB_KEY, ssl_on=False) log.info("pubnub SUBSCRIBED") except: log.error("Error initializing pubnub...Cannot continue") raise SystemExit
class iotbridge(object): def __init__(self, publish_key, subscribe_key, uuid): self.publish_key = publish_key self.subscribe_key = subscribe_key self.uuid = uuid self.pubnub = Pubnub("demo", "demo", None, False) self.pubnub.uuid = self.uuid def send(self, channel, message): # Sending message on the channel self.pubnub.publish(channel, message) def connect(self, channel, callback): # Listening for messages on the channel self.pubnub.subscribe(channel, callback=callback)
def __init__(self, publish_key, subscribe_key, uuid): self.publish_key = publish_key self.subscribe_key = subscribe_key self.uuid = uuid self.pubnub = Pubnub("demo", "demo", None, False) self.pubnub.uuid = self.uuid
class Streamteam(object): def __init__(self, args): self.channel = args.channel self.pubnub = Pubnub( args.publish, args.subscribe, None, False ) def publish(self, m): def callback(message): return message self.pubnub.publish( self.channel, m, callback=callback, error=callback ) def subscribe(self): 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") self.pubnub.subscribe( self.channel, callback=callback, error=callback, connect=connect, reconnect=reconnect, disconnect=disconnect )
def __init__(self, args): self.channel = args.channel self.pubnub = Pubnub( args.publish, args.subscribe, None, False )
def send(channel, message, **kwargs): """ Site: http://www.pubnub.com/ API: https://www.mashape.com/pubnub/pubnub-network Desc: real-time browser notifications Installation and usage: pip install -U pubnub Tests for browser notification http://127.0.0.1:8000/browser_notification/ """ pubnub = Pubnub( publish_key=settings.PUBNUB_PUB_KEY, subscribe_key=settings.PUBNUB_SUB_KEY, secret_key=settings.PUBNUB_SEC_KEY, ssl_on=kwargs.pop('ssl_on', False), **kwargs) return pubnub.publish(channel=channel, message={"text": message})
def __init__(self, subscribe=True, logcb=None, valuecb=None, swap=False): self.channel_down = "%s_down" % self.channel self.channel_up = "%s_up" % self.channel if swap: self.channel_down, self.channel_up = self.channel_up, self.channel_down self.pubnub = Pubnub(publish_key=self.pub_key, subscribe_key=self.sub_key, secret_key=self.secret_key) if subscribe: self.pubnub.subscribe(channels=self.channel_up, callback=self._callback, error=self._error_cb) self.logcb = logcb self.valuecb = valuecb
def main(): print "started" global t t = threading.Timer(TEMPO, callback_timer) t.start() pubnub = Pubnub( "pub-e10385fe-9f9f-46a4-b969-f3c8ba11ff59", ## PUBLISH_KEY "sub-f8f2ff3a-a176-11e1-bbc1-f151a023fb9a", ## SUBSCRIBE_KEY "sec-OGY5MTk3Y2QtMDY2OS00NThiLTlmZjItNWFkZGM3NDgxMmZi", False ) print("subscribing...") pubnub.subscribe({ 'channel' : 'fbhackaton_newquestion', 'callback' : receive })
class Streamteam(object): def __init__(self, args): self.channel = args.channel self.pubnub = Pubnub( args.publish, args.subscribe, None, False ) def publish(self, message): self.pubnub.publish({ 'channel' : self.channel, 'message' : message }) def subscribe(self): def receive(message): # q = "" s = "" v = "" names = "gyroX gyroY AF3 F7 F3 FC5 T7 P7 O1 O2 P8 T8 FC6 F4 F8 AF4".split(" ") os.system('clear') for i in names: # q += str(message['quality'][i]) + " " v += str(message['values'][i]) + " " while len(i) < 7: i += " " s += i print("Channel : " + s) # print("Quality : " + q) print("Values : " + v) return True self.pubnub.subscribe({ 'channel' : self.channel, 'callback' : receive })
class WatchRemote(): """monitoring remote repository""" def __init__(self, pid, path, key ): self.pid = pid self.path = path self.pubnub = Pubnub( None, key, None, False ) def receive(self,message) : notify('GitBox Download', 'receiving new and changed files in %s' % self.path) cmd = 'git push' process = subprocess.Popen(cmd.split(' '), cwd=self.path) process.communicate() return True def start(self): ## Initiat Class self.pubnub.subscribe({'channel' : self.pid, 'callback' : self.receive }) def stop(self): pass
def __doSubscribe(self, **kwargs): self.pubnubConnecor = Pubnub(kwargs['publish_key'], kwargs['subscribe_key'], kwargs['secret_key'], kwargs['ssl_on'] ) if len( kwargs['channel'] ) > 0: logging.info('subscribing to channel ({})'.format(kwargs['channel'])) self.pubnubConnecor.subscribe({ 'channel' : kwargs['channel'], 'callback' : kwargs['callback'] }) else: logging.info('no channel defined, listening will not begin until one is assigned via switchChannel') return False
def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/eke.pid' self.channel_sub = 'hello_world' self.pidfile_timeout = 5 self.df = pd.DataFrame(columns = ['temp']) self.publish_key = '' self.subscribe_key = '' self.secret_key = '' self.cipher_key = '' self.ssl_on = False self.readKeys() self.pubnub = Pubnub(publish_key=self.publish_key, subscribe_key=self.subscribe_key, secret_key=self.secret_key, cipher_key=self.cipher_key, ssl_on=self.ssl_on)
from geom import * from snake import * import json from copy import copy from Pubnub import Pubnub PUBLISH_KEY = "pub-c-33787580-d63f-4c10-a274-4673c54b6655" SUBSCRIBE_KEY = "sub-c-79472c46-6cd4-11e4-ab04-02ee2ddab7fe" pubnub = Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY, None, False) defaultParams = { "rounds": 50, "playersCount": 2, "colors": ["#00f", "#f00", "#006400", "#000", "orange", "#000"], "ucolors": ["#88f", "#f88", "#3cb371", "#666", "white"], "canvasSizes": (640, 480), } class Game: def __init__(self, _id, _players, _params=defaultParams): self.id = _id self.players = copy(_players) self.rounds = _params["rounds"] self.playersCount = _params["playersCount"] self.colors = _params["colors"] self.ucolors = _params["ucolors"] self.canvasSizes = _params["canvasSizes"]
## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ ## ----------------------------------- ## PubNub 3.0 Real-time Push Cloud API ## ----------------------------------- from Pubnub import Pubnub import unittest2 as unittest import sys 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 None ssl_on = len(sys.argv) > 4 and bool(sys.argv[4]) or False pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) crazy = ' ~`!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':",./<>?abcd' class TestDetailedHistory(unittest.TestCase): total_msg = 10 channel = pubnub.time() starttime = None inputs = [] endtime = None slice_a = 8 slice_b = 2 slice_size = slice_a - slice_b @classmethod def publish_msg(cls, start, end, offset):
sys.path.append('../common/') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or None cipher_key = len(sys.argv) > 4 and sys.argv[4] or None ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Command Line Options Supplied PubNub ## ----------------------------------------------------------------------- pubnub_user_supplied_options = Pubnub( publish_key, ## OPTIONAL (supply None to disable) subscribe_key, ## REQUIRED secret_key, ## OPTIONAL (supply None to disable) cipher_key, ## OPTIONAL (supply None to disable) ssl_on ## OPTIONAL (supply None to disable) ) ## ----------------------------------------------------------------------- ## High Security PubNub ## ----------------------------------------------------------------------- pubnub_high_security = Pubnub( ## Publish Key 'pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0', ## Subscribe Key 'sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd', ## Secret Key
def main(): resetAVR() print("Establishing Connections...") pubnub = Pubnub(publish_key='pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96', subscribe_key='sub-c-34be47b2-f776-11e4-b559-0619f8945a4f', uuid="pi") channel = 'leap2pi' GPIO.output(4, False) def checkValue(value): if (value < SERVO_MIN): value = SERVO_MIN elif (value > SERVO_MAX): value = SERVO_MAX return value def invertValue(value): value = checkValue(value) return SERVO_MAX - value + SERVO_MIN def _connect(m): print("Connected to PubNub!") GPIO.output(4, True) def _reconnect(m): print("Reconnected to PubNub!") GPIO.output(4, True) def _disconnect(m): print("Disconnected from PubNub!") GPIO.output(4, False) def _callback(m, n): left_byte = 0 right_byte = 0 yaw = 0 pitch = 0 byte = 0 # Handle message left_hand = m.get("left_hand", {}) right_hand = m.get("right_hand", {}) if (servo_mode == MIRROR): # Leap Motion: Left hand, Servos: Stage Left if left_hand != {}: yaw = left_hand["left_yaw"] yaw = checkValue(yaw) pitch = left_hand["left_pitch"] pitch = checkValue(pitch) left_byte = left_hand["left_byte"] pwm.setPWM(0, 0, yaw) pwm.setPWM(1, 1, pitch) # Leap Motion: Left hand, Servos: Stage Right if right_hand != {}: yaw = right_hand["right_yaw"] yaw = checkValue(yaw) pitch = right_hand["right_pitch"] pitch = checkValue(pitch) right_byte = right_hand["right_byte"] >> 4 pwm.setPWM(2, 2, yaw) pwm.setPWM(3, 3, pitch) byte = left_byte | (right_byte << 4) elif (servo_mode == CLONE): # Leap Motion: Left hand, Servos: Stage Right if left_hand != {}: yaw = left_hand["left_yaw"] yaw = invertValue(yaw) pitch = left_hand["left_pitch"] pitch = invertValue(pitch) left_byte = left_hand["left_byte"] pwm.setPWM(2, 2, yaw) pwm.setPWM(3, 3, pitch) # Leap Motion: Left hand, Servos: Stage Left if right_hand != {}: yaw = right_hand["right_yaw"] yaw = invertValue(yaw) pitch = right_hand["right_pitch"] pitch = invertValue(pitch) right_byte = right_hand["right_byte"] >> 4 pwm.setPWM(0, 0, yaw) pwm.setPWM(1, 1, pitch) byte = (left_byte << 4) | right_byte else: byte = -1 #====send i2c=====# if (byte >= 0): try: bus.write_byte(0x47, byte) except IOError: print("Error!!!!") resetAVR() bus.write_byte(0x47, byte) #Catch and Print Error def _error(m): GPIO.output(4, False) print(m) #Subscribe to subchannel, set callback function to _callback and set error fucntion to _error pubnub.subscribe(channels=channel, callback=_callback, error=_error, connect=_connect, reconnect=_reconnect, disconnect=_disconnect) # Loop here forever while True: # Check for switch position time.sleep(1) if (GPIO.input(16) == False): servo_mode = CLONE elif (GPIO.input(20) == False): servo_mode = MIRROR else: servo_mode = DISABLED
import sys from Pubnub import Pubnub 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 'abcd' 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 = 'ab' # Asynchronous usage def callback_abc(message, channel, real_channel): print(str(message) + ' , ' + channel + ', ' + real_channel) pubnub.unsubscribe_group(channel_group='abc') #pubnub.stop() def callback_d(message, channel):
import sys from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=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)
from Pubnub import Pubnub import time pubnub = Pubnub("demo", "demo") pubnub_pam = Pubnub("pub-c-c077418d-f83c-4860-b213-2f6c77bde29a", "sub-c-e8839098-f568-11e2-a11a-02ee2ddab7fe", "sec-c-OGU3Y2Q4ZWUtNDQwMC00NTI1LThjNWYtNWJmY2M4OGIwNjEy") # Grant permission read true, write true, on channel ( Async Mode ) def test_1(): resp = {'response': None} def _callback(response): resp['response'] = response def _error(response): resp['response'] = response pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1, callback=_callback, error=_error) time.sleep(2) assert resp['response'] == { 'message': u'Success', 'payload': { u'auths': {
import sys import tornado sys.path.append('../') sys.path.append('../..') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' ##(Cipher key is Optional) ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key,cipher_key=cipher_key, ssl_on=ssl_on ) #pubnub = Pubnub( publish_key, subscribe_key, secret_key, ssl_on ) crazy = 'hello_world' def connect_cb(): print 'Connect' def subscribe_result(response): print response pubnub.subscribe({ 'channel' : crazy, 'callback' : subscribe_result, 'connect' : connect_cb }) ## -----------------------------------------------------------------------
import sys, os, time, json from Pubnub import Pubnub def userFileGen(name, rHR, phNum, usrNum): userFile = ({'name':name,'RHR':rHR,'phNum':phNum,'usrNum':usrNum}) print('User file created...') return userFile publish_key = 'pub-c-ea55afd0-74eb-4ed4-9f56-4cd96bb87b0a' subscribe_key = 'sub-c-55cf6ccc-4585-11e4-8772-02ee2ddab7fe' secret_key = 'demo' cipher_key = '' ssl_on = False pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) userFile = open('userFile') userData = userFile.read() name = userData.split(',')[0] rHR = userData.split(',')[1] phNum = userData.split(',')[2] usrNum = userData.split(',')[3] usrJson = userFileGen(name,rHR,phNum,usrNum) pubnub.publish('usrid_channel', usrJson) os.system('./googlet2s.sh User Name ' + name ) os.system('./googlet2s.sh resting heart rate ' + rHR)
## http://www.pubnub.com/ import sys from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=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")
import sys from Pubnub import Pubnub ## Initiat Class pubnub = Pubnub('demo', 'demo', None, False) ## Subscribe Example def receive(message): print(message) return True channel = sys.argv[1] or 'hello_world' print("Listening for messages on '%s' channel..." % channel) pubnub.subscribe({'channel': channel, 'callback': receive})
sys.path.append('../') sys.path.append('./') sys.path.append('../common/') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or None cipher_key = len(sys.argv) > 4 and sys.argv[4] or None ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key, subscribe_key, secret_key, cipher_key, ssl_on) ch = 'python-async-test-channel-' expect = 0 done = 0 failures = 0 passes = 0 def stop(): global done global count pubnub.stop() print "============================" print 'Total\t:\t', failures + passes print 'PASS\t:\t', passes print 'FAIL\t:\t', failures
sensor = 4 GPIO.setmode(GPIO.BCM) GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN) previous_state = False current_state = False connection = httplib.HTTPSConnection('api.parse.com', 443) connection.connect() pubnub = Pubnub(publish_key = 'pub-c-f83b8b34-5dbc-4502-ac34-5073f2382d96', subscribe_key = 'sub-c-34be47b2-f776-11e4-b559-0619f8945a4f', uuid='pi') cam = picamera.PiCamera() lock = threading.Lock() channel = 'iotchannel' subchannel = 'liveCamStatus' ## Camera Settings imgCount = 3 frameSleep = 0.5 # Seconds between burst-snaps camSleep = 5 # Seconds between Detections def _error(m): print(m)
import sys from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False import time ## ----------------------------------------------------------------------- ## 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, daemon=False) channel = 'b' # Asynchronous usage def callback(message, channel): print(message) pubnub.presence(channel, callback=callback)
from Pubnub import PubnubTwisted as Pubnub ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Configuration ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- publish_key = 'pub-c-f6a20151-db8d-45af-ba42-def0edaa459f' subscribe_key = 'sub-c-b5ff3208-7f64-11e4-b601-02ee2ddab7fe' secret_key = 'demo' server_channel = 'echo-server' client_channel = 'echo-channel' ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Create PubNub Instance ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, ssl_on=True) ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Error Log ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- def error_log(data): print(data) ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Access Log ## =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- def access_log(data): print(data)
from Pubnub import Pubnub ## Initiate Class pubnub = Pubnub('demo', 'demo', None, False) ## Publish Example info = pubnub.publish({'channel': 'example-user-id-1234', 'message': 'alert'}) print(info)
import sys sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len( sys.argv) > 4 and sys.argv[4] or '' ##(Cipher key is Optional) ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key, subscribe_key, secret_key, cipher_key, ssl_on) crazy = ' ~`!@#$%^&*( 顶顅 Ȓ)+=[]\\{}|;\':",./<>?abcd' ## --------------------------------------------------------------------------- ## Unit Test Function ## --------------------------------------------------------------------------- def test(trial, name): if trial: print('PASS: '******'FAIL: ' + name) ## ----------------------------------------------------------------------- ## Time Example
from Pubnub import Pubnub import json, time try: import RPi.GPIO as GPIO except RuntimeError: print "Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script" #Setup GPIO GPIO.setmode(GPIO.BOARD) #Setup PubNub pubnub = Pubnub(publish_key="pub-c-bd0276ed-f876-49cc-b73d-aa05b31efe63", subscribe_key="sub-c-76d94746-b211-11e4-b35d-02ee2ddab7fe") pubnubChannelName = 'gpio-raspberry-control' #Setup Glow Status Flow glow = False #PubNub Channel Subscribe Callback def gpioCallback(msg, channel): global glow respstring = '' command = msg print "Command is : " + str(command) if ('req' in command):
import sys from twisted.internet import reactor sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len( sys.argv) > 4 and sys.argv[4] or '' ##(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 ## ----------------------------------------------------------------------- def publish_complete(info): print(info) ## Publish string pubnub.publish({ 'channel': crazy, 'message': 'Hello World!', 'callback': publish_complete
'queued': 0, # Total Unreceived Queue (UnDeliveries) 'successful_publishes': 0, # Confirmed Successful Publish Request 'failed_publishes': 0, # Confirmed UNSuccessful Publish Request 'failed_deliveries': 0, # (successful_publishes - received) 'deliverability': 0 # Percentage Delivery } trips = {'last': None, 'current': None, 'max': 0, 'avg': 0} ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- channel = 'deliverability-' + str(time.time()) pubnub = Pubnub(publish_key, subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on, origin=origin) ## ----------------------------------------------------------------------- ## BENCHMARK ## ----------------------------------------------------------------------- def publish_sent(info=None): if info and info[0]: analytics['successful_publishes'] += 1 else: analytics['failed_publishes'] += 1 analytics['publishes'] += 1
'queued': 0, ## Total Unreceived Queue (UnDeliveries) 'successful_publishes': 0, ## Confirmed Successful Publish Request 'failed_publishes': 0, ## Confirmed UNSuccessful Publish Request 'failed_deliveries': 0, ## (successful_publishes - received) 'deliverability': 0 ## Percentage Delivery } trips = {'last': None, 'current': None, 'max': 0, 'avg': 0} ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- channel = 'deliverability-' + str(time.time()) pubnub = Pubnub(publish_key, subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on, origin=origin) ## ----------------------------------------------------------------------- ## BENCHMARK ## ----------------------------------------------------------------------- def publish_sent(info=None): if info and info[0]: analytics['successful_publishes'] += 1 else: analytics['failed_publishes'] += 1 analytics['publishes'] += 1 analytics['queued'] += 1 pubnub.timeout(send, 0.1)
import sys from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) channel = 'hello_world' # Asynchronous usage def callback(message, channel): print(message) def error(message): print("ERROR : " + str(message))
from twisted.internet import reactor sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or None ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- #pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) crazy = 'hello_world' ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) def connected(): print 'Connected' pubnub.subscribe({
from Pubnub import Pubnub import time import random pubnub = Pubnub("demo","demo") pubnub.set_u(True) def rand_str(s): return str(s) + '-' + str(random.randint(1, 100000000000)) def test_1(): channel = rand_str('channel') channel2 = rand_str('channel') channel_group = rand_str('group') channel_group2 = rand_str('group') namespace = rand_str('ns') resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group, channel=channel) assert resp['status'] == 200 assert resp['message'] == 'OK' assert resp['error'] == False resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group, channel=channel2) assert resp['status'] == 200 assert resp['message'] == 'OK' assert resp['error'] == False resp = pubnub.channel_group_add_channel(channel_group=namespace + ':' + channel_group2, channel=channel) assert resp['status'] == 200
import sys import time import random from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or None cipher_key = len(sys.argv) > 4 and sys.argv[4] or None ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key, subscribe_key, secret_key, cipher_key, ssl_on) ch = 'python-async-test-channel-' expect = 0 done = 0 failures = 0 passes = 0 def stop(): global done global count pubnub.stop() print "============================" print 'Total\t:\t', failures + passes print 'PASS\t:\t', passes print 'FAIL\t:\t', failures
## PubNub 3.1 Real-time Push Cloud API ## ----------------------------------- import sys sys.path.append('../') from twisted.internet import reactor from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=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})
from Pubnub import Pubnub ## Initiat Class pubnub = Pubnub( 'demo', 'demo', None, False ) ## Publish Example info = pubnub.publish({ 'channel' : 'hello_world', 'message' : { 'some_text' : 'Hello my World' } }) print(info)
def init(): global pubnub pubnub = Pubnub(publish_key="demo", subscribe_key="demo") pubnub.subscribe(channels=pubnub_requestchannel, callback=_callback, error=_error)
import threading, uuid from Pubnub import Pubnub import pyperclip USER = "******" PASS = "******" UNIQUEID = "cboard-PC-%s" % uuid.getnode() clipDict = {} clipText = '' clipLen = 0 pubnub = Pubnub( "pub-56806acb-9c46-4008-b8cb-899561b7a762", ## PUBLISH_KEY "sub-26001c28-a260-11e1-9b23-0916190a0759", ## SUBSCRIBE_KEY "sec-MGNhZWJmZmQtOTZlZS00ZjM3LWE4ZTYtY2Q3OTM0MTNhODRj", ## SECRET_KEY False ## SSL_ON? ) def setGlobal(content): try: API_KEY = 'H4vlwkm8tvO8' API_SECRET = 'UZepT6F8abA80DK1ilCz' timestamp = int(time.time()) payload = { 'data': content.decode('utf-8'), 'user': USER,
## PubNub 3.0 Real-time Push Cloud API ## ----------------------------------- from Pubnub import Pubnub import sys 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 None ssl_on = len(sys.argv) > 4 and bool(sys.argv[4]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key, subscribe_key, secret_key, ssl_on) crazy = ' ~`!@#$%^&*(顶顅Ȓ)+=[]\\{}|;\':"./<>?abcd' ## --------------------------------------------------------------------------- ## Unit Test Function ## --------------------------------------------------------------------------- def test(trial, name): if trial: print('PASS: '******'FAIL: ' + name) ## ----------------------------------------------------------------------- ## Publish Example
## http://www.pubnub.com/ import sys from Pubnub import Pubnub publish_key = 'pub-c-6c6b1294-7fdd-4f33-aec4-41217a6d0b6c' subscribe_key = 'sub-c-cf0e18e6-bd43-11e4-861a-0619f8945a4f' 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 = 'my_channel' # Synchronous usage print pubnub.history(channel, count=10) # Asynchronous usage def callback(message): print(message) pubnub.history(channel, count=10, callback=callback, error=callback)
## http://www.pubnub.com/ import sys from Pubnub import PubnubTwisted as Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'pam' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'pam' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'pam' 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' authkey = "abcd" def callback(message): print(message) pubnub.grant(channel, authkey, True, True, callback=callback, error=callback) pubnub.start()
import sys import tornado sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ##(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' ## ----------------------------------------------------------------------- ## History Example ## ----------------------------------------------------------------------- def history_complete(messages): print(messages) pubnub.history( { 'channel' : crazy, 'limit' : 10, 'callback' : history_complete }) ## -----------------------------------------------------------------------
from sqlalchemy.orm import joinedload, contains_eager from sqlalchemy.orm.exc import NoResultFound from flask.ext.cors import CORS from db import db, Recipe, Ingredient, Inventory, ShoppingList, to_json, \ RecipeIngredients, Step, InventoryIngredients, ShoppingListIngredients, EAN import settings from Pubnub import Pubnub PUBLISH_KEY = "FILL_HERE" SUBSCRIBE_KEY = "FILL_HERE" pubnub = Pubnub( 'pub-c-2737ce59-7cef-4844-a3fb-8774d6b0f7d7', 'sub-c-b9d14884-51a7-11e4-a2b1-02ee2ddab7fe', 'sec-c-OTYyZmI0MzQtOTU3Zi00ZGU3LWFjZTQtMDI3NzJhN2IwZTgy', # SECRET_KEY False # SSL_ON? ) app = Flask(__name__) #cors = CORS(app, automatic_options=True, headers=['Content-Type', 'X-DevTools-Emulate-Network-Conditions-Client-Id']) app.config.from_object(settings) db.init_app(app) @app.route('/') def hello_world(): return 'GET /shopping_list<br>POST /inventory<br>GET /recipes' @app.route('/installaaaaaaaa')
## ----------------------------------- from Pubnub import Pubnub import sys import tornado publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or 'demo' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiat Class ## ----------------------------------------------------------------------- pubnub = Pubnub( publish_key, subscribe_key, secret_key,cipher_key, ssl_on ) crazy = 'hello_world' ## --------------------------------------------------------------------------- ## Unit Test Function ## --------------------------------------------------------------------------- def test( trial, name ) : if trial : print( 'PASS: '******'FAIL: ' + name ) ## ----------------------------------------------------------------------- ## Time Example ## ----------------------------------------------------------------------- def time_complete(timestamp):
import sys from twisted.internet import reactor sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key, subscribe_key, secret_key, cipher_key, ssl_on) crazy = 'hello_world' ## ----------------------------------------------------------------------- ## History Example ## ----------------------------------------------------------------------- def history_complete(messages): print(messages) reactor.stop() pubnub.history({'channel': crazy, 'limit': 10, 'callback': history_complete}) ## ----------------------------------------------------------------------- ## IO Event Loop
import sys from twisted.internet import reactor sys.path.append('../') from Pubnub import Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or None ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub( publish_key, subscribe_key, secret_key, cipher_key, ssl_on ) crazy = 'hello_world' ## ----------------------------------------------------------------------- ## Subscribe Example ## ----------------------------------------------------------------------- def message_received(message): print(message) def connected() : pubnub.publish({ 'channel' : crazy, 'message' : { 'Info' : 'Connected!' } }) pubnub.subscribe({
from Pubnub import Pubnub import time pubnub = Pubnub("demo", "demo") pubnub_pam = Pubnub("pam", "pam", "pam") # Grant permission read true, write true, on channel ( Sync Mode ) def test_1(): resp = pubnub_pam.grant(channel="abcd", auth_key="abcd", read=True, write=True, ttl=1) print resp assert resp['message'] == 'Success' assert resp['payload'] == { 'auths': { 'abcd': { 'r': 1, 'w': 1, 'm': 0 } }, 'subscribe_key': 'pam', 'level': 'user', 'channel': 'abcd', 'ttl': 1 }