Forums

Using PubNub to publish message in Django view

I want to use PubNub to publish a message from a Django view. It seems to work fine at first, but if I refresh the page a few times in succession, I eventually catch a RuntimeError exception with the message "can't start new thread". If I wait a bit (I'm not sure how long), it resumes working again, and then repeats the same behavior.

Here's my code for my view:

def court_assignments(request):
    try:
        pnconfig = PNConfiguration()

        pnconfig.subscribe_key = '<sub key>'
        pnconfig.publish_key = '<pub key>'
        pnconfig.ssl = False

        pubnub = PubNub(pnconfig)
        pubnub.publish().channel('MyDemoChannel').message({"text": "My test message."}).sync()
    except:
        logger.exception("Caught exception in my_view()")
             .
             .
             .

And the stack trace:

[25/Aug/2018 23:00:28] ERROR [league.views:104] Caught exception in court_assignments()
Traceback (most recent call last):
  File "/home/tennis/tennis.pythonanywhere.com/website/league/views.py", line 98, in court_assignments
    pubnub = PubNub(pnconfig)
  File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/pubnub.py", line 36, in __init__
    self._subscription_manager = NativeSubscriptionManager(self)
  File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/pubnub.py", line 164, in __init__
    self._start_worker()
  File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/pubnub.py", line 258, in _start_worker
    self._consumer_thread.start()
  File "/usr/lib/python3.6/threading.py", line 846, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread

Is there something I'm doing incorrectly?

Thanks, Mike

I'm not an expert, but looking at the hello world examples for pubnub, it seems like you should do the PNConfiguration only once (ie. outside of a function that keeps recreating it)?

That fixed the issue, and it makes sense. Thanks!