INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Delete a subnet.
def delete_subnet(context, id): """Delete a subnet. : param context: neutron api request context : param id: UUID representing the subnet to delete. """ LOG.info("delete_subnet %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): subnet = db_api.subnet_find(context...
Returns Ext Resources.
def get_resources(cls): """Returns Ext Resources.""" plugin = directory.get_plugin() controller = MacAddressRangesController(plugin) return [extensions.ResourceExtension(Mac_address_ranges.get_alias(), controller)]
Only two fields are allowed for modification:
def _filter_update_security_group_rule(rule): '''Only two fields are allowed for modification: external_service and external_service_id ''' allowed = ['external_service', 'external_service_id'] filtered = {} for k, val in rule.iteritems(): if k in allowed: if isinstance(...
Updates a SG rule async and return the job information.
def _perform_async_update_rule(context, id, db_sg_group, rule_id, action): """Updates a SG rule async and return the job information. Only happens if the security group has associated ports. If the async connection fails the update continues (legacy mode). """ rpc_reply = None sg_rpc = sg_rpc_a...
Creates a rule and updates the ports ( async ) if enabled.
def create_security_group_rule(context, security_group_rule): """Creates a rule and updates the ports (async) if enabled.""" LOG.info("create_security_group for tenant %s" % (context.tenant_id)) with context.session.begin(): rule = _validate_security_group_rule( context, sec...
Updates a rule and updates the ports
def update_security_group_rule(context, id, security_group_rule): '''Updates a rule and updates the ports''' LOG.info("update_security_group_rule for tenant %s" % (context.tenant_id)) new_rule = security_group_rule["security_group_rule"] # Only allow updatable fields new_rule = _filter_...
Deletes a rule and updates the ports ( async ) if enabled.
def delete_security_group_rule(context, id): """Deletes a rule and updates the ports (async) if enabled.""" LOG.info("delete_security_group %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): rule = db_api.security_group_rule_find(context, id=id, ...
Returns combined list of tuples: [ ( table column ) ].
def get_data(): """Returns combined list of tuples: [(table, column)]. List is built, based on retrieved tables, where column with name ``tenant_id`` exists. """ output = [] tables = get_tables() for table in tables: try: columns = get_columns(table) except sa.e...
Returns the public net id
def get_public_net_id(self): """Returns the public net id""" for id, net_params in self.strategy.iteritems(): if id == CONF.QUARK.public_net_id: return id return None
A decorator to be used on another decorator
def opt_args_decorator(func): """A decorator to be used on another decorator This is done to allow separate handling on the basis of argument values """ @wraps(func) def wrapped_dec(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # actual decorate...
Will add the tenant_id to the context from body.
def _fix_missing_tenant_id(self, context, body, key): """Will add the tenant_id to the context from body. It is assumed that the body must have a tenant_id because neutron core could never have gotten here otherwise. """ if not body: raise n_exc.BadRequest(resource=k...
Validate IP allocation pools.
def _validate_allocation_pools(self): """Validate IP allocation pools. Verify start and end address for each allocation pool are valid, ie: constituted by valid and appropriately ordered IP addresses. Also, verify pools do not overlap among themselves. Finally, verify that each ...
Adds job to neutron context for use later.
def add_job_to_context(context, job_id): """Adds job to neutron context for use later.""" db_job = db_api.async_transaction_find( context, id=job_id, scope=db_api.ONE) if not db_job: return context.async_job = {"job": v._make_job_dict(db_job)}
Creates a job with support for subjobs.
def create_job(context, body): """Creates a job with support for subjobs. If parent_id is not in the body: * the job is considered a parent job * it will have a NULL transaction id * its transaction id == its id * all subjobs will use its transaction id as theirs Else: * the job is a s...
Delete an ip address.
def delete_job(context, id, **filters): """Delete an ip address. : param context: neutron api request context : param id: UUID representing the ip address to delete. """ LOG.info("delete_ip_address %s for tenant %s" % (id, context.tenant_id)) if not context.is_admin: raise n_exc.NotAut...
Returns Ext Resources.
def get_resources(cls): """Returns Ext Resources.""" plugin = directory.get_plugin() controller = IPPoliciesController(plugin) return [extensions.ResourceExtension(Ip_policies.get_alias(), controller)]
Selects an open lswitch for a network.
def _lswitch_select_open(self, context, switches=None, **kwargs): """Selects an open lswitch for a network. Note that it does not select the most full switch, but merely one with ports available. """ if switches is not None: for res in switches["results"]: ...
Configure any additional default transport zone bindings.
def _add_default_tz_bindings(self, context, switch, network_id): """Configure any additional default transport zone bindings.""" default_tz = CONF.NVP.default_tz # If there is no default tz specified it's pointless to try # and add any additional default tz bindings. if not defa...
Deconfigure any additional default transport zone bindings.
def _remove_default_tz_bindings(self, context, network_id): """Deconfigure any additional default transport zone bindings.""" default_tz = CONF.NVP.default_tz if not default_tz: LOG.warn("additional_default_tz_types specified, " "but no default_tz. Skipping " ...
Public interface for fetching lswitch ids for a given network.
def get_lswitch_ids_for_network(self, context, network_id): """Public interface for fetching lswitch ids for a given network. NOTE(morgabra) This is here because calling private methods from outside the class feels wrong, and we need to be able to fetch lswitch ids for use in other driv...
Register a floating ip with Unicorn
def register_floating_ip(self, floating_ip, port_fixed_ips): """Register a floating ip with Unicorn :param floating_ip: The quark.db.models.IPAddress to register :param port_fixed_ips: A dictionary containing the port and fixed ips to associate the floating IP with. Has the structure o...
Register a floating ip with Unicorn
def remove_floating_ip(self, floating_ip): """Register a floating ip with Unicorn :param floating_ip: The quark.db.models.IPAddress to remove :return: None """ url = "%s/%s" % (CONF.QUARK.floating_ip_base_url, floating_ip.address_readable) timeou...
Instantiates worker plugins that have requsite properties.
def _load_worker_plugin_with_module(self, module, version): """Instantiates worker plugins that have requsite properties. The required properties are: * must have PLUGIN_EP entrypoint registered (or it wouldn't be in the list) * must have class attribute versions (list) of sup...
Looks for modules with amtching entry points.
def _discover_via_entrypoints(self): """Looks for modules with amtching entry points.""" emgr = extension.ExtensionManager(PLUGIN_EP, invoke_on_load=False) return ((ext.name, ext.plugin) for ext in emgr)
Launches configured # of workers per loaded plugin.
def serve_rpc(self): """Launches configured # of workers per loaded plugin.""" if cfg.CONF.QUARK_ASYNC.rpc_workers < 1: cfg.CONF.set_override('rpc_workers', 1, "QUARK_ASYNC") try: rpc = service.RpcWorker(self.plugins) launcher = common_service.ProcessLauncher...
Initializes eventlet and starts wait for workers to exit.
def start_api_and_rpc_workers(self): """Initializes eventlet and starts wait for workers to exit. Spawns the workers returned from serve_rpc """ pool = eventlet.GreenPool() quark_rpc = self.serve_rpc() pool.spawn(quark_rpc.wait) pool.waitall()
Returns Ext Resources.
def get_resources(cls): """Returns Ext Resources.""" plural_mappings = resource_helper.build_plural_mappings( {}, RESOURCE_ATTRIBUTE_MAP) # attr.PLURALS.update(plural_mappings) return resource_helper.build_resource_info(plural_mappings, ...
Chunks data into chunk with size< = chunk_size.
def _chunks(self, iterable, chunk_size): """Chunks data into chunk with size<=chunk_size.""" iterator = iter(iterable) chunk = list(itertools.islice(iterator, 0, chunk_size)) while chunk: yield chunk chunk = list(itertools.islice(iterator, 0, chunk_size))
Check for overlapping ranges.
def _check_collisions(self, new_range, existing_ranges): """Check for overlapping ranges.""" def _contains(num, r1): return (num >= r1[0] and num <= r1[1]) def _is_overlap(r1, r2): return (_contains(r1[0], r2) or _contains(r1[1], r...
Find a deallocated network segment id and reallocate it.
def _try_allocate(self, context, segment_id, network_id): """Find a deallocated network segment id and reallocate it. NOTE(morgabra) This locks the segment table, but only the rows in use by the segment, which is pretty handy if we ever have more than 1 segment or segment type. ...
Deletes locks for each IP address that is no longer null - routed.
def delete_locks(context, network_ids, addresses): """Deletes locks for each IP address that is no longer null-routed.""" addresses_no_longer_null_routed = _find_addresses_to_be_unlocked( context, network_ids, addresses) LOG.info("Deleting %s lock holders on IPAddress with ids: %s", len...
Creates locks for each IP address that is null - routed.
def create_locks(context, network_ids, addresses): """Creates locks for each IP address that is null-routed. The function creates the IP address if it is not present in the database. """ for address in addresses: address_model = None try: address_model = _find_or_create_ad...
Return relevant IPAM strategy name.
def select_ipam_strategy(self, network_id, network_strategy, **kwargs): """Return relevant IPAM strategy name. :param network_id: neutron network id. :param network_strategy: default strategy for the network. NOTE(morgabra) This feels like a hack but I can't think of a better i...
Return a dict of extra network information.
def _get_base_network_info(self, context, network_id, base_net_driver): """Return a dict of extra network information. :param context: neutron request context. :param network_id: neturon network id. :param net_driver: network driver associated with network_id. :raises IronicExce...
Create a port.
def create_port(self, context, network_id, port_id, **kwargs): """Create a port. :param context: neutron api request context. :param network_id: neutron network id. :param port_id: neutron port id. :param kwargs: required keys - device_id: neutron port device_id (ins...
Update a port.
def update_port(self, context, port_id, **kwargs): """Update a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to update the downstream port for any r...
Delete a port.
def delete_port(self, context, port_id, **kwargs): """Delete a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to delete the downstream port for any r...
Diagnose a port.
def diag_port(self, context, port_id, **kwargs): """Diagnose a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to fetch the downstream port for any re...
Set tag on model object.
def set(self, model, value): """Set tag on model object.""" self.validate(value) self._pop(model) value = self.serialize(value) model.tags.append(value)
Get a matching valid tag off the model.
def get(self, model): """Get a matching valid tag off the model.""" for tag in model.tags: if self.is_tag(tag): value = self.deserialize(tag) try: self.validate(value) return value except TagValidationErr...
Pop all matching tags off the model and return them.
def _pop(self, model): """Pop all matching tags off the model and return them.""" tags = [] # collect any exsiting tags with matching prefix for tag in model.tags: if self.is_tag(tag): tags.append(tag) # remove collected tags from model if ta...
Pop all matching tags off the port return a valid one.
def pop(self, model): """Pop all matching tags off the port, return a valid one.""" tags = self._pop(model) if tags: for tag in tags: value = self.deserialize(tag) try: self.validate(value) return value ...
Does the given port have this tag?
def has_tag(self, model): """Does the given port have this tag?""" for tag in model.tags: if self.is_tag(tag): return True return False
Validates a VLAN ID.
def validate(self, value): """Validates a VLAN ID. :param value: The VLAN ID to validate against. :raises TagValidationError: Raised if the VLAN ID is invalid. """ try: vlan_id_int = int(value) assert vlan_id_int >= self.MIN_VLAN_ID assert vla...
Get all known tags from a model.
def get_all(self, model): """Get all known tags from a model. Returns a dict of {<tag_name>:<tag_value>}. """ tags = {} for name, tag in self.tags.items(): for mtag in model.tags: if tag.is_tag(mtag): tags[name] = tag.get(model) ...
Validate and set all known tags on a port.
def set_all(self, model, **tags): """Validate and set all known tags on a port.""" for name, tag in self.tags.items(): if name in tags: value = tags.pop(name) if value: try: tag.set(model, value) ...
Creates a payload for the redis server.
def serialize_rules(self, rules): """Creates a payload for the redis server.""" # TODO(mdietz): If/when we support other rule types, this comment # will have to be revised. # Action and direction are static, for now. The implementation may # support 'deny' and 'egre...
Creates a payload for the redis server
def serialize_groups(self, groups): """Creates a payload for the redis server The rule schema is the following: REDIS KEY - port_device_id.port_mac_address/sg REDIS VALUE - A JSON dump of the following: port_mac_address must be lower-cased and stripped of non-alphanumeric ...
Writes a series of security group rules to a redis server.
def apply_rules(self, device_id, mac_address, rules): """Writes a series of security group rules to a redis server.""" LOG.info("Applying security group rules for device %s with MAC %s" % (device_id, mac_address)) rule_dict = {SECURITY_GROUP_RULE_KEY: rules} redis_key =...
Gets security groups for interfaces from Redis
def get_security_group_states(self, interfaces): """Gets security groups for interfaces from Redis Returns a dictionary of xapi.VIFs with values of the current acknowledged status in Redis. States not explicitly handled: * ack key, no rules - This is the same as just tagging th...
Updates security groups by setting the ack field
def update_group_states_for_vifs(self, vifs, ack): """Updates security groups by setting the ack field""" vif_keys = [self.vif_key(vif.device_id, vif.mac_address) for vif in vifs] self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)
Run migrations in offline mode.
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in online mode.
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine( neutron_config.database.connection, poolclass=pool.NullPool) connection = engine.connect() ...
Generic Notifier.
def do_notify(context, event_type, payload): """Generic Notifier. Parameters: - `context`: session context - `event_type`: the event type to report, i.e. ip.usage - `payload`: dict containing the payload to send """ LOG.debug('IP_BILL: notifying {}'.format(payload)) notifie...
Method to send notifications.
def notify(context, event_type, ipaddress, send_usage=False, *args, **kwargs): """Method to send notifications. We must send USAGE when a public IPv4 address is deallocated or a FLIP is associated. Parameters: - `context`: the context for notifier - `event_type`: the event type for IP a...
Method builds a payload out of the passed arguments.
def build_payload(ipaddress, event_type, event_time=None, start_time=None, end_time=None): """Method builds a payload out of the passed arguments. Parameters: `ipaddress`: the models.IPAddress object `event_type`: USAGE,CRE...
Method to build an IP list for the case 1
def build_full_day_ips(query, period_start, period_end): """Method to build an IP list for the case 1 when the IP was allocated before the period start and is still allocated after the period end. This method only looks at public IPv4 addresses. """ # Filter out only IPv4 that have not been dea...
Returns a tuple of start_period and end_period.
def calc_periods(hour=0, minute=0): """Returns a tuple of start_period and end_period. Assumes that the period is 24-hrs. Parameters: - `hour`: the hour from 0 to 23 when the period ends - `minute`: the minute from 0 to 59 when the period ends This method will calculate the end of the p...
Creates the view for a job while calculating progress.
def _make_job_dict(job): """Creates the view for a job while calculating progress. Since a root job does not have a transaction id (TID) it will return its id as the TID. """ body = {"id": job.get('id'), "action": job.get('action'), "completed": job.get('completed'), ...
Retrieve a mac_address_range.
def get_mac_address_range(context, id, fields=None): """Retrieve a mac_address_range. : param context: neutron api request context : param id: UUID representing the network to fetch. : param fields: a list of strings that are valid keys in a network dictionary as listed in the RESOURCE_ATTRIBUT...
Delete a mac_address_range.
def delete_mac_address_range(context, id): """Delete a mac_address_range. : param context: neutron api request context : param id: UUID representing the mac_address_range to delete. """ LOG.info("delete_mac_address_range %s for tenant %s" % (id, context.tenant_id)) if not context.i...
Returns Ext Resources.
def get_resources(cls): """Returns Ext Resources.""" job_controller = JobsController( directory.get_plugin()) resources = [] resources.append(extensions.ResourceExtension( Jobs.get_alias(), job_controller)) return reso...
alexm: i believe this method is never called
def downgrade(): """alexm: i believe this method is never called""" with op.batch_alter_table(t2_name) as batch_op: batch_op.drop_column('do_not_use') with op.batch_alter_table(t1_name) as batch_op: batch_op.drop_column('enabled')
Delete a segment_allocation_range.
def delete_segment_allocation_range(context, sa_id): """Delete a segment_allocation_range. : param context: neutron api request context : param id: UUID representing the segment_allocation_range to delete. """ LOG.info("delete_segment_allocation_range %s for tenant %s" % (sa_id, contex...
Returns a WSGI filter app for use with paste. deploy.
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def wrapper(app): return ResponseAsyncIdAdder(app, conf) return wrapper
Returns dictionary with keys segment_id and value used IPs count.
def get_used_ips(session, **kwargs): """Returns dictionary with keys segment_id and value used IPs count. Used IP address count is determined by: - allocated IPs - deallocated IPs whose `deallocated_at` is within the `reuse_after` window compared to the present time, excluding IPs that are accounte...
Returns dictionary with key segment_id and value unused IPs count.
def get_unused_ips(session, used_ips_counts, **kwargs): """Returns dictionary with key segment_id, and value unused IPs count. Unused IP address count is determined by: - adding subnet's cidr's size - subtracting IP policy exclusions on subnet - subtracting used ips per segment """ LOG.debu...
Returns a dict of VM OpaqueRef ( str ) - > xapi. VM.
def get_instances(self, session): """Returns a dict of `VM OpaqueRef` (str) -> `xapi.VM`.""" LOG.debug("Getting instances from Xapi") recs = session.xenapi.VM.get_all_records() # NOTE(asadoughi): Copied from xen-networking-scripts/utils.py is_inst = lambda r: (r['power_state']....
Returns a set of VIFs from get_instances return value.
def get_interfaces(self): """Returns a set of VIFs from `get_instances` return value.""" LOG.debug("Getting interfaces from Xapi") with self.sessioned() as session: instances = self.get_instances(session) recs = session.xenapi.VIF.get_all_records() interfaces = ...
Handles changes to interfaces security groups
def update_interfaces(self, added_sg, updated_sg, removed_sg): """Handles changes to interfaces' security groups Calls refresh_interfaces on argument VIFs. Set security groups on added_sg's VIFs. Unsets security groups on removed_sg's VIFs. """ if not (added_sg or updated_sg or ...
Create a network.
def create_network(context, network): """Create a network. Create a network which represents an L2 network segment which can have a set of subnets and ports associated with it. : param context: neutron api request context : param network: dictionary describing the network, with keys as list...
Update values of a network.
def update_network(context, id, network): """Update values of a network. : param context: neutron api request context : param id: UUID representing the network to update. : param network: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow...
Retrieve a network.
def get_network(context, id, fields=None): """Retrieve a network. : param context: neutron api request context : param id: UUID representing the network to fetch. : param fields: a list of strings that are valid keys in a network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object...
Retrieve a list of networks.
def get_networks(context, limit=None, sorts=['id'], marker=None, page_reverse=False, filters=None, fields=None): """Retrieve a list of networks. The contents of the list depends on the identity of the user making the request (as indicated by the context) as well as any filters. : p...
Return the number of networks.
def get_networks_count(context, filters=None): """Return the number of networks. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are vali...
Delete a network.
def delete_network(context, id): """Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete. """ LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(conte...
This is a helper method for testing.
def make_case2(context): """This is a helper method for testing. When run with the current context, it will create a case 2 entries in the database. See top of file for what case 2 is. """ query = context.session.query(models.IPAddress) period_start, period_end = billing.calc_periods() ip_l...
Runs billing report. Optionally sends notifications to billing
def main(notify, hour, minute): """Runs billing report. Optionally sends notifications to billing""" # Read the config file and get the admin context config_opts = ['--config-file', '/etc/neutron/neutron.conf'] config.init(config_opts) # Have to load the billing module _after_ config is parsed so ...
Configure all listeners here
def start_rpc_listeners(self): """Configure all listeners here""" self._setup_rpc() if not self.endpoints: return [] self.conn = n_rpc.create_connection() self.conn.create_consumer(self.topic, self.endpoints, fanout=False) ret...
Provides an admin context for workers.
def context(self): """Provides an admin context for workers.""" if not self._context: self._context = context.get_admin_context() return self._context
Begins the async update process.
def update_sg(self, context, sg, rule_id, action): """Begins the async update process.""" db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE) if not db_sg: return None with context.session.begin(): job_body = dict(action="%s sg rule %s" % (action,...
Produces a list of ports to be updated async.
def populate_subtasks(self, context, sg, parent_job_id): """Produces a list of ports to be updated async.""" db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE) if not db_sg: return None ports = db_api.sg_gather_associated_ports(context, db_sg) if len...
Updates the ports through redis.
def update_ports_for_sg(self, context, portid, jobid): """Updates the ports through redis.""" port = db_api.port_find(context, id=portid, scope=db_api.ONE) if not port: LOG.warning("Port not found") return net_driver = port_api._get_net_driver(port.network, port=p...
Gather all ports associated to security group.
def sg_gather_associated_ports(context, group): """Gather all ports associated to security group. Returns: * list, or None """ if not group: return None if not hasattr(group, "ports") or len(group.ports) <= 0: return [] return group.ports
Updates a security group rule.
def security_group_rule_update(context, rule, **kwargs): '''Updates a security group rule. NOTE(alexm) this is non-standard functionality. ''' rule.update(kwargs) context.session.add(rule) return rule
Query for segment allocations.
def segment_allocation_find(context, lock_mode=False, **filters): """Query for segment allocations.""" range_ids = filters.pop("segment_allocation_range_ids", None) query = context.session.query(models.SegmentAllocation) if lock_mode: query = query.with_lockmode("update") query = query.fil...
Returns Ext Resources.
def get_resources(cls): """Returns Ext Resources.""" controller = RoutesController(directory.get_plugin()) return [extensions.ResourceExtension( Routes.get_alias(), controller)]
Sends the given command to Niko Home Control and returns the output of the system.
def send(self, s): """ Sends the given command to Niko Home Control and returns the output of the system. Aliases: write, put, sendall, send_all """ self._socket.send(s.encode()) return self.read()
Implements the if operator with support for multiple elseif - s.
def if_(*args): """Implements the 'if' operator with support for multiple elseif-s.""" for i in range(0, len(args) - 1, 2): if args[i]: return args[i + 1] if len(args) % 2: return args[-1] else: return None
Implements the == operator which does type JS - style coertion.
def soft_equals(a, b): """Implements the '==' operator, which does type JS-style coertion.""" if isinstance(a, str) or isinstance(b, str): return str(a) == str(b) if isinstance(a, bool) or isinstance(b, bool): return bool(a) is bool(b) return a == b
Implements the === operator.
def hard_equals(a, b): """Implements the '===' operator.""" if type(a) != type(b): return False return a == b
Implements the < operator with JS - style type coertion.
def less(a, b, *args): """Implements the '<' operator with JS-style type coertion.""" types = set([type(a), type(b)]) if float in types or int in types: try: a, b = float(a), float(b) except TypeError: # NaN return False return a < b and (not args or l...
Implements the < = operator with JS - style type coertion.
def less_or_equal(a, b, *args): """Implements the '<=' operator with JS-style type coertion.""" return ( less(a, b) or soft_equals(a, b) ) and (not args or less_or_equal(b, *args))
Converts a string either to int or to float. This is important because e. g. { ! ==: [ { +: 0 } 0. 0 ] }
def to_numeric(arg): """ Converts a string either to int or to float. This is important, because e.g. {"!==": [{"+": "0"}, 0.0]} """ if isinstance(arg, str): if '.' in arg: return float(arg) else: return int(arg) return arg
Also converts either to ints or to floats.
def minus(*args): """Also, converts either to ints or to floats.""" if len(args) == 1: return -to_numeric(args[0]) return to_numeric(args[0]) - to_numeric(args[1])
Implements the merge operator for merging lists.
def merge(*args): """Implements the 'merge' operator for merging lists.""" ret = [] for arg in args: if isinstance(arg, list) or isinstance(arg, tuple): ret += list(arg) else: ret.append(arg) return ret
Gets variable value from data dictionary.
def get_var(data, var_name, not_found=None): """Gets variable value from data dictionary.""" try: for key in str(var_name).split('.'): try: data = data[key] except TypeError: data = data[int(key)] except (KeyError, TypeError, ValueError): ...
Implements the missing operator for finding missing variables.
def missing(data, *args): """Implements the missing operator for finding missing variables.""" not_found = object() if args and isinstance(args[0], list): args = args[0] ret = [] for arg in args: if get_var(data, arg, not_found) is not_found: ret.append(arg) return re...
Implements the missing_some operator for finding missing variables.
def missing_some(data, min_required, args): """Implements the missing_some operator for finding missing variables.""" if min_required < 1: return [] found = 0 not_found = object() ret = [] for arg in args: if get_var(data, arg, not_found) is not_found: ret.append(arg)...
Executes the json - logic with given data.
def jsonLogic(tests, data=None): """Executes the json-logic with given data.""" # You've recursed to a primitive, stop! if tests is None or not isinstance(tests, dict): return tests data = data or {} operator = list(tests.keys())[0] values = tests[operator] # Easy syntax for unary...