Subscribe to spark events using python


I wrote a small python program that control my spark from my computer. I would like to read spark events.
I found it pretty easy to call functions and read variables, but didn’t figure out how to read events. I also failed to find someone who implement reading spark events with python.

Spyrk is a great project, but unfortunately not support Spark event for now.
SSEclient is Python library enable Server sent event but when I try to use it I get ‘400 - bad request’ from Spark cloud.

What is the right way to read spark event with Python client?

Looking at the example for SSEClient:

from sseclient import SSEClient

messages = SSEClient('')
for msg in messages:

What’s the URL that you used?

It should be something like this:

1 Like

Using python 2.7:

from sseclient import SSEClient 
import requests, json

messages = SSEClient('{EVENT FILTER}?access_token={ACCESS TOKEN}')

for msg in messages:
    event = str(msg.event).encode('utf-8')
    data = str('utf-8')
    print event
    print data
    dataJson = json.loads(data)

I’m trying to parse simple data from DHT22 temperature humidity sensor from an event stream but with the code above I keep getting
File “/usr/lib/python2.7/json/”, line 338, in loads
return _default_decoder.decode(s)
File “/usr/lib/python2.7/json/”, line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File “/usr/lib/python2.7/json/”, line 384, in raw_decode
raise ValueError(“No JSON object could be decoded”)
ValueError: No JSON object could be decoded

and if I # out the dataJson line and just print the raw event and data I get:


which and the data looks like good json… but I’m a newbie

I’m not a Python guy, but how about removing the event name first and only providing the JSON part of data to the decoder?

This is an old thread but thought I’d add my code in case someone else runs into the same issue. It took me a few hours to figure out. Maybe someone will find it useful and save them time.

#prior code omitted from this post cleanliness
for msg in messages:
    #Get the message event type. This is the Publish Event name. 
    event = str(msg.event)

    #Only add events to SQL that have the event name of "Stat"
    if event == 'Stat':

        #use str and JSON.Loads to decifer string/JSON object from Particle into a Python Dictionary
        data = str(
        msgDict = json.loads(data)
        dataDict = json.loads(msgDict["data"])
        msgDict.update({'data': dataDict})

        #Now that the message from Particle is a Pyhton Dictionary, access info within it like this:

        #Do whatever you want with the data now.