def on_message(self,ch, method, properties, body): print " [x] %r:%r" % (method.routing_key, json.loads(body),) msg = json.loads(body) # if 'Cards in hand' in msg: self.pKeys[method.routing_key] = 1 # if len(self.pKeys) == 1: self.pKeys = {} self.channel.basic_publish(exchange='dealer_exchange_1', routing_key="dealer", body=json.dumps({'method':'action','action':8,'user_id':1, "room_id":1, "private_key":self.users[0].private_key, "amount":20}))
def is_json_by_line_file(input_arg): """ Check is input_arg file contains lines of json. Actually, checks if first line of input_arg is a json. :param input_arg: full path filename (should be openable with open function) :return: boolean """ with open(input_arg, "r") as f: try: json.loads(f.readline()) return True except json.DecodeError: return False
def send_request(url, args = []): response = urllib.urlopen(base_url + "%s?%s" % (url, urllib.urlencode(args + get_args()))) if response.getcode() != 200: raise RequestException("Request fail: %s" % response.read()) if json.__name__ == "cjson": return json.decode(clean_slashes_for_cjson(response.read())) return json.loads(response.read())
def default(self, *args, **kwargs): """ Nimmt die JSON-RPC-Anfrage entgegen und übergibt sie an die entsprechende JSON-RPC-Methode. """ responses = [] # Response content type -> JSON set_content_type_json() # Get data if cherrypy.request.method == "GET": data = kwargs if "params" in data: if self.debug: cherrypy.log("") cherrypy.log(u"params (raw): " + repr(data["params"])) cherrypy.log("") try: data["params"] = json.loads(data["params"]) except _ParseError, err: traceback_info = "".join(traceback.format_exception(*sys.exc_info())) cherrypy.log(traceback_info) return json.dumps( responses.ParseErrorResponse( data = unicode(err) ).to_dict() ) requests = [data]
def load(self): """ Load data in self.input_data :return: yield self.input_data json loaded """ yield json.loads(self.input_data)
def test_ask(self): """ Test the "ask" Tropo class method. """ tropo = Tropo() tropo.ask("[5 digits]", say = Say("Please enter a 5 digit zip code").json) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_ask=================" print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"ask": {"say": {"value": "Please enter a 5 digit zip code"}, "choices": {"value": "[5 digits]"}}}]}' wanted_obj = jsonlib.loads(wanted_json) # print "test_ask: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def _do_post(self, url, data, limit=None): """ Send a JSON payload with a string for ranking or sorting. """ payload = {} response = {} http = httplib2.Http(".cache") # Data can't be an empty string. if not data: raise LingAPIException("Empty required parameter: %s" % arg) payload['string'] = data if limit: payload['limit'] = limit resp, content = http.request( url, "PUT", body=json.dumps(payload), headers={'content-type': 'application/json'}) if resp.status == 200: response["response"] = resp response["content"] = json.loads(content) else: print url raise LingAPIException("Response failed with status code: %s" % resp["status"]) return response
def __init__(self, result_json): result_data = jsonlib.loads(result_json) result_dict = result_data['result'] for opt in self.options_array: if result_dict.get(opt, False): setattr(self, '_%s' % opt, result_dict[opt])
def _do_post(self, url, data, limit=None): """ Send a JSON payload with a string for ranking or sorting. """ payload = {} response = {} http = httplib2.Http(".cache") # Data can't be an empty string. if not data: raise LingAPIException("Empty required parameter: %s" % arg) payload['string'] = data if limit: payload['limit'] = limit resp, content = http.request(url, "PUT", body=json.dumps(payload), headers={'content-type': 'application/json'}) if resp.status == 200: response["response"] = resp response["content"] = json.loads(content) else: print url raise LingAPIException("Response failed with status code: %s" % resp["status"]) return response
def test_hangup(self): """ Test the "hangup" Tropo class method. """ tropo = Tropo() tropo.hangup() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_hangup=================" print "render json: %s" % pretty_rendered # print "test_hangup: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"hangup": null}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_stopRecording(self): """ Test the "stopRecording" Tropo class method. """ tropo = Tropo() tropo.stopRecording() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_stopRecording=================" print "render json: %s" % pretty_rendered # print "test_stopRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"stopRecording": {}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_list_say(self): """ Test the "say" Tropo class method, when a list of Strings is passed to it. """ tropo = Tropo() tropo.say(["Hello, World", "How ya doing?"]) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_list_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": [{"value": "Hello, World"}, {"value": "How ya doing?"}]}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_say(self): """ Test the "say" Tropo class method. """ tropo = Tropo() tropo.say("Hello, World") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "Hello, World"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def fix_line(line): try: rec = loads(line) rec['time'] = rec['time'][:len("2017-02-07T19:11:04")] rec['day'] = rec['time'][:rec['time'].index("T")] return dumps(rec) except: return
def test_hangup(self): """ Test the "hangup" Tropo class method. """ tropo = Tropo() tropo.hangup() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_hangup=================" print "render json: %s" % pretty_rendered # print "test_hangup: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"hangup": {}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_startRecording(self): """ Test the "startRecording" Tropo class method. """ tropo = Tropo() tropo.startRecording(self.RECORDING_URL) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print("===============test_startRecording=================") print("render json: %s" % pretty_rendered) # print "test_startRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"startRecording": {"url": "/receive_recording.py"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_list_say(self): """ Test the "say" Tropo class method, when a list of Strings is passed to it. """ tropo = Tropo() tropo.say(["Hello, World", "How ya doing?"], promptLogSecurity = "suppredd") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_list_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": [{"value": "Hello, World", "promptLogSecurity": "suppredd"}, {"value": "How ya doing?", "promptLogSecurity": "suppredd"}]}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def __init__(self, session_json): logging.info ("POST data: %s" % session_json) session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] logging.info ("key: %s val: %s" % (key, val)) setattr(self, key, val)
def __init__(self, session_json): logging.info("POST data: %s" % session_json) session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] logging.info("key: %s val: %s" % (key, val)) setattr(self, key, val)
def __init__(self, result_json): logging.info("result POST data: %s" % result_json) result_data = jsonlib.loads(result_json) result_dict = result_data["result"] for opt in self.options_array: if result_dict.get(opt, False): setattr(self, "_%s" % opt, result_dict[opt])
def test_startRecording(self): """ Test the "startRecording" Tropo class method. """ tropo = Tropo() tropo.startRecording(self.RECORDING_URL) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_startRecording=================" print "render json: %s" % pretty_rendered # print "test_startRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"startRecording": {"url": "/receive_recording.py"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_say(self): """ Test the "say" Tropo class method. """ tropo = Tropo() tropo.say("Hello, World", promptLogSecurity='soppress') rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_say=================" print "render json: %s" % pretty_rendered # print "test_say: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "Hello, World", "promptLogSecurity": "soppress"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_message(self): """ Test the "message" Tropo class method. """ tropo = Tropo() tropo.message("Hello World", self.MY_PHONE, channel='TEXT', network='SMS', timeout=5, promptLogSecurity = 'suppress') rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_message=================" print "render json: %s" % pretty_rendered # print "test_message: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"message": {"to": "%s", "say": {"value": "Hello World"}, "promptLogSecurity": "suppress", "network": "SMS", "timeout": 5, "channel": "TEXT"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_message(self): """ Test the "message" Tropo class method. """ tropo = Tropo() tropo.message("Hello World", self.MY_PHONE, channel='TEXT', network='SMS', timeout=5) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_message=================" print "render json: %s" % pretty_rendered # print "test_message: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"message": {"to": "%s", "say": {"value": "Hello World"}, "network": "SMS", "timeout": 5, "channel": "TEXT"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def send_request(url, args =[]): g_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) response = urllib.request.urlopen(base_url + "%s?%s" % (url, urllib.parse.urlencode(args + get_args())), context=g_context) if response.getcode() != 200: raise Exception("Request fail: %s" % response.read()) if json.__name__ == "cjson": return json.decode(clean_slashes_for_cjson(response.read())) return json.loads(response.read())
def test_stopRecording(self): """ Test the "stopRecording" Tropo class method. """ tropo = Tropo() tropo.stopRecording() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_stopRecording=================" print "render json: %s" % pretty_rendered # print "test_stopRecording: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"stopRecording": null}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_reject(self): """ Test the "reject" Tropo class method. """ tropo = Tropo() tropo.reject() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_reject=================" print "render json: %s" % pretty_rendered print "Want %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"reject": {}}]}' wanted_obj = jsonlib.loads(wanted_json) # print "test_reject: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS', label='labelofcall', voice = 'Tian-tian', callbackUrl = 'foourl', promptLogSecurity = 'suppress') tropo.say ("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print ("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT", "label": "labelofcall", "voice": "Tian-tian", "callbackUrl": "foourl", "promptLogSecurity": "suppress"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def _json_loads(s): try: from cjson import decode as loads except ImportError: try: from json import loads except ImportError: from simplejson import loads return loads(s)
def test_redirect(self): """ Test the "redirect" Tropo class method. """ tropo = Tropo() tropo.redirect(self.MY_PHONE) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print("===============test_redirect=================") print("render json: %s" % pretty_rendered) print("Wanted_Json %s" % tropo.RenderJson()) rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"redirect": {"to": "%s"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_redirect: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS') tropo.say ("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print ("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def load(self): """ Load data in self.input_data :return: yield each line in self.input_data json loaded """ with open(self.input_data, "r") as f: for line in f: yield json.loads(line)
def test_reject(self): """ Test the "reject" Tropo class method. """ tropo = Tropo() tropo.reject() rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_reject=================" print "render json: %s" % pretty_rendered print "Want %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"reject": null}]}' wanted_obj = jsonlib.loads(wanted_json) # print "test_reject: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_call(self): """ Test the "call" Tropo class method. """ tropo = Tropo() tropo.call(self.MY_PHONE, channel='TEXT', network='SMS') tropo.say("Wish you were here") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print("============test_call=============") print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"call": {"to": "%s", "network": "SMS", "channel": "TEXT"}}, {"say": {"value": "Wish you were here"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_call: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_redirect(self): """ Test the "redirect" Tropo class method. """ tropo = Tropo() tropo.redirect(self.MY_PHONE, "fakeredirectname") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_redirect=================" print "render json: %s" % pretty_rendered print "Wanted_Json %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"redirect": {"name": "fakeredirectname", "to": "%s"}}]}' % self.MY_PHONE wanted_obj = jsonlib.loads(wanted_json) # print "test_redirect: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_transfer(self): """ Test the "transfer" Tropo class method. """ tropo = Tropo() tropo.say("One moment please.") tropo.transfer(self.MY_PHONE) tropo.say("Hi. I am a robot") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_transfer=================" print "render json: %s" % pretty_rendered # print "test_transfer: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "One moment please."}}, {"transfer": {"to": "6021234567"}}, {"say": {"value": "Hi. I am a robot"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_conference(self): """ Test the "conference" Tropo class method. """ tropo = Tropo() tropo.conference(self.ID, playTones=True,terminator="#", name="Staff Meeting", mute=False) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_conference=================" print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"conference": {"playTones": true, "mute": false, "name": "Staff Meeting", "id": "foo", "terminator": "#"}}]}' print "wanted_json: %s" % wanted_json wanted_obj = jsonlib.loads(wanted_json) # print "test_conference: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def __init__(self, session_json): session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] if key == "from": setattr(self, "fromaddress", val) else: setattr(self, key, val) setattr(self, 'dict', session_dict)
def test_transfer(self): """ Test the "transfer" Tropo class method. """ tropo = Tropo() tropo.say ("One moment please.") tropo.transfer(self.MY_PHONE) tropo.say("Hi. I am a robot") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_transfer=================" print "render json: %s" % pretty_rendered # print "test_transfer: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "One moment please."}}, {"transfer": {"to": "6021234567"}}, {"say": {"value": "Hi. I am a robot"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def json_process(message): ''' Decode a message from the json format :param message: The message to pre-process :return: The pre-processed message ''' try: message = json.loads(message) except: message = _default_message() return message
def test_conference(self): """ Test the "conference" Tropo class method. """ tropo = Tropo() tropo.conference(self.ID, playTones=True, mute=False, name="Staff Meeting") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_conference=================" print "render json: %s" % pretty_rendered rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"conference": {"playTones": true, "mute": false, "name": "Staff Meeting", "id": "foo"}}]}' print "wanted_json: %s" % wanted_json wanted_obj = jsonlib.loads(wanted_json) # print "test_conference: %s" % tropo.RenderJson() self.assertEqual(rendered_obj, wanted_obj)
def test_transfer(self): """ Test the "transfer" Tropo class method. """ tropo = Tropo() tropo.say ("One moment please.") tropo.transfer(self.MY_PHONE, callbackUrl="http://192.168.26.88:8080/FileUpload/receiveJson", label="woshitestlidela") tropo.say("Hi. I am a robot") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_transfer=================" print "render json: %s" % pretty_rendered # print "test_transfer: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = '{"tropo": [{"say": {"value": "One moment please."}}, {"transfer": {"to": "6021234567", "callbackUrl": "http://192.168.26.88:8080/FileUpload/receiveJson", "label": "woshitestlidela"}}, {"say": {"value": "Hi. I am a robot"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_on(self): """ Test the "on" Tropo class method. """ tropo = Tropo() tropo.on(event="continue", next="/weather.py?uri=end", say="Please hold.") rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_on=================" print "render json: %s" % pretty_rendered # print "test_on: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"on": {"say": {"value": "Please hold."}, "event": "continue", "next": "/weather.py?uri=end"}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def test_record(self): """ Test the "record" Tropo class method. """ tropo = Tropo() url = "/receive_recording.py" choices_obj = Choices("", terminator="#").json tropo.record(say="Tell us about yourself", url=url, choices=choices_obj) rendered = tropo.RenderJson() pretty_rendered = tropo.RenderJson(pretty=True) print "===============test_record=================" print "render json: %s" % pretty_rendered # print "test_record: %s" % tropo.RenderJson() rendered_obj = jsonlib.loads(rendered) wanted_json = ' {"tropo": [{"record": {"url": "/receive_recording.py", "say": {"value": "Tell us about yourself"}, "choices": {"terminator": "#", "value": ""}}}]}' wanted_obj = jsonlib.loads(wanted_json) self.assertEqual(rendered_obj, wanted_obj)
def __init__(self, session_json): logging.info("POST data: %s" % session_json) session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] logging.info("key: %s val: %s" % (key, val)) if key == "from": setattr(self, "fromaddress", val) else: setattr(self, key, val) setattr(self, 'dict', session_dict)
def __init__(self, session_json): logging.info ("POST data: %s" % session_json) session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] logging.info ("key: %s val: %s" % (key, val)) if key in keyword.kwlist: key = key + '_' logging.info ("changed key: %s val: %s" % (key, val)) setattr(self, key, val)
def __init__(self, session_json): logging.info ("POST data: %s" % session_json) session_data = jsonlib.loads(session_json) session_dict = session_data['session'] for key in session_dict: val = session_dict[key] logging.info ("key: %s val: %s" % (key, val)) if key == "from": setattr(self, "fromaddress", val) else: setattr(self, key, val) setattr(self, 'dict', session_dict)
def loads(data, use_datetime=False, use_builtin_types=None): """data -> unmarshalled data, method name Convert an JSON-RPC packet to unmarshalled data plus a method name (None if not present). If the JSON-RPC packet represents a fault condition, this function raises a Fault exception. """ if hasattr(data, 'read'): data = data.read() if isinstance(data, bytes): r = json.loads(data.decode('utf8'), object_hook=_object_hook) else: r = json.loads(data, object_hook=_object_hook) if "method" in r: params = r.pop("params") if "params" in r else [] kwargs = r.pop("kwargs") if "kwargs" in r else {} return params, kwargs, r['method'] elif "result" in r: return r.pop("result"), {}, None else: raise Fault(*r.pop("error"))
def find_input_loader(input_arg): """ Test input_arg to determine with private loader (defined in this module) should be used. :param input_arg: can be - dictionary - other iterable - json (string) - json file (one json per line in file) - csv (string) - csv file - gz file - directory :return: selected loader class """ if isinstance(input_arg, dict): return _DictLoader if isinstance(input_arg, basestring): try: json.loads(input_arg) return _JsonLoader except json.DecodeError: if os.path.isfile(input_arg): try: with gzip.open(input_arg, "r") as f: f.read(1) return _GzLoader except IOError: if is_json_by_line_file(input_arg): return _JsonLineFileLoader return _CsvFileLoader if os.path.exists(input_arg): return _DirLoader if hasattr(input_arg, "__iter__"): return _GenericIterableLoader return _CsvLoader
def get(cls, keys): rows = cls._cf.multiget(keys, include_timestamp=True, column_count=tdb_cassandra.max_column_count) res = {} for row, columns in rows.iteritems(): data = [] timestamps = [] for (key, (value, timestamp)) in columns.iteritems(): value = json.loads(value) data.append((key,) + tuple(value)) timestamps.append((key, timestamp)) res[row] = (data, dict(timestamps)) return res
while THROTTLE > 1150: # Check whether QuadTarget process is still running poll = p.poll() if poll is not None: break # Clear QuadTarget output, so that we'll get the newest data. # p.stdout.flush() # Read JSON data from QuadTarget and decode it. p.stdin.write('\n') out = p.stdout.readline() if out != "": try: decoded = json.loads(out) dist = 1.0 if 'target' in decoded and decoded['target'] is not None: dist = float(decoded['target']['distance(m)']) if dist > max_dist: dist = max_dist if dist < 1: dist = 1.0 raw_pitch = 0.5 - (1.0 - decoded['sticks']['pitch']) raw_roll = 0.5 - decoded['sticks']['roll'] raw_yaw = decoded['sticks']['yaw'] PITCH = int(center - ((raw_pitch * dist) * dist_scale)) ROLL = int(center - ((raw_roll * dist) * dist_scale)) THROTTLE -= 1.0 / dist if raw_yaw < 0: raw_yaw = 1300
def loads(self): return self.mapValues(lambda v: json.loads(v.decode('utf-8')))
def unserialize(filepath, encoding="utf-8"): _file = codecs.open( filepath, 'r', encoding=encoding ) datastruct = loads( _file.read() ) _file.close() return datastruct
def get_data(self, url, force_type = False): response_type = "unknown" req = urllib2.Request(url = url, headers = self.headers) data = False log(self.__class__.__name__ + ": Trying to open %s." % url) try: response = urllib2.urlopen(req) except (urllib2.URLError, urllib2.HTTPError) as e: if DEBUG: log(self.__class__.__name__ + ": %s" % str(e)) log(self.__class__.__name__ + ": Error while opening %s, Fatal." % url ) return(False, response_type) if response.getcode() == 200: response_info = response.info() if "Content-Type" in response_info: if (response_info["Content-Type"].lower().find('json')) > -1: response_type="json" elif (response_info["Content-Type"].lower().find('xml')) > -1: response_type = "xml" else: print(response_info["Content-Type"]) if force_type: if not force_type == response_type: response_type = force_type log(self.__class__.__name__ + ": Response-type data forced to '%s' from %s." % (response_type, url)) else: log(self.__class__.__name__ + ": Response-type data '%s' from %s." % (response_type, url)) else: log(self.__class__.__name__ + ": Response-type data '%s' from %s." % (response_type, url)) if "Content-Length" in response_info: if int(response_info["Content-Length"]) < 5: # No json data available, #doesnotexist log(self.__class__.__name__ + ": Getting %s bytes from %s" % (response_info["Content-Length"], url)) else: log(self.__class__.__name__ + ": Getting %s bytes from %s" % (response_info["Content-Length"], url)) else: log(self.__class__.__name__+ ": Getting ? bytes from %s." % (url)) try: data = response.read() log(self.__class__.__name__+ ": Got %i bytes from %s." % (len(data), url)) except: log(self.__class__.__name__ + ": Error while reading data.") return(False, response_type) if not len(data) > 0: log(self.__class__.__name__+ ": Data size to small (%i bytes) from %s." % (len(data), url)) return(False, response_type) else: log(self.__class__.__name__ + ": Did not get a 200 ok response, got %i." % (response.getcode())) return(False, response_type) if response_type == "xml": try: data = xml_fromstring(data) log(self.__class__.__name__ + ": Converted raw data to xmletree object.") walker=data.iter() for item in walker: print(item, item.tag, item.text) except: log(self.__class__.__name__ + ": Error while converting raw data to xml.") return(False, response_type) if response_type == "feed": try: data = feedparser.parse(data) try: data["feed"].pop("updated_parsed") except: pass log(self.__class__.__name__ + ": Converted raw data to feed object.") #walker=data.iter() #for item in walker: # print(item, item.tag, item.text) except: log(self.__class__.__name__ + ": Error while converting raw data to feed.") return(False, response_type) if response_type == "json": try: data = loads(data) log(self.__class__.__name__ + ": Converted raw data to json.") except: log(self.__class__.__name__ + ": Error while converting raw data to json.") return(False, response_type) return(data, response_type)