def __call__(self, *args, **kwargs): # pull in simplejson imports lazily so that the library isn't required # unless you actually need to do encoding and decoding from simplejson import decoder, encoder postdata = encoder.JSONEncoder().encode({ "method": self.__serviceName, 'params': args + (kwargs, ), 'id': 'jsonrpc' }) request = urllib2.Request(self.__serviceURL, data=postdata, headers=self.__headers) respdata = urllib2.urlopen(request).read() try: resp = decoder.JSONDecoder().decode(respdata) except ValueError: raise JSONRPCException('Error decoding JSON response:\n' + respdata) if resp['error'] is not None: error_message = (resp['error']['name'] + ': ' + resp['error']['message'] + '\n' + resp['error']['traceback']) raise JSONRPCException(error_message) else: return resp['result']
def test_make_iterencode(self): """ Description: Tests that the _make_iterencode_() function properly configures a generator function to yield JSON string tokens with default values. Input: A set of correct parameters where 'markers' is {} while the rest of the required parameters are initialized to their default values taken from JSONEncoder. Output: (generator): A generator function that yields JSON string tokens. Test Case: Corresponds to test case TEST-0026. """ test_input = { "nums": [0, 1, 2], "int": 0, "kvs": { "abc": 0, "def": 1, "ghi": 2 } } test_output = "{\"nums\": [0, 1, 2], \"int\": 0, \"kvs\": {\"abc\": 0, \"def\": 1, \"ghi\": 2}}" encdr = encoder.JSONEncoder() self.assertEqual(encdr.encode(test_input), test_output)
def test_json_encoder_iterencode_none(self): """ Description: Tests that JSONEncoder : iterencode() yields ‘null’. Input: (None) Output: (generator): A generator function that yields the encoded version of the Python None type. Test Case: Corresponds to test case TEST-0044. """ encdr = encoder.JSONEncoder() self.assertEqual(next(encdr.iterencode(None)), "null")
def test_json_encoder_encode_none(self): """ Description: Tests that JSONEncoder : encode() returns the JSON ‘null’ type. Input: (None): The Python None type. Output: (str): 'null'. Test Case: Corresponds to test case TEST-0042. """ test_input = None encdr = encoder.JSONEncoder() self.assertEqual(encdr.encode(test_input), "null")
def test_create_json_encoder(self): """ Description: Tests that a JSONEncoder object can be created with default options. Input: Assume all parameters for the JSONEncoder are initialized to their defaults. Output: (JSONEncoder): A JSONEncoder object initialized to the default configuration. Test Case: Corresponds to test case TEST-0040. """ encdr = encoder.JSONEncoder() self.assertIsInstance(encdr, encoder.JSONEncoder)
def test_json_encoder_encode_correct(self): """ Description: Tests that JSONEncoder : encode() returns a string containing encoded JSON from a Python object. Input: (Object): A Python object. Output: (str): An encoded JSON string corresponding to the input object. Test Case: Corresponds to test case TEST-0041. """ test_input = {"abc": 0, "def": 1, "ghi": 2} test_output = [ '{', '"abc"', ': ', '0', ', ', '"def"', ': ', '1', ', ', '"ghi"', ': ', '2', '}' ] encdr = encoder.JSONEncoder() gen = encdr.iterencode(test_input) for token in test_output: self.assertEqual(next(gen), token)
def test_json_encoder_iterencode_correct(self): """ Description: Tests that JSONEncoder : iterencode() yields encoded JSON chunks from a Python object. Input: (Object): A Python object. Output: (generator): A Python generator that yields chunks of the encoded Python object. Test Case: Corresponds to test case TEST-0043. """ test_input = {"abc": 0, "def": 1, "ghi": 2} test_output = [ '{', '"abc"', ': ', '0', ', ', '"def"', ': ', '1', ', ', '"ghi"', ': ', '2', '}' ] encdr = encoder.JSONEncoder() gen = encdr.iterencode(test_input) for token in test_output: self.assertEqual(token, next(gen))
_MULTIPLE_PLOT_HEIGHT_PER_PLOT = 4 _MULTIPLE_PLOT_MARKER_TYPE = 'o' _MULTIPLE_PLOT_MARKER_SIZE = 4 _SINGLE_PLOT_STYLE = 'bs-' # blue squares with lines connecting _SINGLE_PLOT_ERROR_BAR_COLOR = 'r' _LEGEND_FONT_SIZE = 'xx-small' _LEGEND_HANDLE_LENGTH = 0.03 _LEGEND_NUM_POINTS = 3 _LEGEND_MARKER_TYPE = 'o' _LINE_XTICK_LABELS_SIZE = 'x-small' _BAR_XTICK_LABELS_SIZE = 8 _json_encoder = encoder.JSONEncoder() class NoDataError(Exception): """ Exception to raise if the graphing query returned an empty resultset. """ def _colors(n): """ Generator function for creating n colors. The return value is a tuple representing the RGB of the color. """ for i in xrange(n):
def test_bad_encoding(self): with self.assertRaises(UnicodeEncodeError): encoder.JSONEncoder(encoding='\udcff').encode({b('key'): 123})
def test(): encoder.JSONEncoder(int_as_string_bitcount=long_count).encode(0)
def test(name): encoder.JSONEncoder(**{name: BadBool()}).encode({})
def updateGrovestreams(): # This is VERY different from their examples. I named # my streams with something I could understand and read # Probably not the best way to do it, but it works really # well for me. component_id = "desert-home-id" rpowerStream_id = "power_usage" otempStream_id = "outside_temp" apowerStream_id = "apparent_power" voltageStream_id = "voltage" currentStream_id = "current" pfactorStream_id = "power_factor" itempStream_id = "inside_temp" ptempStream_id = "pool_temp" pmotorStream_id = "pool_motor" frequencyStream_id = "frequency" # This object really helps when displaying # the rather complex data below pp = pprint.PrettyPrinter(depth=10) #get the millis since epoch # in unix the epoch began back in 1970, look it up now = datetime.now() nowEpoch = int(time.mktime(now.timetuple())) * 1000 #assemble feed and convert it to a JSON string feed = {} feed['feed'] = {} feed['feed']['component'] = [] if DEBUG: pp.pprint(feed) print sys.stdout.flush() comp = {} comp['stream'] = [] comp['componentId'] = component_id feed['feed']['component'].append(comp) if DEBUG: pp.pprint(feed) print sys.stdout.flush() # Now I'm going to fill in the stream values, open database # I took a brute force approach to building the dictionary that # is converted into JSON. I could have been much more elegant # in building it, but the folks just starting out would have # had a tough time understanding it dbconn = sqlite3.connect(DATABASE) c = dbconn.cursor() # So, you make a stream to stuff things into. It's actually # a python dictionary that we'll pass to a JSON encoder a ways # down into the code. I'll be adding entries to this as I pull # items out of the database stream1 = {} stream1['streamId'] = rpowerStream_id stream1['time'] = [] stream1['data'] = [] comp['stream'].append(stream1) current_value = c.execute("select rpower from power").fetchone()[0] stream1['time'].append(nowEpoch) stream1['data'].append(float(current_value)) # this is a cool way to debug this kind of thing. if DEBUG: pp.pprint(feed) print sys.stdout.flush() # notice how I get an item out of the database # and add it to the dictionary. I'll do this # several times stream2 = {} stream2['streamId'] = otempStream_id stream2['time'] = [] stream2['data'] = [] comp['stream'].append(stream2) current_value = c.execute( "select temperature from Barometer").fetchone()[0] stream2['time'].append(nowEpoch) stream2['data'].append(float(current_value)) stream3 = {} stream3['streamId'] = apowerStream_id stream3['time'] = [] stream3['data'] = [] comp['stream'].append(stream3) current_value = c.execute("select apower from power").fetchone()[0] stream3['time'].append(nowEpoch) stream3['data'].append(float(current_value)) stream4 = {} stream4['streamId'] = voltageStream_id stream4['time'] = [] stream4['data'] = [] comp['stream'].append(stream4) current_value = c.execute("select voltage from power").fetchone()[0] stream4['time'].append(nowEpoch) stream4['data'].append(float(current_value)) stream5 = {} stream5['streamId'] = currentStream_id stream5['time'] = [] stream5['data'] = [] comp['stream'].append(stream5) current_value = c.execute("select current from power").fetchone()[0] stream5['time'].append(nowEpoch) stream5['data'].append(float(current_value)) stream6 = {} stream6['streamId'] = pfactorStream_id stream6['time'] = [] stream6['data'] = [] comp['stream'].append(stream6) current_value = c.execute("select pfactor from power").fetchone()[0] stream6['time'].append(nowEpoch) stream6['data'].append(float(current_value)) stream7 = {} stream7['streamId'] = itempStream_id stream7['time'] = [] stream7['data'] = [] comp['stream'].append(stream7) current_value = c.execute( "select avg(\"temp-reading\") from thermostats").fetchone()[0] stream7['time'].append(nowEpoch) stream7['data'].append(float(current_value)) stream8 = {} stream8['streamId'] = ptempStream_id stream8['time'] = [] stream8['data'] = [] comp['stream'].append(stream8) current_value = c.execute("select ptemp from pool").fetchone()[0] stream8['time'].append(nowEpoch) stream8['data'].append(float(current_value)) stream9 = {} stream9['streamId'] = pmotorStream_id stream9['time'] = [] stream9['data'] = [] comp['stream'].append(stream9) tmp = c.execute("select motor from pool").fetchone()[0] if (tmp == 'High'): # a little special handling for the pool motor motor = 2 elif (tmp == 'Low'): motor = 1 else: motor = 0 stream9['time'].append(nowEpoch) stream9['data'].append(int(motor)) stream10 = {} stream10['streamId'] = frequencyStream_id stream10['time'] = [] stream10['data'] = [] comp['stream'].append(stream10) current_value = c.execute("select frequency from power").fetchone()[0] stream10['time'].append(nowEpoch) stream10['data'].append(float(current_value)) # all the values are filled in, close the database # update the time in the database c.execute("update grovestream set utime=?;", (dbTime(), )) dbconn.commit() dbconn.close() # close the data base # This will print the entire dictionary I just constructed # so you can see what is going on if DEBUG: pp.pprint(feed) print sys.stdout.flush() # exit() # I put this in for debugging. It exits before # the JSON string is constructed and sent off to grovestreams # Of course you want to keep it commented until needed # # And this is where the JSON string is built encoder = jsonEncoder.JSONEncoder() json = encoder.encode(feed) # and this will print it so you can see what is happening if DEBUG: print json # for debugging print sys.stdout.flush() #Upload the feed try: lprint("Updating GroveStream") conn = httplib.HTTPConnection('www.grovestreams.com', timeout=10) url = '/api/feed?&org=%s&api_key=%s' % (org, api_key) compress = True if compress: body = compressBuf(json) headers = { "Content-type": "application/json", "Content-Encoding": "gzip" } else: body = json headers = {"Content-type": "application/json", "charset": "UTF-8"} conn.request("PUT", url, body, headers) response = conn.getresponse() status = response.status if status != 200 and status != 201: try: if (response.reason != None): lprint('reason: ' + response.reason + ' body: ' + response.read()) else: lprint('body: ' + response.read()) except Exception: lprint('HTTP Fail Status: %d' % (status)) return except Exception as e: lprint('HTTP Send Error: ' + str(e)) return finally: if conn != None: conn.close()