def test_error_invalid_key(self): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" self.pubnub = PubNubTornado(conf, custom_ioloop=self.io_loop) self.assert_server_side_error(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key") self.assert_server_side_error_yield(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key")
def test_error_invalid_key(self): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" pubnub = PubNubTwisted(conf) with pytest.raises(PubNubTwistedException) as exception: yield pubnub.publish().channel(channel).message("hey").deferred() self.assertEqual(exception.value.status.error_data.information, "HTTP Client Error (400): [0, u'Invalid Key', u'14767989321048626']")
def test_error_invalid_key(event_loop): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" conf.enable_subscribe = False pubnub = PubNubAsyncio(conf, custom_event_loop=event_loop) yield from assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "Invalid Key") pubnub.stop()
def main(): pnconf = PNConfiguration() pnconf.subscribe_key = 'demo' pnconf.publish_key = 'demo' pubnub = PubNub(pnconf) def my_publish_callback(result, status): # Check whether request successfully completed or not if not status.is_error(): envelope = result # noqa pass # Message successfully published to specified channel. else: pass # Handle message publish error. Check 'category' property to find out possible issue # because of which request did fail. # Request can be resent using: [status retry]; class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass # handle incoming presence data def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: pass # This event happens when radio / connectivity is lost elif status.category == PNStatusCategory.PNConnectedCategory: # Connect event. You can do stuff like publish, and know you'll get it. # Or just use the connected event to confirm you are subscribed for # UI / internal notifications, etc pubnub.publish().channel("awesome_channel").message("Hello!").pn_async(my_publish_callback), elif status.category == PNStatusCategory.PNReconnectedCategory: pass # Happens as part of our regular operation. This event happens when # radio / connectivity is lost, then regained. elif status.category == PNStatusCategory.PNDecryptionErrorCategory: pass # Handle message decryption error. Probably client configured to # encrypt messages and on live data feed it received plain text. def message(self, pubnub, message): # Handle new message stored in message.message pass pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels('awesome_channel').execute() reactor.callLater(30, pubnub.stop) # stop reactor loop after 30 seconds pubnub.start()
def test_invalid_key(self): config = PNConfiguration() config.publish_key = "fake" config.subscribe_key = "demo" config.enable_subscribe = False try: PubNub(config).publish() \ .channel("ch1") \ .message("hey") \ .sync() self.fail(Exception("Should throw exception", 'pnsdk')) except PubNubException as e: assert "Invalid Key" in str(e)
def test_invalid_key(self): self.invalid_key_message = "" config = PNConfiguration() config.publish_key = "fake" config.subscribe_key = "demo" config.enable_subscribe = False PubNub(config).publish() \ .channel("ch1") \ .message("hey") \ .async(self.callback) self.event.wait() assert self.status.is_error() assert self.status.category is PNStatusCategory.PNBadRequestCategory assert self.status.original_response[0] is 0 assert self.status.original_response[1] == 'Invalid Key' assert "HTTP Client Error (400):" in str(self.status.error_data.exception) assert "Invalid Key" in str(self.status.error_data.exception)
def test_reconnection(self): pnconf = PNConfiguration() pnconf.publish_key = "demo" pnconf.subscribe_key = "demo" pnconf.origin = "localhost:8089" pnconf.subscribe_request_timeout = 10 pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) time_until_open_again = 10 @gen.coroutine def close_soon(): yield gen.sleep(3) pubnub.http.close() pubnub.http = None print(">>> connection is broken") @gen.coroutine def open_again(): yield gen.sleep(time_until_open_again) pubnub.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS) print(">>> connection is open again") @gen.coroutine def countdown(): yield gen.sleep(2) opened = False count = time_until_open_again while not opened: print(">>> %ds to open again" % count) count -= 1 if count <= 0: break yield gen.sleep(1) my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) pubnub.subscribe().channels('my_channel').execute() yield gen.sleep(1000)
from mock import patch except ImportError: from unittest.mock import patch # noqa: F401 crypto = PubNubCryptodome() pub_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" sub_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pub_key_pam = "pub-c-98863562-19a6-4760-bf0b-d537d1f5c582" sub_key_pam = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f" sec_key_pam = "sec-c-MGFkMjQxYjMtNTUxZC00YzE3LWFiZGYtNzUwMjdjNmM3NDhk" pnconf = PNConfiguration() pnconf.publish_key = pub_key pnconf.subscribe_key = sub_key pnconf.enable_subscribe = False pnconf_sub = PNConfiguration() pnconf_sub.publish_key = pub_key pnconf_sub.subscribe_key = sub_key pnconf_enc = PNConfiguration() pnconf_enc.publish_key = pub_key pnconf_enc.subscribe_key = sub_key pnconf_enc.cipher_key = "testKey" pnconf_enc.enable_subscribe = False pnconf_enc_sub = PNConfiguration() pnconf_enc_sub.publish_key = pub_key
from pubnub.pnconfiguration import PNConfiguration pnconf = PNConfiguration() pnconf.subscribe_key = "demo" pnconf.publish_key = "demo" pnconf.enable_subscribe = False
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory, PNOperationType from pubnub.pubnub_asyncio import PubNubAsyncio d = os.path.dirname PUBNUB_ROOT = d(d(d(os.path.dirname(os.path.abspath(__file__))))) APP_ROOT = d(os.path.abspath(__file__)) sys.path.append(PUBNUB_ROOT) from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration pnconf = PNConfiguration() pnconf.subscribe_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pnconf.publish_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" pnconf.uuid = "pubnub-demo-api-python-backend" DEFAULT_CHANNEL = "pubnub_demo_api_python_channel" EVENTS_CHANNEL = "pubnub_demo_api_python_events" APP_KEY = utils.uuid() loop = asyncio.get_event_loop() pubnub = PubNubAsyncio(pnconf) def publish_sync(): return _not_implemented_error({ "error": "Sync publish not implemented" })
from pubnub.pnconfiguration import PNConfiguration try: from mock import patch except ImportError: from unittest.mock import patch # noqa: F401 pub_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" sub_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" pub_key_pam = "pub-c-98863562-19a6-4760-bf0b-d537d1f5c582" sub_key_pam = "sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f" sec_key_pam = "sec-c-MGFkMjQxYjMtNTUxZC00YzE3LWFiZGYtNzUwMjdjNmM3NDhk" pnconf = PNConfiguration() pnconf.publish_key = pub_key pnconf.subscribe_key = sub_key pnconf.enable_subscribe = False pnconf_sub = PNConfiguration() pnconf_sub.publish_key = pub_key pnconf_sub.subscribe_key = sub_key pnconf_enc = PNConfiguration() pnconf_enc.publish_key = pub_key pnconf_enc.subscribe_key = sub_key pnconf_enc.cipher_key = "testKey" pnconf_enc.enable_subscribe = False pnconf_enc_sub = PNConfiguration() pnconf_enc_sub.publish_key = pub_key
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-a41be4e8-b620-11e5-a916-0619f8945a4f' pnconfig.publish_key = 'pub-c-b525a8c0-3301-432e-a37b-d8fec5583788' pnconfig.subscribe_key = 'demo' pnconfig.publish_key = 'demo' pubnub = PubNub(pnconfig) def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): pass # Message successfully published to specified channel. else: pass # Handle message publish error. Check 'category' property to find out possible issue # because of which request did fail. # Request can be resent using: [status retry]; class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass # handle incoming presence data
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import RPi.GPIO as GPIO import time import sys pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-74c2a3a2-9b76-11e7-bec3-c65ebd354f7d' pnconfig.publish_key = 'pub-c-73a9c60e-26a6-4e5e-a92a-858d0a7247e2' pubnub = PubNub(pnconfig) GPIO.setmode (GPIO.BCM) GPIO.setwarnings(False) LED_PIN = 20 GPIO.setup(LED_PIN,GPIO.OUT) channel = 'Channel-rqbvqvvdo'
#!/usr/bin/python3 from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub pnconfig = PNConfiguration() pnconfig.subscribe_key = "my_subkey" pnconfig.publish_key = "my_pubkey" pnconfig.ssl = False pubnub = PubNub(pnconfig) from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNOperationType, PNStatusCategory class MySubscribeCallback(SubscribeCallback): def status(self, pubnub, status): pass # The status object returned is always related to subscribe but could contain # information about subscribe, heartbeat, or errors # use the operationType to switch on different options if status.operation == PNOperationType.PNSubscribeOperation \ or status.operation == PNOperationType.PNUnsubscribeOperation: if status.category == PNStatusCategory.PNConnectedCategory: pass # This is expected for a subscribe, this means there is no error or issue whatsoever elif status.category == PNStatusCategory.PNReconnectedCategory: pass # This usually occurs if subscribe temporarily fails but reconnects. This means # there was an error but there is no longer any issue elif status.category == PNStatusCategory.PNDisconnectedCategory:
from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import subprocess import time import datetime import math pnconfig = PNConfiguration() pnconfig.publish_key ='pub-c-9c260cad-9e78-4bea-a3a9-f584ea818532' pnconfig.subscribe_key = 'sub-c-2e6e94ce-305d-11e9-a223-2ae0221900a7' pubnub = PubNub(pnconfig) x=10 def callback(message, status): print(message) avg=0.0 count=0 while x>0: x-=1 count+=1 time.sleep(1) p = subprocess.check_output('lifepo4wered-cli get vbat',shell=True) b1=round(float(p)/1000,5) p = subprocess.check_output('lifepo4wered-cli get vout',shell=True) r1=round(float(p)/1000,5) data ={ "eon":{"Battery Voltage (Volts)":b1,"Raspberry Pi Voltage (Volts)":r1} } avg=avg+r1 data2={ "PL":20,"ON":round(avg/count,3),"W":"Working","S":x,"WT":"Not Set Yet"}
import pubnub as pn import tornado from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep pn.set_stream_logger('pubnub', logging.DEBUG) from tornado.testing import AsyncTestCase from pubnub.exceptions import PubNubException from pubnub.models.consumer.pubsub import PNPublishResult from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope, PubNubTornadoException from tests.helper import pnconf_sub_copy corrupted_keys = PNConfiguration() corrupted_keys.publish_key = "blah" corrupted_keys.subscribe_key = "blah" pn.set_stream_logger('pubnub', logging.DEBUG) ch = "tornado-publish" class TestPubNubTornadoInvocations(AsyncTestCase): def setUp(self): super(TestPubNubTornadoInvocations, self).setUp() @tornado.testing.gen_test def test_publish_resultx(self): pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) result = yield pubnub.publish().message('hey').channel('blah').result()
import time from pubnub.pubnub import PubNub from pubnub.pnconfiguration import PNConfiguration from pubnub.callbacks import SubscribeCallback from backend.wallet.transaction import Transaction from backend.Blockchain.block import Block pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-9d19cfbc-77e0-11ea-912d-22a939e7b3e3' pnconfig.publish_key = 'pub-c-e569b18f-d5f7-46aa-a616-d17563bfbcea' CHANNELS = { 'TEST': 'TEST', 'BLOCK': 'BLOCK', 'TRANSACTION': 'TRANSACTION' } class Listener(SubscribeCallback): def __init__(self, blockchain, transaction_pool): self.blockchain = blockchain self.transaction_pool = transaction_pool def message(self, pubnub, message_object): print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') if message_object.channel == CHANNELS['BLOCK']: block = Block.from_json(message_object.message) potential_chain = self.blockchain.chain[:] potential_chain.append(block)
# On Raspberry Pi terminal - sudo pip install pubnub # Execute this file (with your keys) - A message will be published and the same terminal will also show the message as received. # You can use this same file on another raspberry pi or your computer and execute the file on both of them to exchange messages from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub pnconfig = PNConfiguration() pnconfig.subscribe_key = 'demo' pnconfig.publish_key = 'demo' pubnub = PubNub(pnconfig) def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): print ("Message published\n") #pass # Message successfully published to specified channel. else: print "Message publish failed" #pass # Handle message publish error. Check 'category' property to find out possible issue # because of which request did fail. # Request can be resent using: [status retry];