def post(self): # Get route to database user_collection = app.db.users # JSON to post json = request.json #Getting password from client password = json.get('password') print(password) # Encrypting password by using a hash function and salt encoded_password = password.encode('utf-8') hashed = bcrypt.hashpw( encoded_password, bcrypt.gensalt(app.bcrypt_rounds) ) json['password'] = hashed print("This is the json " + str(json)) if 'username' in json and 'email' in json and 'password' in json: user = user_collection.find_one({'email': json['email']}) if user is not None: # User exists return({'error': 'User already exists'}, 409, None) user_collection.insert_one(json) json.pop('password') return (json, 201, None) else: return(None, 404, None)
def updatePrice(self, id, price): response = requests.get(self.api + "/api/houses/" + id) if not response.ok: return response.ok json = response.json() json["LastVisit"] = datetime.now().isoformat() if json["Price"].lower() == price.lower(): response = requests.put(self.api + "/api/houses/" + id, data = json) return True #if json["History"] == None: # json["History"] = "" #json["History"] = HistoryPattern.format(json["History"], datetime.now().isoformat(), json["Price"]) json.pop('HouseHistories', None) json["Price"] = price response = requests.put(self.api + "/api/houses/" + id, data = json) if not response.ok: print("update House failed " + id) #add history instead history = {} history['houseid']= id history['ChangedAt'] = json["LastVisit"] history['Price'] = price response = requests.post(self.api + "/api/househistories", json = history) return True
def check_param_of_model_json (json): """ Check validity of params of model json. It need each one of next parameters: model_type and organization. :param json: json dict of data with parameters to check :type json: dict :returns: response :rtype: boolean """ commun = check_commun_params_json(json) if commun is True : if 'model_type' in json : if json['model_type'] != "" : if len(Param_ModelType.objects.filter(authorized_value=json['model_type'])) != 1 : return ("You gave an invalid model_type parameter") else : json.pop('model_type', None) if 'organization' in json : if json['organization'] != "" : if len(Param_organizations.objects.filter(authorized_value=json['organization'])) != 1 : return ("You gave an invalid organization parameter") else : json.pop('organization', None) return (True) else : return (commun)
def check_param_of_test_json (json): """ Check validity of params of test json. It need each one of next parameters: data_modality, test_type and score_type. :param json: json dict of data with parameters to check :type json: dict :returns: response :rtype: boolean """ commun = check_commun_params_json(json) if commun is True : if 'data_modality' in json : if json['data_modality'] != "" : if len(Param_DataModalities.objects.filter(authorized_value=json['data_modality'])) != 1 : return ("You gave an invalid data_modality parameter") else : json.pop('data_modality', None) if 'test_type' in json : if json['test_type'] != "" : if len(Param_TestType.objects.filter(authorized_value=json['test_type'])) != 1 : return ("You gave an invalid test_type parameter") else : json.pop('test_type', None) # if 'score_type' in json : # if json['score_type'] != "" : # if len(Param_ScoreType.objects.filter(authorized_value=json['score_type'])) != 1 : # return ("You gave an invalid score_type parameter") # else : # json.pop('score_type', None) return (True) else : return (commun)
def couchdb_json_to_doc(json, id=None): """Returns a doc, todo tuple. The first is either a LocalDocument or a Document, while the second contains follow: true attachments that still have to be added to doc.attachments to complete the conversion. """ id = json.pop('_id', id) # default to None for local docs: try: rev_num, rev_hash = parse_rev(json.pop('_rev')) except KeyError: revs_default = None else: revs_default = {'start': rev_num, 'ids': [rev_hash]} revs = json.pop('_revisions', revs_default) is_deleted = json.get('_deleted', False) body = None if is_deleted else json todo = [] if id.startswith('_local/'): id = id[len('_local/'):] doc = LocalDocument(id, body) else: atts = None if body is None else parse_attachments(body, todo) rev_num, path = revs['start'], tuple(revs['ids']) doc = Document(id, rev_num, path, body, atts, is_deleted) return doc, todo
def sign_json(self, json): """Signs a JSON object. NOTE: The object is modified in-place and the return value can be ignored. As specified, this is done by encoding the JSON object without ``signatures`` or keys grouped as ``unsigned``, using canonical encoding. Args: json (dict): The JSON object to sign. Returns: The same JSON object, with a ``signatures`` key added. It is formatted as ``"signatures": ed25519:<device_id>: <base64_signature>``. """ signatures = json.pop('signatures', {}) unsigned = json.pop('unsigned', None) signature_base64 = self.olm_account.sign(encode_canonical_json(json)) key_id = 'ed25519:{}'.format(self.device_id) signatures.setdefault(self.user_id, {})[key_id] = signature_base64 json['signatures'] = signatures if unsigned: json['unsigned'] = unsigned return json
def from_mongodb(self, json) -> Dict: """ Get HWPCReport from a MongoDB database. { 'timestamp': $int, 'sensor': '$str', 'target': '$str', 'groups' : { '$group_name': { '$socket_id': { '$core_id': { '$event_name': '$int', ... } ... } ... } ... } """ # Re arrange the json before return it by removing '_id' field json.pop('_id', None) return json
def flatten(json, veld): for key in json[veld]: if key in json: raise (Exception('Key {} allready existst'.format(key))) json[key] = json[veld][key] json.pop(veld) return json
def flatten_json(json): if type(json) == dict: for k, v in list(json.items()): if type(v) == dict: flatten_json(v) json.pop(k) for k2, v2 in v.items(): json[k+"."+k2] = v2
def video_json(cls, video): json = video.to_json() rentals = Rental.query.filter_by(video_id = video.video_id).count() checked_out_count = rentals total_inventory = json["inventory"] json.pop("inventory") json["total_inventory"] = total_inventory json["available_inventory"] = total_inventory - checked_out_count return json
def _get_with_fallback(json: dict[str, Any], field: str, unstable_prefix: str, default: Any = None) -> Any: try: return json.pop(field) except KeyError: try: return json.pop(f"{unstable_prefix}.{field}") except KeyError: return default
def check_in(cls, data): errors = cls.validate_data(data) if errors: return (make_response(errors, 400)) rental = Rental.query.get((data["customer_id"], data["video_id"])) if not rental: return (make_response({"errors": "No such rental"}, 400)) db.session.delete(rental) db.session.commit() json = cls.rental_json(rental) json.pop("due_date") return make_response(json, 200)
def _make_url_refs_opaque(json): if isinstance(json, dict): for key in json: if key == '$ref' and isinstance(json[key], basestring)\ and json[key].startswith('https://delphix.com/platform/api#'): json.pop(key) json['type'] = 'object' else: _make_url_refs_opaque(json[key]) elif isinstance(json, list): for element in json: _make_url_refs_opaque(element)
def server_ping(app): # Handler for sync ping json = get_ping_params(app) if json["tls_created_at"] is None: json.pop("tls_created_at") logger.info(f"Pinging control server! - {json}") r = httpx.post(f"{app.api_server}/ping", verify=False, json=json, headers=default_ping_headers) if r.status_code == httpx.codes.OK: return handle_ping(app, r.json()) else: logger.error(f"Ping errored out! - {r.text}")
def _object_hook(json): filename = json.pop('__rfm_file__', None) typename = json.pop('__rfm_class__', None) if filename is None or typename is None: return json mod = util.import_module_from_file(filename) cls = getattr(mod, typename) obj = cls.__new__(cls) obj.__dict__.update(json) if hasattr(obj, '__rfm_json_decode__'): obj.__rfm_json_decode__(json) return obj
def generate_calls(self, api): payload = api.get("payload") # print payload if payload: json = self.parse_dict(payload) call_url = "" if re.search((r'<get#'), api.get("url")): url_split = api.get("url").split("/") for split_data in url_split: if "<get#" in split_data: new_uuid = self.get_value( self.get_calls[self.get_get_calls(split_data)]) index = url_split.index(split_data) url_split[index] = new_uuid call_url = "/".join(url_split[3::]) del_url = "/".join(url_split[3:index + 1:]) self.delete_dict[new_uuid] = del_url else: call_url = "/".join(api.get("url").split("/")[3::]) response = self.client.get(url=call_url, verify=False) if response.status_code == 200: resp = response.json() for entity in resp["entities"]: if payload["name"] in entity.values(): return print "+" * 100 print json print "+" * 100 if json.get("vm_disks"): json.pop("vm_disks") if api.get("wait_for_task"): response = self.client.post(url=call_url, json=json, verify=False) if response: task_details = response.json() if task_details.get("task_uuid"): self.wait_for_task(task_details.get("task_uuid")) else: self.client.post(url=call_url, json=json, verify=False) if self.delete_dict: for uuid, url in self.delete_dict.iteritems(): self.client.delete(url=url) self.delete_dict.pop(uuid)
def check_json(self, json, typ, msg): import iso8601 # Check the type. jsontype = json.pop("type") self.assertEqual(jsontype, typ) # Check the message. jsonmsg = json.pop("message") self.assertEqual(jsonmsg, msg) # Check the timestamp. jsonts = json.pop("timestamp") dt = iso8601.parse_date(jsonts) now = datetime.datetime.now(dt.tzinfo) self.assertGreater(now, dt) # Check there are no more keys left (and thus not previously tested). self.assertEqual(len(json), 0)
def create_dict(json): dict = {} stateIdx = -1 popIdx = -1 for i in range(len(json[0])): if (json[0][i] == "NAME"): stateIdx = i elif (json[0][i] == "POP"): popIdx = i json.pop(0) for item in json: dict[item[stateIdx]] = int(item[popIdx]) return dict
def extractJson(params): json = vars(params) json.pop("cmd") json.pop("httpdetail") json.pop("pgid") json.pop("modelid") return json
def convert_notification(self, xml_string): '''Converts the given XML Notification string into JSON Returns converted JSON string ''' # Assuming 'notification' tag and 'eventTime' to be present, since the # ncclient would have done the correct validation notification = lxml.etree.fromstring(xml_string) json = [] json.append('{"notification" : ') json.append('{"eventTime" : ') # The first element in notification is always 'eventTime' json.append('"' + notification[0].text + '"') json.append(",") prefixes = [] for element in notification[1:]: qelem = lxml.etree.QName(element) name, prefix, prefixes = _split_tag_and_update_prefixes( element, prefixes) schema_node = self._schema.search_child(qelem.localname, qelem.namespace) if schema_node is None: self._logger.error( "Notification: Unable to find node %s{%s} in loaded schema", qelem.localname, qelem.namespace) return None # Node should be of type notification if schema_node.get_stmt_type() != RwYang.StmtType.STMT_TYPE_NOTIF: self._logger.error( "Notification schema node - invalid type. Expected "+\ "STMT_TYPE_NOTIF, got %s", schema_node.get_stmt_type()) return None json.append('"%s%s" : {' % (prefix, name)) tstr = self._translate_node(False, schema_node, element, prefixes) json.append(tstr) json.append("}") json.append(",") json.pop() # Pops the last ',' json.append("}") json.append("}") result = ''.join(json) return result
def _bind_json(self, json): # generally, not required for override. instead use _bind_custom_json # if possible if not isinstance(json, dict): self._binding_failed('expected dict, got %s', type(json)) for binding in self._bindings: val = json.pop(binding.name, None) if binding.expected and val is None: self._binding_failed('expected val for %s', binding.name) if binding.binding and val is not None: if issubclass(binding.binding, PermSpecConverterBase): if isinstance(val, list): val = [ binding.binding(v, getattr(self, '_resource', None), parent=self) for v in val ] else: val = binding.binding(val, getattr(self, '_resource', None), parent=self) else: if isinstance(val, list): val = [binding.binding(v, parent=self) for v in val] else: val = binding.binding(val, parent=self) setattr(self, binding.name, val) self._bind_custom_json(json)
def formatRecord(json): for key in json.keys(): new_key = formatName(key, "field") json[new_key] = json.pop(key) if isinstance(json[new_key], dict) == True: json[new_key] = formatRecord(json[new_key]) return json
def list_rentals(cls, customer_id): db_results = db.session.query(Video, Rental, Customer)\ .join(Rental, Rental.video_id==Video.video_id)\ .join(Customer, Rental.customer_id==Customer.customer_id)\ .filter(Customer.customer_id == customer_id).all() result = [] for element in db_results: video = element[0] rental = element[1] #print(element[2]) json = video.to_json() json.pop("inventory") json["due_date"] = rental.due_date result.append(json) return make_response(jsonify(result), 200)
def ensure_list(json: Dict[str, Any], name: str) -> List[Any]: result = json.pop(name, []) if isinstance(result, list): return result raise InvalidConfiguration( f"Configuration `{name}` is expected to be a list but got `{json}`." )
def convert_notification(self, xml_string): '''Converts the given XML Notification string into JSON Returns converted JSON string ''' # Assuming 'notification' tag and 'eventTime' to be present, since the # ncclient would have done the correct validation notification = lxml.etree.fromstring(xml_string) json = [] json.append('{"notification" : ') json.append('{"eventTime" : ') # The first element in notification is always 'eventTime' json.append('"' + notification[0].text + '"') json.append(",") prefixes = [] for element in notification[1:]: qelem = lxml.etree.QName(element) name, prefix, prefixes = _split_tag_and_update_prefixes(element, prefixes) schema_node = self._schema.search_child(qelem.localname, qelem.namespace) if schema_node is None: self._logger.error( "Notification: Unable to find node %s{%s} in loaded schema", qelem.localname, qelem.namespace) return None # Node should be of type notification if schema_node.get_stmt_type() != RwYang.StmtType.STMT_TYPE_NOTIF: self._logger.error( "Notification schema node - invalid type. Expected "+\ "STMT_TYPE_NOTIF, got %s", schema_node.get_stmt_type()) return None json.append('"%s%s" : {' % (prefix, name)) tstr = self._translate_node(False, schema_node, element, prefixes) json.append(tstr) json.append("}") json.append(",") json.pop() # Pops the last ',' json.append("}") json.append("}") result = ''.join(json) return result
def from_json(cls, json): """Create a recipe from a JSON dict""" steps = json.pop('steps') strategy = cls(**json) strategy.steps = [(MonitorStep if kw.get('monitor') else Step) .from_json(**kw) for kw in steps] return strategy
def from_builtin(self, json): """ Decode a simple Python representation (dict, list, str, float, bool, None) of a value of the attribute that is compatible with JSON and YAML Args: json (:obj:`dict`): simple Python representation of a value of the attribute Returns: :obj:`Bio.motifs.matrix.FrequencyPositionMatrix`: decoded value of the attribute """ if json is None: return None else: json = copy.copy(json) alphabet = json['_alphabet'] json.pop('_alphabet') return Bio.motifs.matrix.FrequencyPositionMatrix(alphabet, json)
def post(self): """POST is used when authenticating via the mobile application.""" yield gen.Task(self._StartJSONRequest, 'verify', self.request, json_schema.VERIFY_VIEWFINDER_REQUEST) # Validate the identity and access token. identity = yield Identity.VerifyConfirmedIdentity(self._client, self._request_message.dict['identity'], self._request_message.dict['access_token']) # Get the ShortURL associated with the access token. group_id = identity.json_attrs['group_id'] random_key = identity.json_attrs['random_key'] short_url = yield gen.Task(ShortURL.Query, self._client, group_id, random_key, None) # Extract parameters that shouldn't be passed to handler. json = short_url.json self._action = json.pop('action') json.pop('identity_key') json.pop('user_name') json.pop('access_token') # If there is no verification handler, then token was not intended to be redeemed via # /verify/viewfinder. handler = VerifyIdBaseHandler.ACTION_MAP[self._action].handler if handler is None: raise InvalidRequestError(INVALID_VERIFY_VIEWFINDER, action=self._action) # Invoke the action handler. handler(self, self._client, **json)
def post(self): """POST is used when authenticating via the mobile application.""" yield gen.Task(self._StartJSONRequest, 'verify', self.request, json_schema.VERIFY_VIEWFINDER_REQUEST) # Validate the identity and access token. identity = yield Identity.VerifyConfirmedIdentity( self._client, self._request_message.dict['identity'], self._request_message.dict['access_token']) # Get the ShortURL associated with the access token. group_id = identity.json_attrs['group_id'] random_key = identity.json_attrs['random_key'] short_url = yield gen.Task(ShortURL.Query, self._client, group_id, random_key, None) # Extract parameters that shouldn't be passed to handler. json = short_url.json self._action = json.pop('action') json.pop('identity_key') json.pop('user_name') json.pop('access_token') # If there is no verification handler, then token was not intended to be redeemed via # /verify/viewfinder. handler = VerifyIdBaseHandler.ACTION_MAP[self._action].handler if handler is None: raise InvalidRequestError(INVALID_VERIFY_VIEWFINDER, action=self._action) # Invoke the action handler. handler(self, self._client, **json)
def _build_req_args( *, token: Optional[str], http_verb: str, files: dict, data: dict, default_params: dict, params: dict, json: dict, # skipcq: PYL-W0621 headers: dict, auth: dict, ssl: Optional[SSLContext], proxy: Optional[str], ) -> dict: has_json = json is not None has_files = files is not None if has_json and http_verb != "POST": msg = "Json data can only be submitted as POST requests. GET requests should use the 'params' argument." raise SlackRequestError(msg) if data is not None and isinstance(data, dict): data = {k: v for k, v in data.items() if v is not None} _set_default_params(data, default_params) if files is not None and isinstance(files, dict): files = {k: v for k, v in files.items() if v is not None} # NOTE: We do not need to all #_set_default_params here # because other parameters in binary data requests can exist # only in either data or params, not in files. if params is not None and isinstance(params, dict): params = {k: v for k, v in params.items() if v is not None} _set_default_params(params, default_params) if json is not None and isinstance(json, dict): _set_default_params(json, default_params) token: Optional[str] = token if params is not None and "token" in params: token = params.pop("token") if json is not None and "token" in json: token = json.pop("token") req_args = { "headers": _get_headers( headers=headers, token=token, has_json=has_json, has_files=has_files, request_specific_headers=headers, ), "data": data, "files": files, "params": params, "json": json, "ssl": ssl, "proxy": proxy, "auth": auth, } return req_args
def ensure_option_type(json: Dict[str, Any], name: str, expected_type: Type[T]) -> Optional[T]: result = json.pop(name, None) if result is None: return None elif isinstance(result, expected_type): return result raise InvalidConfiguration( f"Configuration `{name}` is expected to have type " f"{expected_type} but got: `{json}`.")
def count_duplicates_within_source(json): unique = set() new_map = dict() source = json['source'] json.pop('source') for k, v in json.iteritems(): new_map[k] = dict() for string in v: if string not in unique: unique.add(string) new_map[k].update({string: { 'source': source, 'count': 1 } }) else: new_map[k][string]['count'] += 1 return new_map
def ensure_optional_string_list(json: Dict[str, Any], name: str) -> Optional[List[str]]: result = json.pop(name, None) if result is None: return None elif is_list_of_string(result): return result raise InvalidConfiguration( f"Configuration `{name}` is expected to be a list of " f"strings but got `{json}`.")
def ensure_string_list(json: Dict[str, Any], name: str, allow_single_string: bool = False) -> List[str]: result = json.pop(name, []) if allow_single_string and isinstance(result, str): result = [result] if is_list_of_string(result): return result raise InvalidConfiguration( f"Configuration `{name}` is expected to be a list of " f"strings but got `{json}`.")
def check_param_of_model_json (json): commun = check_commun_params_json(json) if commun is True : if 'model_type' in json : if json['model_type'] != "" : if len(Param_ModelType.objects.filter(authorized_value=json['model_type'])) != 1 : return ("You gave an invalid model_type parameter") else : json.pop('model_type', None) if 'organization' in json : if json['organization'] != "" : if len(Param_organizations.objects.filter(authorized_value=json['organization'])) != 1 : return ("You gave an invalid organization parameter") else : json.pop('organization', None) return (True) else : return (commun)
def from_json(cls, json_blob): blob = copy.deepcopy(json_blob) json = blob.pop("data", blob) obj = json.pop("ASSET", json) result = {} for k, v in obj.iteritems(): t = k.lower() result[t] = v a = cls(result["tag"], result) # set ipmi object a.ipmi = IPMI.from_json(json.pop("IPMI")) # set Address (IP Address) a.addresses = Address.from_json(json.pop("ADDRESSES")) return a
def crsf_protect(): if request.method in ['POST', 'PUT']: token = session.pop('_csrf_token', None) if request.headers.get('Content-Type') == "application/json": json = request.get_json() # check for csrf in json if not token or token != json.pop('_csrf_token', None): abort(403) else: # else check in the form if not token or token != request.form.get('_csrf_token'): abort(403)
def check_param_of_test_json (json): commun = check_commun_params_json(json) if commun is True : if 'data_modality' in json : if json['data_modality'] != "" : if len(Param_DataModalities.objects.filter(authorized_value=json['data_modality'])) != 1 : return ("You gave an invalid data_modality parameter") else : json.pop('data_modality', None) if 'test_type' in json : if json['test_type'] != "" : if len(Param_TestType.objects.filter(authorized_value=json['test_type'])) != 1 : return ("You gave an invalid test_type parameter") else : json.pop('test_type', None) if 'score_type' in json : if json['score_type'] != "" : if len(Param_ScoreType.objects.filter(authorized_value=json['score_type'])) != 1 : return ("You gave an invalid score_type parameter") else : json.pop('score_type', None) return (True) else : return (commun)
def __init__(self, json_feed, method, params): json = json_feed.copy() self.on_this_page = int(json.pop('on_this_page')) self.perpage = int(json.pop('perpage')) self.page = int(json.pop('page')) if 'total' in json: self.total = int(json.pop('total')) else: self.total = None self.method = method self.params = params self.__current = 0 if len(json) == 1: (self.type, entries) = json.popitem() if isinstance(entries, list): self.__entries = entries elif isinstance(entries, dict): self.__entries = [entries] else: raise Exception('Cannot construct PymeoFeed')
def _bind_json(self, json): # generally, not required for override. instead use _bind_custom_json # if possible if not isinstance(json, dict): self._binding_failed('expected dict, got %s', type(json)) for binding in self._bindings: val = json.pop(binding.name, None) if binding.expected and val is None: self._binding_failed('expected val for %s', binding.name) if binding.binding and val is not None: if isinstance(val, list): val = [binding.binding(v, parent=self) for v in val] else: val = binding.binding(val, parent=self) setattr(self, binding.name, val) self._bind_custom_json(json)
def replace(json, s1, s2): if type(json) == list: # If json object is an array iterate over the array for i in range(len(json)): if json[i] == s1: # If the list item == s1 replace json[i] = s2 if type(json[i]) == dict or type(json[i]) == list: # If there is futher nesting call it recursively replace(json[i], s1, s2) elif type(json) == dict: # If json object is a dictionary iterate over the keys for key in json: if type(json[key]) == dict or type(json[key]) == list: # If there is futher nesting call it recursively replace(json[key], s1, s2) if json[key] == s1: # If the value of the key == s1 replace it json[key] = s2 if key == s1: # If the key == s1 replace it json[s2] = json.pop(s1)
def show(self): def get_value(value): if type(value) is not DBRef: return value dbref = value #mongo_db = self._mongo_client[db_name] mongo_db = self._mongo_db mongo_collection = self._mongo_db[dbref.collection] try: name = '[' + mongo_collection.find_one({'_id': dbref.id})['name'] + ']' except: name = '[id_' + str(dbref.id) + ']' return name def resolve_links(json): internal_json = {} if type(json) is not dict: return get_value(json) for key in json: val = json[key] if type(val) is dict: internal_json[key] = resolve_links(val) continue if type(val) is list: internal_list = val[:] for idx in range(len(internal_list)): internal_list[idx] = resolve_links(internal_list[idx]) internal_json[key] = internal_list[:] continue internal_json[key] = get_value(val) return internal_json json = self._get_json() try: json.pop('_id') except: pass try: json.pop(use_key) except: pass try: json.pop(usedby_key) except: pass return resolve_links(json)
def check_commun_params_json (json): if 'cell_type' in json : if json['cell_type'] != "" : if len(Param_CellType.objects.filter(authorized_value= json['cell_type'])) != 1 : return ("You gave an invalid cell_type parameter") else : json.pop('cell_type', None) if 'species' in json : if json['species'] != "" : if len(Param_Species.objects.filter(authorized_value=json['species'])) != 1 : return ("You gave an invalid species parameter") else : json.pop('species', None) if 'brain_region' in json : if json['brain_region'] != "" : if len(Param_BrainRegion.objects.filter(authorized_value=json['brain_region'])) != 1 : return ("You gave an invalid brain_region parameter") else : json.pop('brain_region', None) return (True)
def _translate_node(self, is_collection, schema_root, xml_node, prefixes, depth=0): ''' Translates the given XML node into JSON is_collection -- True if the results is in the collection+json format xml_node -- the current XML element to translate ''' json = list() first_child = False current_list = None current_name = schema_root.get_name() if schema_root.is_leafy(): schema_root = schema_root.get_parent() siblings = collect_siblings(xml_node) if len(siblings) == 0: if xml_node.text is None: return '"empty":""' else: return '"%s":"%s"' % (current_name,xml_node.text) for sibling_tag, is_last in iterate_with_lookahead(siblings): sib_xml_nodes = siblings[sibling_tag] child_schema_node = find_child_by_name(schema_root, sibling_tag) if child_schema_node is None: self._logger.warning("Unknown Child schema node <%s> for parent <%s>", sibling_tag, current_name) if is_last and json[-1] == ",": json.pop() continue has_siblings = child_schema_node.is_listy() if has_siblings: sib_name, sib_prefix, prefixes = _split_tag_and_update_prefixes(sib_xml_nodes[0], prefixes) json.append('"%s%s" : [' % (sib_prefix, sib_name)) for child_xml_node, sib_is_last in iterate_with_lookahead(sib_xml_nodes): name, prefix, prefixes = _split_tag_and_update_prefixes(child_xml_node, prefixes) value = child_xml_node.text if not child_schema_node.is_leafy(): # it's a container, so iterate over children if has_siblings: json.append('{') else: json.append('"%s%s":{' % (prefix,name)) body = self._translate_node(is_collection, child_schema_node, child_xml_node, prefixes, depth+1, ) json.append(body) json.append('}') else: if child_schema_node.node_type().leaf_type == RwYang.LeafType.LEAF_TYPE_EMPTY: value = "[null]" elif child_schema_node.node_type().leaf_type == RwYang.LeafType.LEAF_TYPE_STRING: if not value: value = '""' else: value = tornado.escape.json_encode(value) else: if not value: value = '""' else: try: float(value) except ValueError: value = tornado.escape.json_encode(value) if has_siblings: json.append('%s' % (value)) else: json.append('"%s" : %s' % (name, value)) if not sib_is_last: json.append(',') if prefix != "": prefixes.pop() if has_siblings: json.append(']') if sib_prefix != "": prefixes.pop() if not is_last: json.append(',') return ''.join(json)
def _bind_json(self,json): self.layer_type = json.pop('type') self._bind(json)