sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
def _get_diff(self, cp_file):
"""Get a diff between running config and a proposed file."""
diff = []
self._create_sot_file()
diff_out = self.device.show(
'show diff rollback-patch file {0} file {1}'.format(
'sot_file', self.replace_file.split('/')[-1]), raw_text=True)
try:
diff_out = diff_out.split(
'#Generating Rollback Patch')[1].replace(
'Rollback Patch is Empty', '').strip()
for line in diff_out.splitlines():
if line:
if line[0].strip() != '!':
diff.append(line.rstrip(' '))
except (AttributeError, KeyError):
raise ReplaceConfigException(
'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
return '\n'.join(diff) | Get a diff between running config and a proposed file. | entailment |
def _save_config(self, filename):
"""Save the current running config to the given file."""
self.device.show('checkpoint file {}'.format(filename), raw_text=True) | Save the current running config to the given file. | entailment |
def open(self):
"""Open the connection wit the device."""
try:
self.device.open()
except ConnectTimeoutError as cte:
raise ConnectionException(cte.message)
self.device.timeout = self.timeout
self.device._conn._session.transport.set_keepalive(self.keepalive)
if hasattr(self.device, "cu"):
# make sure to remove the cu attr from previous session
# ValueError: requested attribute name cu already exists
del self.device.cu
self.device.bind(cu=Config)
if self.config_lock:
self._lock() | Open the connection wit the device. | entailment |
def _lock(self):
"""Lock the config DB."""
if not self.locked:
self.device.cu.lock()
self.locked = True | Lock the config DB. | entailment |
def _unlock(self):
"""Unlock the config DB."""
if self.locked:
self.device.cu.unlock()
self.locked = False | Unlock the config DB. | entailment |
def compare_config(self):
"""Compare candidate config with running."""
diff = self.device.cu.diff()
if diff is None:
return ''
else:
return diff.strip() | Compare candidate config with running. | entailment |
def commit_config(self):
"""Commit configuration."""
self.device.cu.commit(ignore_warning=self.ignore_warning)
if not self.config_lock:
self._unlock() | Commit configuration. | entailment |
def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.config_lock:
self._unlock() | Discard changes (rollback 0). | entailment |
def get_facts(self):
"""Return facts of the device."""
output = self.device.facts
uptime = self.device.uptime or -1
interfaces = junos_views.junos_iface_table(self.device)
interfaces.get()
interface_list = interfaces.keys()
return {
'vendor': u'Juniper',
'model': py23_compat.text_type(output['model']),
'serial_number': py23_compat.text_type(output['serialnumber']),
'os_version': py23_compat.text_type(output['version']),
'hostname': py23_compat.text_type(output['hostname']),
'fqdn': py23_compat.text_type(output['fqdn']),
'uptime': uptime,
'interface_list': interface_list
} | Return facts of the device. | entailment |
def get_interfaces(self):
"""Return interfaces details."""
result = {}
interfaces = junos_views.junos_iface_table(self.device)
interfaces.get()
# convert all the tuples to our pre-defined dict structure
for iface in interfaces.keys():
result[iface] = {
'is_up': interfaces[iface]['is_up'],
'is_enabled': interfaces[iface]['is_enabled'],
'description': (interfaces[iface]['description'] or u''),
'last_flapped': float((interfaces[iface]['last_flapped'] or -1)),
'mac_address': napalm_base.helpers.convert(
napalm_base.helpers.mac,
interfaces[iface]['mac_address'],
py23_compat.text_type(interfaces[iface]['mac_address'])),
'speed': -1
}
# result[iface]['last_flapped'] = float(result[iface]['last_flapped'])
match = re.search(r'(\d+)(\w*)', interfaces[iface]['speed'] or u'')
if match is None:
continue
speed_value = napalm_base.helpers.convert(int, match.group(1), -1)
if speed_value == -1:
continue
speed_unit = match.group(2)
if speed_unit.lower() == 'gbps':
speed_value *= 1000
result[iface]['speed'] = speed_value
return result | Return interfaces details. | entailment |
def _get_address_family(table):
"""
Function to derive address family from a junos table name.
:params table: The name of the routing table
:returns: address family
"""
address_family_mapping = {
'inet': 'ipv4',
'inet6': 'ipv6',
'inetflow': 'flow'
}
family = table.split('.')[-2]
try:
address_family = address_family_mapping[family]
except KeyError:
address_family = family
return address_family | Function to derive address family from a junos table name.
:params table: The name of the routing table
:returns: address family | entailment |
def get_bgp_neighbors(self):
"""Return BGP neighbors details."""
bgp_neighbor_data = {}
default_neighbor_details = {
'local_as': 0,
'remote_as': 0,
'remote_id': '',
'is_up': False,
'is_enabled': False,
'description': '',
'uptime': 0,
'address_family': {}
}
keys = default_neighbor_details.keys()
uptime_table = junos_views.junos_bgp_uptime_table(self.device)
bgp_neighbors_table = junos_views.junos_bgp_table(self.device)
uptime_table_lookup = {}
def _get_uptime_table(instance):
if instance not in uptime_table_lookup:
uptime_table_lookup[instance] = uptime_table.get(instance=instance).items()
return uptime_table_lookup[instance]
def _get_bgp_neighbors_core(neighbor_data, instance=None, uptime_table_items=None):
'''
Make sure to execute a simple request whenever using
junos > 13. This is a helper used to avoid code redundancy
and reuse the function also when iterating through the list
BGP neighbors under a specific routing instance,
also when the device is capable to return the routing
instance name at the BGP neighbor level.
'''
for bgp_neighbor in neighbor_data:
peer_ip = napalm_base.helpers.ip(bgp_neighbor[0].split('+')[0])
neighbor_details = deepcopy(default_neighbor_details)
neighbor_details.update(
{elem[0]: elem[1] for elem in bgp_neighbor[1] if elem[1] is not None}
)
if not instance:
# not instance, means newer Junos version,
# as we request everything in a single request
peer_fwd_rti = neighbor_details.pop('peer_fwd_rti')
instance = peer_fwd_rti
else:
# instance is explicitly requests,
# thus it's an old Junos, so we retrieve the BGP neighbors
# under a certain routing instance
peer_fwd_rti = neighbor_details.pop('peer_fwd_rti', '')
instance_name = 'global' if instance == 'master' else instance
if instance_name not in bgp_neighbor_data:
bgp_neighbor_data[instance_name] = {}
if 'router_id' not in bgp_neighbor_data[instance_name]:
# we only need to set this once
bgp_neighbor_data[instance_name]['router_id'] = \
py23_compat.text_type(neighbor_details.get('local_id', ''))
peer = {
key: self._parse_value(value)
for key, value in neighbor_details.items()
if key in keys
}
peer['local_as'] = napalm_base.helpers.as_number(peer['local_as'])
peer['remote_as'] = napalm_base.helpers.as_number(peer['remote_as'])
peer['address_family'] = self._parse_route_stats(neighbor_details)
if 'peers' not in bgp_neighbor_data[instance_name]:
bgp_neighbor_data[instance_name]['peers'] = {}
bgp_neighbor_data[instance_name]['peers'][peer_ip] = peer
if not uptime_table_items:
uptime_table_items = _get_uptime_table(instance)
for neighbor, uptime in uptime_table_items:
if neighbor not in bgp_neighbor_data[instance_name]['peers']:
bgp_neighbor_data[instance_name]['peers'][neighbor] = {}
bgp_neighbor_data[instance_name]['peers'][neighbor]['uptime'] = uptime[0][1]
# Commenting out the following sections, till Junos
# will provide a way to identify the routing instance name
# from the details of the BGP neighbor
# currently, there are Junos 15 version having a field called `peer_fwd_rti`
# but unfortunately, this is not consistent.
# Junos 17 might have this fixed, but this needs to be revisited later.
# In the definition below, `old_junos` means a version that does not provide
# the forwarding RTI information.
#
# old_junos = napalm_base.helpers.convert(
# int, self.device.facts.get('version', '0.0').split('.')[0], 0) < 15
# if old_junos:
instances = junos_views.junos_route_instance_table(self.device).get()
for instance, instance_data in instances.items():
if instance.startswith('__'):
# junos internal instances
continue
bgp_neighbor_data[instance] = {'peers': {}}
instance_neighbors = bgp_neighbors_table.get(instance=instance).items()
uptime_table_items = uptime_table.get(instance=instance).items()
_get_bgp_neighbors_core(instance_neighbors,
instance=instance,
uptime_table_items=uptime_table_items)
# If the OS provides the `peer_fwd_rti` or any way to identify the
# rotuing instance name (see above), the performances of this getter
# can be significantly improved, as we won't execute one request
# for each an every RT.
# However, this improvement would only be beneficial for multi-VRF envs.
#
# else:
# instance_neighbors = bgp_neighbors_table.get().items()
# _get_bgp_neighbors_core(instance_neighbors)
bgp_tmp_dict = {}
for k, v in bgp_neighbor_data.items():
if bgp_neighbor_data[k]['peers']:
bgp_tmp_dict[k] = v
return bgp_tmp_dict | Return BGP neighbors details. | entailment |
def get_lldp_neighbors(self):
"""Return LLDP neighbors details."""
lldp = junos_views.junos_lldp_table(self.device)
try:
lldp.get()
except RpcError as rpcerr:
# this assumes the library runs in an environment
# able to handle logs
# otherwise, the user just won't see this happening
log.error('Unable to retrieve the LLDP neighbors information:')
log.error(rpcerr.message)
return {}
result = lldp.items()
neighbors = {}
for neigh in result:
if neigh[0] not in neighbors.keys():
neighbors[neigh[0]] = []
neighbors[neigh[0]].append({x[0]: py23_compat.text_type(x[1]) for x in neigh[1]})
return neighbors | Return LLDP neighbors details. | entailment |
def get_lldp_neighbors_detail(self, interface=''):
"""Detailed view of the LLDP neighbors."""
lldp_neighbors = {}
lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device)
try:
lldp_table.get()
except RpcError as rpcerr:
# this assumes the library runs in an environment
# able to handle logs
# otherwise, the user just won't see this happening
log.error('Unable to retrieve the LLDP neighbors information:')
log.error(rpcerr.message)
return {}
interfaces = lldp_table.get().keys()
# get lldp neighbor by interface rpc for EX Series, QFX Series, J Series
# and SRX Series is get-lldp-interface-neighbors-information,
# and rpc for M, MX, and T Series is get-lldp-interface-neighbors
# ref1: https://apps.juniper.net/xmlapi/operTags.jsp (Junos 13.1 and later)
# ref2: https://www.juniper.net/documentation/en_US/junos12.3/information-products/topic-collections/junos-xml-ref-oper/index.html (Junos 12.3) # noqa
lldp_table.GET_RPC = 'get-lldp-interface-neighbors'
if self.device.facts.get('personality') not in ('MX', 'M', 'T'):
lldp_table.GET_RPC = 'get-lldp-interface-neighbors-information'
for interface in interfaces:
if self.device.facts.get('personality') not in ('MX', 'M', 'T'):
lldp_table.get(interface_name=interface)
else:
lldp_table.get(interface_device=interface)
for item in lldp_table:
if interface not in lldp_neighbors.keys():
lldp_neighbors[interface] = []
lldp_neighbors[interface].append({
'parent_interface': item.parent_interface,
'remote_port': item.remote_port,
'remote_chassis_id': napalm_base.helpers.convert(
napalm_base.helpers.mac, item.remote_chassis_id, item.remote_chassis_id),
'remote_port_description': napalm_base.helpers.convert(
py23_compat.text_type, item.remote_port_description),
'remote_system_name': item.remote_system_name,
'remote_system_description': item.remote_system_description,
'remote_system_capab': item.remote_system_capab,
'remote_system_enable_capab': item.remote_system_enable_capab
})
return lldp_neighbors | Detailed view of the LLDP neighbors. | entailment |
def get_arp_table(self):
"""Return the ARP table."""
# could use ArpTable
# from jnpr.junos.op.phyport import ArpTable
# and simply use it
# but
# we need:
# - filters
# - group by VLAN ID
# - hostname & TTE fields as well
arp_table = []
arp_table_raw = junos_views.junos_arp_table(self.device)
arp_table_raw.get()
arp_table_items = arp_table_raw.items()
for arp_table_entry in arp_table_items:
arp_entry = {
elem[0]: elem[1] for elem in arp_table_entry[1]
}
arp_entry['mac'] = napalm_base.helpers.mac(arp_entry.get('mac'))
arp_entry['ip'] = napalm_base.helpers.ip(arp_entry.get('ip'))
arp_table.append(arp_entry)
return arp_table | Return the ARP table. | entailment |
def get_ntp_peers(self):
"""Return the NTP peers configured on the device."""
ntp_table = junos_views.junos_ntp_peers_config_table(self.device)
ntp_table.get()
ntp_peers = ntp_table.items()
if not ntp_peers:
return {}
return {napalm_base.helpers.ip(peer[0]): {} for peer in ntp_peers} | Return the NTP peers configured on the device. | entailment |
def get_ntp_servers(self):
"""Return the NTP servers configured on the device."""
ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
ntp_table.get()
ntp_servers = ntp_table.items()
if not ntp_servers:
return {}
return {napalm_base.helpers.ip(server[0]): {} for server in ntp_servers} | Return the NTP servers configured on the device. | entailment |
def get_ntp_stats(self):
"""Return NTP stats (associations)."""
# NTP Peers does not have XML RPC defined
# thus we need to retrieve raw text and parse...
# :(
ntp_stats = []
REGEX = (
'^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)'
'\s+([a-zA-Z0-9\.]+)\s+([0-9]{1,2})'
'\s+(-|u)\s+([0-9h-]+)\s+([0-9]+)'
'\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.-]+)'
'\s+([0-9\.]+)\s?$'
)
ntp_assoc_output = self.device.cli('show ntp associations no-resolve')
ntp_assoc_output_lines = ntp_assoc_output.splitlines()
for ntp_assoc_output_line in ntp_assoc_output_lines[3:]: # except last line
line_search = re.search(REGEX, ntp_assoc_output_line, re.I)
if not line_search:
continue # pattern not found
line_groups = line_search.groups()
try:
ntp_stats.append({
'remote': napalm_base.helpers.ip(line_groups[1]),
'synchronized': (line_groups[0] == '*'),
'referenceid': py23_compat.text_type(line_groups[2]),
'stratum': int(line_groups[3]),
'type': py23_compat.text_type(line_groups[4]),
'when': py23_compat.text_type(line_groups[5]),
'hostpoll': int(line_groups[6]),
'reachability': int(line_groups[7]),
'delay': float(line_groups[8]),
'offset': float(line_groups[9]),
'jitter': float(line_groups[10])
})
except Exception:
continue # jump to next line
return ntp_stats | Return NTP stats (associations). | entailment |
def get_mac_address_table(self):
"""Return the MAC address table."""
mac_address_table = []
if self.device.facts.get('personality', '') in ['SWITCH']: # for EX & QFX devices
if self.device.facts.get('switch_style', '') in ['VLAN_L2NG']: # for L2NG devices
mac_table = junos_views.junos_mac_address_table_switch_l2ng(self.device)
else:
mac_table = junos_views.junos_mac_address_table_switch(self.device)
else:
mac_table = junos_views.junos_mac_address_table(self.device)
mac_table.get()
mac_table_items = mac_table.items()
default_values = {
'mac': u'',
'interface': u'',
'vlan': 0,
'static': False,
'active': True,
'moves': 0,
'last_move': 0.0
}
for mac_table_entry in mac_table_items:
mac_entry = default_values.copy()
mac_entry.update(
{elem[0]: elem[1] for elem in mac_table_entry[1]}
)
mac = mac_entry.get('mac')
# JUNOS returns '*' for Type = Flood
if mac == '*':
continue
mac_entry['mac'] = napalm_base.helpers.mac(mac)
mac_address_table.append(mac_entry)
return mac_address_table | Return the MAC address table. | entailment |
def get_probes_config(self):
"""Return the configuration of the RPM probes."""
probes = {}
probes_table = junos_views.junos_rpm_probes_config_table(self.device)
probes_table.get()
probes_table_items = probes_table.items()
for probe_test in probes_table_items:
test_name = py23_compat.text_type(probe_test[0])
test_details = {
p[0]: p[1] for p in probe_test[1]
}
probe_name = napalm_base.helpers.convert(
py23_compat.text_type, test_details.pop('probe_name'))
target = napalm_base.helpers.convert(
py23_compat.text_type, test_details.pop('target', ''))
test_interval = napalm_base.helpers.convert(int, test_details.pop('test_interval', '0'))
probe_count = napalm_base.helpers.convert(int, test_details.pop('probe_count', '0'))
probe_type = napalm_base.helpers.convert(
py23_compat.text_type, test_details.pop('probe_type', ''))
source = napalm_base.helpers.convert(
py23_compat.text_type, test_details.pop('source_address', ''))
if probe_name not in probes.keys():
probes[probe_name] = {}
probes[probe_name][test_name] = {
'probe_type': probe_type,
'target': target,
'source': source,
'probe_count': probe_count,
'test_interval': test_interval
}
return probes | Return the configuration of the RPM probes. | entailment |
def get_probes_results(self):
"""Return the results of the RPM probes."""
probes_results = {}
probes_results_table = junos_views.junos_rpm_probes_results_table(self.device)
probes_results_table.get()
probes_results_items = probes_results_table.items()
for probe_result in probes_results_items:
probe_name = py23_compat.text_type(probe_result[0])
test_results = {
p[0]: p[1] for p in probe_result[1]
}
test_results['last_test_loss'] = napalm_base.helpers.convert(
int, test_results.pop('last_test_loss'), 0)
for test_param_name, test_param_value in test_results.items():
if isinstance(test_param_value, float):
test_results[test_param_name] = test_param_value * 1e-3
# convert from useconds to mseconds
test_name = test_results.pop('test_name', '')
source = test_results.get('source', u'')
if source is None:
test_results['source'] = u''
if probe_name not in probes_results.keys():
probes_results[probe_name] = {}
probes_results[probe_name][test_name] = test_results
return probes_results | Return the results of the RPM probes. | entailment |
def traceroute(self,
destination,
source=C.TRACEROUTE_SOURCE,
ttl=C.TRACEROUTE_TTL,
timeout=C.TRACEROUTE_TIMEOUT,
vrf=C.TRACEROUTE_VRF):
"""Execute traceroute and return results."""
traceroute_result = {}
# calling form RPC does not work properly :(
# but defined junos_route_instance_table just in case
source_str = ''
maxttl_str = ''
wait_str = ''
vrf_str = ''
if source:
source_str = ' source {source}'.format(source=source)
if ttl:
maxttl_str = ' ttl {ttl}'.format(ttl=ttl)
if timeout:
wait_str = ' wait {timeout}'.format(timeout=timeout)
if vrf:
vrf_str = ' routing-instance {vrf}'.format(vrf=vrf)
traceroute_command = 'traceroute {destination}{source}{maxttl}{wait}{vrf}'.format(
destination=destination,
source=source_str,
maxttl=maxttl_str,
wait=wait_str,
vrf=vrf_str
)
traceroute_rpc = E('command', traceroute_command)
rpc_reply = self.device._conn.rpc(traceroute_rpc)._NCElement__doc
# make direct RPC call via NETCONF
traceroute_results = rpc_reply.find('.//traceroute-results')
traceroute_failure = napalm_base.helpers.find_txt(
traceroute_results, 'traceroute-failure', '')
error_message = napalm_base.helpers.find_txt(
traceroute_results, 'rpc-error/error-message', '')
if traceroute_failure and error_message:
return {'error': '{}: {}'.format(traceroute_failure, error_message)}
traceroute_result['success'] = {}
for hop in traceroute_results.findall('hop'):
ttl_value = napalm_base.helpers.convert(
int, napalm_base.helpers.find_txt(hop, 'ttl-value'), 1)
if ttl_value not in traceroute_result['success']:
traceroute_result['success'][ttl_value] = {'probes': {}}
for probe in hop.findall('probe-result'):
probe_index = napalm_base.helpers.convert(
int, napalm_base.helpers.find_txt(probe, 'probe-index'), 0)
ip_address = napalm_base.helpers.convert(
napalm_base.helpers.ip, napalm_base.helpers.find_txt(probe, 'ip-address'), '*')
host_name = py23_compat.text_type(
napalm_base.helpers.find_txt(probe, 'host-name', '*'))
rtt = napalm_base.helpers.convert(
float, napalm_base.helpers.find_txt(probe, 'rtt'), 0) * 1e-3 # ms
traceroute_result['success'][ttl_value]['probes'][probe_index] = {
'ip_address': ip_address,
'host_name': host_name,
'rtt': rtt
}
return traceroute_result | Execute traceroute and return results. | entailment |
def parse_intf_section(interface):
"""Parse a single entry from show interfaces output.
Different cases:
mgmt0 is up
admin state is up
Ethernet2/1 is up
admin state is up, Dedicated Interface
Vlan1 is down (Administratively down), line protocol is down, autostate enabled
Ethernet154/1/48 is up (with no 'admin state')
"""
interface = interface.strip()
re_protocol = r"^(?P<intf_name>\S+?)\s+is\s+(?P<status>.+?)" \
r",\s+line\s+protocol\s+is\s+(?P<protocol>\S+).*$"
re_intf_name_state = r"^(?P<intf_name>\S+) is (?P<intf_state>\S+).*"
re_is_enabled_1 = r"^admin state is (?P<is_enabled>\S+)$"
re_is_enabled_2 = r"^admin state is (?P<is_enabled>\S+), "
re_is_enabled_3 = r"^.* is down.*Administratively down.*$"
re_mac = r"^\s+Hardware.*address:\s+(?P<mac_address>\S+) "
re_speed = r"^\s+MTU .*, BW (?P<speed>\S+) (?P<speed_unit>\S+), "
re_description = r"^\s+Description:\s+(?P<description>.*)$"
# Check for 'protocol is ' lines
match = re.search(re_protocol, interface, flags=re.M)
if match:
intf_name = match.group('intf_name')
status = match.group('status')
protocol = match.group('protocol')
if 'admin' in status.lower():
is_enabled = False
else:
is_enabled = True
is_up = bool('up' in protocol)
else:
# More standard is up, next line admin state is lines
match = re.search(re_intf_name_state, interface)
intf_name = match.group('intf_name')
intf_state = match.group('intf_state').strip()
is_up = True if intf_state == 'up' else False
admin_state_present = re.search("admin state is", interface)
if admin_state_present:
# Parse cases where 'admin state' string exists
for x_pattern in [re_is_enabled_1, re_is_enabled_2]:
match = re.search(x_pattern, interface, flags=re.M)
if match:
is_enabled = match.group('is_enabled').strip()
is_enabled = True if is_enabled == 'up' else False
break
else:
msg = "Error parsing intf, 'admin state' never detected:\n\n{}".format(interface)
raise ValueError(msg)
else:
# No 'admin state' should be 'is up' or 'is down' strings
# If interface is up; it is enabled
is_enabled = True
if not is_up:
match = re.search(re_is_enabled_3, interface, flags=re.M)
if match:
is_enabled = False
match = re.search(re_mac, interface, flags=re.M)
if match:
mac_address = match.group('mac_address')
mac_address = napalm_base.helpers.mac(mac_address)
else:
mac_address = ""
match = re.search(re_speed, interface, flags=re.M)
speed = int(match.group('speed'))
speed_unit = match.group('speed_unit')
# This was alway in Kbit (in the data I saw)
if speed_unit != "Kbit":
msg = "Unexpected speed unit in show interfaces parsing:\n\n{}".format(interface)
raise ValueError(msg)
speed = int(round(speed / 1000.0))
description = ''
match = re.search(re_description, interface, flags=re.M)
if match:
description = match.group('description')
return {
intf_name: {
'description': description,
'is_enabled': is_enabled,
'is_up': is_up,
'last_flapped': -1.0,
'mac_address': mac_address,
'speed': speed}
} | Parse a single entry from show interfaces output.
Different cases:
mgmt0 is up
admin state is up
Ethernet2/1 is up
admin state is up, Dedicated Interface
Vlan1 is down (Administratively down), line protocol is down, autostate enabled
Ethernet154/1/48 is up (with no 'admin state') | entailment |
def _get_diff(self):
"""Get a diff between running config and a proposed file."""
diff = []
self._create_sot_file()
command = ('show diff rollback-patch file {0} file {1}'.format(
'sot_file', self.replace_file.split('/')[-1]))
diff_out = self.device.send_command(command)
try:
diff_out = diff_out.split(
'#Generating Rollback Patch')[1].replace(
'Rollback Patch is Empty', '').strip()
for line in diff_out.splitlines():
if line:
if line[0].strip() != '!' and line[0].strip() != '.':
diff.append(line.rstrip(' '))
except (AttributeError, KeyError):
raise ReplaceConfigException(
'Could not calculate diff. It\'s possible the given file doesn\'t exist.')
return '\n'.join(diff) | Get a diff between running config and a proposed file. | entailment |
def _save_to_checkpoint(self, filename):
"""Save the current running config to the given file."""
command = 'checkpoint file {}'.format(filename)
self.device.send_command(command) | Save the current running config to the given file. | entailment |
def get_facts(self):
"""Return a set of facts from the devices."""
# default values.
vendor = u'Cisco'
uptime = -1
serial_number, fqdn, os_version, hostname, domain_name = ('',) * 5
# obtain output from device
show_ver = self.device.send_command('show version')
show_hosts = self.device.send_command('show hosts')
show_int_status = self.device.send_command('show interface status')
show_hostname = self.device.send_command('show hostname')
# uptime/serial_number/IOS version
for line in show_ver.splitlines():
if ' uptime is ' in line:
_, uptime_str = line.split(' uptime is ')
uptime = self.parse_uptime(uptime_str)
if 'Processor Board ID' in line:
_, serial_number = line.split("Processor Board ID ")
serial_number = serial_number.strip()
if 'system: ' in line:
line = line.strip()
os_version = line.split()[2]
os_version = os_version.strip()
if 'cisco' in line and 'Chassis' in line:
_, model = line.split()[:2]
model = model.strip()
hostname = show_hostname.strip()
# Determine domain_name and fqdn
for line in show_hosts.splitlines():
if 'Default domain' in line:
_, domain_name = re.split(r".*Default domain.*is ", line)
domain_name = domain_name.strip()
break
if hostname.count(".") >= 2:
fqdn = hostname
elif domain_name:
fqdn = '{}.{}'.format(hostname, domain_name)
# interface_list filter
interface_list = []
show_int_status = show_int_status.strip()
for line in show_int_status.splitlines():
if line.startswith(' ') or line.startswith('-') or line.startswith('Port '):
continue
interface = line.split()[0]
interface_list.append(interface)
return {
'uptime': int(uptime),
'vendor': vendor,
'os_version': py23_compat.text_type(os_version),
'serial_number': py23_compat.text_type(serial_number),
'model': py23_compat.text_type(model),
'hostname': py23_compat.text_type(hostname),
'fqdn': fqdn,
'interface_list': interface_list
} | Return a set of facts from the devices. | entailment |
def get_arp_table(self):
"""
Get arp table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float)
For example::
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 12.0
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 14.0
}
]
"""
arp_table = []
command = 'show ip arp vrf default | exc INCOMPLETE'
output = self.device.send_command(command)
separator = r"^Address\s+Age.*Interface.*$"
arp_list = re.split(separator, output, flags=re.M)
if len(arp_list) != 2:
raise ValueError("Error processing arp table output:\n\n{}".format(output))
arp_entries = arp_list[1].strip()
for line in arp_entries.splitlines():
if len(line.split()) == 4:
address, age, mac, interface = line.split()
else:
raise ValueError("Unexpected output from: {}".format(line.split()))
if age == '-':
age = -1.0
elif ':' not in age:
# Cisco sometimes returns a sub second arp time 0.411797
try:
age = float(age)
except ValueError:
age = -1.0
else:
age = convert_hhmmss(age)
age = float(age)
age = round(age, 1)
# Validate we matched correctly
if not re.search(RE_IPADDR, address):
raise ValueError("Invalid IP Address detected: {}".format(address))
if not re.search(RE_MAC, mac):
raise ValueError("Invalid MAC Address detected: {}".format(mac))
entry = {
'interface': interface,
'mac': napalm_base.helpers.mac(mac),
'ip': address,
'age': age
}
arp_table.append(entry)
return arp_table | Get arp table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float)
For example::
[
{
'interface' : 'MgmtEth0/RSP0/CPU0/0',
'mac' : '5c:5e:ab:da:3c:f0',
'ip' : '172.17.17.1',
'age' : 12.0
},
{
'interface': 'MgmtEth0/RSP0/CPU0/0',
'mac' : '66:0e:94:96:e0:ff',
'ip' : '172.17.17.2',
'age' : 14.0
}
] | entailment |
def get_mac_address_table(self):
"""
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address
Table, having the following keys
* mac (string)
* interface (string)
* vlan (int)
* active (boolean)
* static (boolean)
* moves (int)
* last_move (float)
Format1:
Legend:
* - primary entry, G - Gateway MAC, (R) - Routed MAC, O - Overlay MAC
age - seconds since last seen,+ - primary entry using vPC Peer-Link,
(T) - True, (F) - False
VLAN MAC Address Type age Secure NTFY Ports/SWID.SSID.LID
---------+-----------------+--------+---------+------+----+------------------
* 27 0026.f064.0000 dynamic - F F po1
* 27 001b.54c2.2644 dynamic - F F po1
* 27 0000.0c9f.f2bc dynamic - F F po1
* 27 0026.980a.df44 dynamic - F F po1
* 16 0050.56bb.0164 dynamic - F F po2
* 13 90e2.ba5a.9f30 dynamic - F F eth1/2
* 13 90e2.ba4b.fc78 dynamic - F F eth1/1
"""
# The '*' is stripped out later
RE_MACTABLE_FORMAT1 = r"^\s+{}\s+{}\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+".format(VLAN_REGEX,
MAC_REGEX)
RE_MACTABLE_FORMAT2 = r"^\s+{}\s+{}\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+".format('-',
MAC_REGEX)
mac_address_table = []
command = 'show mac address-table'
output = self.device.send_command(command) # noqa
def remove_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
def process_mac_fields(vlan, mac, mac_type, interface):
"""Return proper data for mac address fields."""
if mac_type.lower() in ['self', 'static', 'system']:
static = True
if vlan.lower() == 'all':
vlan = 0
elif vlan == '-':
vlan = 0
if interface.lower() == 'cpu' or re.search(r'router', interface.lower()) or \
re.search(r'switch', interface.lower()):
interface = ''
else:
static = False
if mac_type.lower() in ['dynamic']:
active = True
else:
active = False
return {
'mac': napalm_base.helpers.mac(mac),
'interface': interface,
'vlan': int(vlan),
'static': static,
'active': active,
'moves': -1,
'last_move': -1.0
}
# Skip the header lines
output = re.split(r'^----.*', output, flags=re.M)[1:]
output = "\n".join(output).strip()
# Strip any leading astericks or G character
output = re.sub(r"^[\*G]", "", output, flags=re.M)
for line in output.splitlines():
# Every 500 Mac's Legend is reprinted, regardless of term len.
# Above split will not help in this scenario
if re.search('^Legend', line):
continue
elif re.search('^\s+\* \- primary entry', line):
continue
elif re.search('^\s+age \-', line):
continue
elif re.search('^\s+VLAN', line):
continue
elif re.search('^------', line):
continue
elif re.search('^\s*$', line):
continue
for pattern in [RE_MACTABLE_FORMAT1, RE_MACTABLE_FORMAT2]:
if re.search(pattern, line):
if len(line.split()) == 7:
vlan, mac, mac_type, _, _, _, interface = line.split()
mac_address_table.append(process_mac_fields(vlan, mac, mac_type, interface))
break
else:
raise ValueError("Unexpected output from: {}".format(repr(line)))
return mac_address_table | Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address
Table, having the following keys
* mac (string)
* interface (string)
* vlan (int)
* active (boolean)
* static (boolean)
* moves (int)
* last_move (float)
Format1:
Legend:
* - primary entry, G - Gateway MAC, (R) - Routed MAC, O - Overlay MAC
age - seconds since last seen,+ - primary entry using vPC Peer-Link,
(T) - True, (F) - False
VLAN MAC Address Type age Secure NTFY Ports/SWID.SSID.LID
---------+-----------------+--------+---------+------+----+------------------
* 27 0026.f064.0000 dynamic - F F po1
* 27 001b.54c2.2644 dynamic - F F po1
* 27 0000.0c9f.f2bc dynamic - F F po1
* 27 0026.980a.df44 dynamic - F F po1
* 16 0050.56bb.0164 dynamic - F F po2
* 13 90e2.ba5a.9f30 dynamic - F F eth1/2
* 13 90e2.ba4b.fc78 dynamic - F F eth1/1 | entailment |
def get(self, request, format=None):
"""
Remove all auth tokens owned by request.user.
"""
tokens = Token.objects.filter(user=request.user)
for token in tokens:
token.delete()
content = {'success': _('User logged out.')}
return Response(content, status=status.HTTP_200_OK) | Remove all auth tokens owned by request.user. | entailment |
def _set_attrs_to_values(self, response={}):
"""
Set attributes to dictionary values so can access via dot notation.
"""
for key in response.keys():
setattr(self, key, response[key]) | Set attributes to dictionary values so can access via dot notation. | entailment |
def add_custom_nl2br_filters(self, app):
"""Add a custom filter nl2br to jinja2
Replaces all newline to <BR>
"""
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){3,}')
@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
result = '\n\n'.join('%s' % p.replace('\n', '<br>\n')
for p in _paragraph_re.split(value))
return result | Add a custom filter nl2br to jinja2
Replaces all newline to <BR> | entailment |
def doc(self, groups=None, set_location=True, **properties):
"""Add flask route to autodoc for automatic documentation
Any route decorated with this method will be added to the list of
routes to be documented by the generate() or html() methods.
By default, the route is added to the 'all' group.
By specifying group or groups argument, the route can be added to one
or multiple other groups as well, besides the 'all' group.
If set_location is True, the location of the function will be stored.
NOTE: this assumes that the decorator is placed just before the
function (in the normal way).
Custom parameters may also be passed in beyond groups, if they are
named something not already in the dict descibed in the docstring for
the generare() function, they will be added to the route's properties,
which can be accessed from the template.
If a parameter is passed in with a name that is already in the dict, but
not of a reserved name, the passed parameter overrides that dict value.
"""
def decorator(f):
# Get previous group list (if any)
if f in self.func_groups:
groupset = self.func_groups[f]
else:
groupset = set()
# Set group[s]
if type(groups) is list:
groupset.update(groups)
elif type(groups) is str:
groupset.add(groups)
groupset.add('all')
self.func_groups[f] = groupset
self.func_props[f] = properties
# Set location
if set_location:
caller_frame = inspect.stack()[1]
self.func_locations[f] = {
'filename': caller_frame[1],
'line': caller_frame[2],
}
return f
return decorator | Add flask route to autodoc for automatic documentation
Any route decorated with this method will be added to the list of
routes to be documented by the generate() or html() methods.
By default, the route is added to the 'all' group.
By specifying group or groups argument, the route can be added to one
or multiple other groups as well, besides the 'all' group.
If set_location is True, the location of the function will be stored.
NOTE: this assumes that the decorator is placed just before the
function (in the normal way).
Custom parameters may also be passed in beyond groups, if they are
named something not already in the dict descibed in the docstring for
the generare() function, they will be added to the route's properties,
which can be accessed from the template.
If a parameter is passed in with a name that is already in the dict, but
not of a reserved name, the passed parameter overrides that dict value. | entailment |
def generate(self, groups='all', sort=None):
"""Return a list of dict describing the routes specified by the
doc() method
Each dict contains:
- methods: the set of allowed methods (ie ['GET', 'POST'])
- rule: relative url (ie '/user/<int:id>')
- endpoint: function name (ie 'show_user')
- doc: docstring of the function
- args: function arguments
- defaults: defaults values for the arguments
By specifying the group or groups arguments, only routes belonging to
those groups will be returned.
Routes are sorted alphabetically based on the rule.
"""
groups_to_generate = list()
if type(groups) is list:
groups_to_generate = groups
elif type(groups) is str:
groups_to_generate.append(groups)
links = []
for rule in current_app.url_map.iter_rules():
if rule.endpoint == 'static':
continue
func = current_app.view_functions[rule.endpoint]
arguments = rule.arguments if rule.arguments else ['None']
func_groups = self.func_groups[func]
func_props = self.func_props[func] if func in self.func_props \
else {}
location = self.func_locations.get(func, None)
if func_groups.intersection(groups_to_generate):
props = dict(
methods=rule.methods,
rule="%s" % rule,
endpoint=rule.endpoint,
docstring=func.__doc__,
args=arguments,
defaults=rule.defaults,
location=location,
)
for p in func_props:
if p not in self.immutable_props:
props[p] = func_props[p]
links.append(props)
if sort:
return sort(links)
else:
return sorted(links, key=itemgetter('rule')) | Return a list of dict describing the routes specified by the
doc() method
Each dict contains:
- methods: the set of allowed methods (ie ['GET', 'POST'])
- rule: relative url (ie '/user/<int:id>')
- endpoint: function name (ie 'show_user')
- doc: docstring of the function
- args: function arguments
- defaults: defaults values for the arguments
By specifying the group or groups arguments, only routes belonging to
those groups will be returned.
Routes are sorted alphabetically based on the rule. | entailment |
def html(self, groups='all', template=None, **context):
"""Return an html string of the routes specified by the doc() method
A template can be specified. A list of routes is available under the
'autodoc' value (refer to the documentation for the generate() for a
description of available values). If no template is specified, a
default template is used.
By specifying the group or groups arguments, only routes belonging to
those groups will be returned.
"""
context['autodoc'] = context['autodoc'] if 'autodoc' in context \
else self.generate(groups=groups)
context['defaults'] = context['defaults'] if 'defaults' in context \
else self.default_props
if template:
return render_template(template, **context)
else:
filename = os.path.join(
os.path.dirname(__file__),
'templates',
'autodoc_default.html'
)
with open(filename) as file:
content = file.read()
with current_app.app_context():
return render_template_string(content, **context) | Return an html string of the routes specified by the doc() method
A template can be specified. A list of routes is available under the
'autodoc' value (refer to the documentation for the generate() for a
description of available values). If no template is specified, a
default template is used.
By specifying the group or groups arguments, only routes belonging to
those groups will be returned. | entailment |
def unsaved_files_dialog(
self, all_files=False, with_cancel=True, with_discard=True):
"""Return true if OK to continue with close or quit or whatever"""
for image in self.images:
if image.metadata.changed() and (all_files or image.selected):
break
else:
return True
dialog = QtWidgets.QMessageBox()
dialog.setWindowTitle(self.tr('Photini: unsaved data'))
dialog.setText(self.tr('<h3>Some images have unsaved metadata.</h3>'))
dialog.setInformativeText(self.tr('Do you want to save your changes?'))
dialog.setIcon(QtWidgets.QMessageBox.Warning)
buttons = QtWidgets.QMessageBox.Save
if with_cancel:
buttons |= QtWidgets.QMessageBox.Cancel
if with_discard:
buttons |= QtWidgets.QMessageBox.Discard
dialog.setStandardButtons(buttons)
dialog.setDefaultButton(QtWidgets.QMessageBox.Save)
result = dialog.exec_()
if result == QtWidgets.QMessageBox.Save:
self._save_files()
return True
return result == QtWidgets.QMessageBox.Discard | Return true if OK to continue with close or quit or whatever | entailment |
def from_ISO_8601(cls, date_string, time_string, tz_string):
"""Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601
"""
# parse tz_string
if tz_string:
tz_offset = (int(tz_string[1:3]) * 60) + int(tz_string[3:])
if tz_string[0] == '-':
tz_offset = -tz_offset
else:
tz_offset = None
if time_string == '000000':
# assume no time information
time_string = ''
tz_offset = None
datetime_string = date_string + time_string[:13]
precision = min((len(datetime_string) - 2) // 2, 7)
if precision <= 0:
return None
fmt = ''.join(('%Y', '%m', '%d', '%H', '%M', '%S', '.%f')[:precision])
return cls(
(datetime.strptime(datetime_string, fmt), precision, tz_offset)) | Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601 | entailment |
def post_post():
"""Create a new post.
Form Data: title, content, authorid.
"""
authorid = request.form.get('authorid', None)
Post(request.form['title'],
request.form['content'],
users[authorid])
return redirect("/posts") | Create a new post.
Form Data: title, content, authorid. | entailment |
def xpath(self, xpath):
""" Finds another node by XPath originating at the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_xpath_ids(xpath).split(",")
if node_id] | Finds another node by XPath originating at the current node. | entailment |
def css(self, css):
""" Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_css_ids(css).split(",")
if node_id] | Finds another node by a CSS selector relative to the current node. | entailment |
def get_bool_attr(self, name):
""" Returns the value of a boolean HTML attribute like `checked` or `disabled`
"""
val = self.get_attr(name)
return val is not None and val.lower() in ("true", name) | Returns the value of a boolean HTML attribute like `checked` or `disabled` | entailment |
def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value))) | Sets the value of an attribute. | entailment |
def value(self):
""" Returns the node's value. """
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value") | Returns the node's value. | entailment |
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value) | Sets a HTTP header for future requests. | entailment |
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res | Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`. | entailment |
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0] | Evaluates a piece of Javascript in the context of the current page and
returns its value. | entailment |
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height) | Renders the current page to a PNG file (viewport size in pixels). | entailment |
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()] | Returns a list of all cookies in cookie string format. | entailment |
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value) | Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_. | entailment |
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html) | Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. | entailment |
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password) | Sets a custom HTTP proxy to use for future requests. | entailment |
def connect(self):
""" Returns a new socket connection to this server. """
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", self._port))
return sock | Returns a new socket connection to this server. | entailment |
def read_line(self):
""" Consume one line from the stream. """
while True:
newline_idx = self.buf.find(b"\n")
if newline_idx >= 0:
res = self.buf[:newline_idx]
self.buf = self.buf[newline_idx + 1:]
return res
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk | Consume one line from the stream. | entailment |
def read(self, n):
""" Consume `n` characters from the stream. """
while len(self.buf) < n:
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
res, self.buf = self.buf[:n], self.buf[n:]
return res | Consume `n` characters from the stream. | entailment |
def issue_command(self, cmd, *args):
""" Sends and receives a message to/from the server """
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encode("utf-8"))
return self._read_response() | Sends and receives a message to/from the server | entailment |
def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != "ok":
raise InvalidResponseError(msg)
return msg | Reads a complete response packet from the server | entailment |
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8") | Reads a single size-annotated message from the server | entailment |
def get_deep_search_results(self, address, zipcode):
"""
GetDeepSearchResults API
"""
url = 'http://www.zillow.com/webservice/GetDeepSearchResults.htm'
params = {
'address': address,
'citystatezip': zipcode,
'zws-id': self.api_key
}
return self.get_data(url, params) | GetDeepSearchResults API | entailment |
def get_updated_property_details(self, zpid):
"""
GetUpdatedPropertyDetails API
"""
url = 'http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm'
params = {
'zpid': zpid,
'zws-id': self.api_key
}
return self.get_data(url, params) | GetUpdatedPropertyDetails API | entailment |
def fix_orientation(img, save_over=False):
"""
`img` can be an Image instance or a path to an image file.
`save_over` indicates if the original image file should be replaced by the new image.
* Note: `save_over` is only valid if `img` is a file path.
"""
path = None
if not isinstance(img, Image.Image):
path = img
img = Image.open(path)
elif save_over:
raise ValueError("You can't use `save_over` when passing an Image instance. Use a file path instead.")
try:
orientation = img._getexif()[EXIF_ORIENTATION_TAG]
except (TypeError, AttributeError, KeyError):
raise ValueError("Image file has no EXIF data.")
if orientation in [3,6,8]:
degrees = ORIENTATIONS[orientation][1]
img = img.transpose(degrees)
if save_over and path is not None:
try:
img.save(path, quality=95, optimize=1)
except IOError:
# Try again, without optimization (PIL can't optimize an image
# larger than ImageFile.MAXBLOCK, which is 64k by default).
# Setting ImageFile.MAXBLOCK should fix this....but who knows.
img.save(path, quality=95)
return (img, degrees)
else:
return (img, 0) | `img` can be an Image instance or a path to an image file.
`save_over` indicates if the original image file should be replaced by the new image.
* Note: `save_over` is only valid if `img` is a file path. | entailment |
def log_error(self, error, message, detail=None, strip=4):
"Add an error message and optional user message to the error list"
if message:
msg = message + ": " + error
else:
msg = error
tb = traceback.format_stack()
if sys.version_info >= (3, 0):
tb = tb[:-strip]
else:
tb = tb[strip:]
self.errors.append({
'message': msg,
'traceback': tb,
'detail': detail
}) | Add an error message and optional user message to the error list | entailment |
def equal(self, a, b, message=None):
"Check if two values are equal"
if a != b:
self.log_error("{} != {}".format(str(a), str(b)), message)
return False
return True | Check if two values are equal | entailment |
def is_not_none(self, a, message=None):
"Check if a value is not None"
if a is None:
self.log_error("{} is None".format(str(a)), message)
return False
return True | Check if a value is not None | entailment |
def raises(self, exception_type, function, *args, **kwargs):
"""
Check if a function raises a specified exception type,
*args and **kwargs are forwarded to the function
"""
try:
result = function(*args, **kwargs)
self.log_error("{} did not throw exception {}".format(
function.__name__,
exception_type.__name__
), None)
return result
except Exception as e:
if type(e) != exception_type:
self.log_error("{} did raise {}: {}".format(
function.__name__,
type(e).__name__, e
), None) | Check if a function raises a specified exception type,
*args and **kwargs are forwarded to the function | entailment |
def does_not_raise(self, function, *args, **kwargs):
"""
Check if a function does not raise an exception,
*args and **kwargs are forwarded to the function
"""
try:
return function(*args, **kwargs)
except Exception as e:
self.log_error("{} did raise {}: {}".format(
function.__name__,
type(e).__name__, e
), None) | Check if a function does not raise an exception,
*args and **kwargs are forwarded to the function | entailment |
def calculate_color_temperature(r, g, b):
"""Converts the raw R/G/B values to color temperature in degrees Kelvin."""
# 1. Map RGB values to their XYZ counterparts.
# Based on 6500K fluorescent, 3000K fluorescent
# and 60W incandescent values for a wide range.
# Note: Y = Illuminance or lux
X = (-0.14282 * r) + (1.54924 * g) + (-0.95641 * b)
Y = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
Z = (-0.68202 * r) + (0.77073 * g) + ( 0.56332 * b)
# Check for divide by 0 (total darkness) and return None.
if (X + Y + Z) == 0:
return None
# 2. Calculate the chromaticity co-ordinates
xc = (X) / (X + Y + Z)
yc = (Y) / (X + Y + Z)
# Check for divide by 0 again and return None.
if (0.1858 - yc) == 0:
return None
# 3. Use McCamy's formula to determine the CCT
n = (xc - 0.3320) / (0.1858 - yc)
# Calculate the final CCT
cct = (449.0 * (n ** 3.0)) + (3525.0 *(n ** 2.0)) + (6823.3 * n) + 5520.33
return int(cct) | Converts the raw R/G/B values to color temperature in degrees Kelvin. | entailment |
def calculate_lux(r, g, b):
"""Converts the raw R/G/B values to luminosity in lux."""
illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
return int(illuminance) | Converts the raw R/G/B values to luminosity in lux. | entailment |
def _write8(self, reg, value):
"""Write a 8-bit value to a register."""
self._device.write8(TCS34725_COMMAND_BIT | reg, value) | Write a 8-bit value to a register. | entailment |
def enable(self):
"""Enable the chip."""
# Flip on the power and enable bits.
self._write8(TCS34725_ENABLE, TCS34725_ENABLE_PON)
time.sleep(0.01)
self._write8(TCS34725_ENABLE, (TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)) | Enable the chip. | entailment |
def disable(self):
"""Disable the chip (power down)."""
# Flip off the power on and enable bits.
reg = self._readU8(TCS34725_ENABLE)
reg &= ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)
self._write8(TCS34725_ENABLE, reg) | Disable the chip (power down). | entailment |
def set_integration_time(self, integration_time):
"""Sets the integration time for the TC34725. Provide one of these
constants:
- TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024
- TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240
- TCS34725_INTEGRATIONTIME_50MS = 50ms - 20 cycles - Max Count: 20480
- TCS34725_INTEGRATIONTIME_101MS = 101ms - 42 cycles - Max Count: 43008
- TCS34725_INTEGRATIONTIME_154MS = 154ms - 64 cycles - Max Count: 65535
- TCS34725_INTEGRATIONTIME_700MS = 700ms - 256 cycles - Max Count: 65535
"""
self._integration_time = integration_time
self._write8(TCS34725_ATIME, integration_time) | Sets the integration time for the TC34725. Provide one of these
constants:
- TCS34725_INTEGRATIONTIME_2_4MS = 2.4ms - 1 cycle - Max Count: 1024
- TCS34725_INTEGRATIONTIME_24MS = 24ms - 10 cycles - Max Count: 10240
- TCS34725_INTEGRATIONTIME_50MS = 50ms - 20 cycles - Max Count: 20480
- TCS34725_INTEGRATIONTIME_101MS = 101ms - 42 cycles - Max Count: 43008
- TCS34725_INTEGRATIONTIME_154MS = 154ms - 64 cycles - Max Count: 65535
- TCS34725_INTEGRATIONTIME_700MS = 700ms - 256 cycles - Max Count: 65535 | entailment |
def get_raw_data(self):
"""Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers).
"""
# Read each color register.
r = self._readU16LE(TCS34725_RDATAL)
g = self._readU16LE(TCS34725_GDATAL)
b = self._readU16LE(TCS34725_BDATAL)
c = self._readU16LE(TCS34725_CDATAL)
# Delay for the integration time to allow for next reading immediately.
time.sleep(INTEGRATION_TIME_DELAY[self._integration_time])
return (r, g, b, c) | Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers). | entailment |
def set_interrupt(self, enabled):
"""Enable or disable interrupts by setting enabled to True or False."""
enable_reg = self._readU8(TCS34725_ENABLE)
if enabled:
enable_reg |= TCS34725_ENABLE_AIEN
else:
enable_reg &= ~TCS34725_ENABLE_AIEN
self._write8(TCS34725_ENABLE, enable_reg)
time.sleep(1) | Enable or disable interrupts by setting enabled to True or False. | entailment |
def set_interrupt_limits(self, low, high):
"""Set the interrupt limits to provied unsigned 16-bit threshold values.
"""
self._device.write8(0x04, low & 0xFF)
self._device.write8(0x05, low >> 8)
self._device.write8(0x06, high & 0xFF)
self._device.write8(0x07, high >> 8) | Set the interrupt limits to provied unsigned 16-bit threshold values. | entailment |
def convert(json_input, build_direction="LEFT_TO_RIGHT", table_attributes=None):
"""
Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
build_direction : {"TOP_TO_BOTTOM", "LEFT_TO_RIGHT"}
String denoting the build direction of the table. If ``"TOP_TO_BOTTOM"`` child
objects will be appended below parents, i.e. in the subsequent row. If ``"LEFT_TO_RIGHT"``
child objects will be appended to the right of parents, i.e. in the subsequent column.
Default is ``"LEFT_TO_RIGHT"``.
table_attributes : dict, optional
Dictionary of ``(key, value)`` pairs describing attributes to add to the table.
Each attribute is added according to the template ``key="value". For example,
the table ``{ "border" : 1 }`` modifies the generated table tags to include
``border="1"`` as an attribute. The generated opening tag would look like
``<table border="1">``. Default is ``None``.
Returns
-------
str
String of converted HTML.
An example usage is shown below:
>>> json_object = {"key" : "value"}
>>> build_direction = "TOP_TO_BOTTOM"
>>> table_attributes = {"border" : 1}
>>> html = convert(json_object, build_direction=build_direction, table_attributes=table_attributes)
>>> print(html)
"<table border="1"><tr><th>key</th><td>value</td></tr></table>"
"""
json_converter = JsonConverter(build_direction=build_direction, table_attributes=table_attributes)
return json_converter.convert(json_input) | Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
build_direction : {"TOP_TO_BOTTOM", "LEFT_TO_RIGHT"}
String denoting the build direction of the table. If ``"TOP_TO_BOTTOM"`` child
objects will be appended below parents, i.e. in the subsequent row. If ``"LEFT_TO_RIGHT"``
child objects will be appended to the right of parents, i.e. in the subsequent column.
Default is ``"LEFT_TO_RIGHT"``.
table_attributes : dict, optional
Dictionary of ``(key, value)`` pairs describing attributes to add to the table.
Each attribute is added according to the template ``key="value". For example,
the table ``{ "border" : 1 }`` modifies the generated table tags to include
``border="1"`` as an attribute. The generated opening tag would look like
``<table border="1">``. Default is ``None``.
Returns
-------
str
String of converted HTML.
An example usage is shown below:
>>> json_object = {"key" : "value"}
>>> build_direction = "TOP_TO_BOTTOM"
>>> table_attributes = {"border" : 1}
>>> html = convert(json_object, build_direction=build_direction, table_attributes=table_attributes)
>>> print(html)
"<table border="1"><tr><th>key</th><td>value</td></tr></table>" | entailment |
def convert(self, json_input):
"""
Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
Returns
-------
str
String of converted HTML.
"""
html_output = self._table_opening_tag
if self._build_top_to_bottom:
html_output += self._markup_header_row(json_input.keys())
html_output += "<tr>"
for value in json_input.values():
if isinstance(value, list):
# check if all keys in the list are identical
# and group all values under a common column
# heading if so, if not default to normal markup
html_output += self._maybe_club(value)
else:
html_output += self._markup_table_cell(value)
html_output += "</tr>"
else:
for key, value in iter(json_input.items()):
html_output += "<tr><th>{:s}</th>".format(self._markup(key))
if isinstance(value, list):
html_output += self._maybe_club(value)
else:
html_output += self._markup_table_cell(value)
html_output += "</tr>"
html_output += "</table>"
return html_output | Converts JSON to HTML Table format.
Parameters
----------
json_input : dict
JSON object to convert into HTML.
Returns
-------
str
String of converted HTML. | entailment |
def _dict_to_html_attributes(d):
"""
Converts a dictionary to a string of ``key=\"value\"`` pairs.
If ``None`` is provided as the dictionary an empty string is returned,
i.e. no html attributes are generated.
Parameters
----------
d : dict
Dictionary to convert to html attributes.
Returns
-------
str
String of HTML attributes in the form ``key_i=\"value_i\" ... key_N=\"value_N\"``,
where ``N`` is the total number of ``(key, value)`` pairs.
"""
if d is None:
return ""
return "".join(" {}=\"{}\"".format(key, value) for key, value in iter(d.items())) | Converts a dictionary to a string of ``key=\"value\"`` pairs.
If ``None`` is provided as the dictionary an empty string is returned,
i.e. no html attributes are generated.
Parameters
----------
d : dict
Dictionary to convert to html attributes.
Returns
-------
str
String of HTML attributes in the form ``key_i=\"value_i\" ... key_N=\"value_N\"``,
where ``N`` is the total number of ``(key, value)`` pairs. | entailment |
def _list_of_dicts_to_column_headers(list_of_dicts):
"""
Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to test for identical keys.
Returns
-------
list or None
List of column headers if all dictionary posessed the same keys. Returns ``None`` otherwise.
"""
if len(list_of_dicts) < 2 or not all(isinstance(item, dict) for item in list_of_dicts):
return None
column_headers = list_of_dicts[0].keys()
for d in list_of_dicts[1:]:
if len(d.keys()) != len(column_headers) or not all(header in d for header in column_headers):
return None
return column_headers | Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to test for identical keys.
Returns
-------
list or None
List of column headers if all dictionary posessed the same keys. Returns ``None`` otherwise. | entailment |
def _markup(self, entry):
"""
Recursively generates HTML for the current entry.
Parameters
----------
entry : object
Object to convert to HTML. Maybe be a single entity or contain multiple and/or nested objects.
Returns
-------
str
String of HTML formatted json.
"""
if entry is None:
return ""
if isinstance(entry, list):
list_markup = "<ul>"
for item in entry:
list_markup += "<li>{:s}</li>".format(self._markup(item))
list_markup += "</ul>"
return list_markup
if isinstance(entry, dict):
return self.convert(entry)
# default to stringifying entry
return str(entry) | Recursively generates HTML for the current entry.
Parameters
----------
entry : object
Object to convert to HTML. Maybe be a single entity or contain multiple and/or nested objects.
Returns
-------
str
String of HTML formatted json. | entailment |
def _maybe_club(self, list_of_dicts):
"""
If all keys in a list of dicts are identical, values from each ``dict``
are clubbed, i.e. inserted under a common column heading. If the keys
are not identical ``None`` is returned, and the list should be converted
to HTML per the normal ``convert`` function.
Parameters
----------
list_of_dicts : list
List to attempt to club.
Returns
-------
str or None
String of HTML if list was successfully clubbed. Returns ``None`` otherwise.
Example
-------
Given the following json object::
{
"sampleData": [
{"a":1, "b":2, "c":3},
{"a":5, "b":6, "c":7}]
}
Calling ``_maybe_club`` would result in the following HTML table:
_____________________________
| | | | |
| | a | c | b |
| sampleData |---|---|---|
| | 1 | 3 | 2 |
| | 5 | 7 | 6 |
-----------------------------
Adapted from a contribution from @muellermichel to ``json2html``.
"""
column_headers = JsonConverter._list_of_dicts_to_column_headers(list_of_dicts)
if column_headers is None:
# common headers not found, return normal markup
html_output = self._markup(list_of_dicts)
else:
html_output = self._table_opening_tag
html_output += self._markup_header_row(column_headers)
for list_entry in list_of_dicts:
html_output += "<tr><td>"
html_output += "</td><td>".join(self._markup(list_entry[column_header]) for column_header in column_headers)
html_output += "</td></tr>"
html_output += "</table>"
return self._markup_table_cell(html_output) | If all keys in a list of dicts are identical, values from each ``dict``
are clubbed, i.e. inserted under a common column heading. If the keys
are not identical ``None`` is returned, and the list should be converted
to HTML per the normal ``convert`` function.
Parameters
----------
list_of_dicts : list
List to attempt to club.
Returns
-------
str or None
String of HTML if list was successfully clubbed. Returns ``None`` otherwise.
Example
-------
Given the following json object::
{
"sampleData": [
{"a":1, "b":2, "c":3},
{"a":5, "b":6, "c":7}]
}
Calling ``_maybe_club`` would result in the following HTML table:
_____________________________
| | | | |
| | a | c | b |
| sampleData |---|---|---|
| | 1 | 3 | 2 |
| | 5 | 7 | 6 |
-----------------------------
Adapted from a contribution from @muellermichel to ``json2html``. | entailment |
def update_voice_notify(self, param, must=[APIKEY, TPL_ID, TPL_CONTENT]):
'''修改语音通知模版
注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错!
参数:
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
tpl_id Long 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板 9527
tpl_content String 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板模板内容 您的验证码是#code#
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()])
return self.path('update_voice_notify.json').post(param, h, r) | 修改语音通知模版
注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错!
参数:
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
tpl_id Long 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板 9527
tpl_content String 是 模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板模板内容 您的验证码是#code#
Args:
param:
Results:
Result | entailment |
def code(self, code=None, ret_r=False):
'''
Args:
code: (Optional) set code
ret_r: (Optional) force to return Result. Default value is False
returns:
response code(0-success, others-failure) or self
'''
if code or ret_r:
self._code = code
return self
return self._code | Args:
code: (Optional) set code
ret_r: (Optional) force to return Result. Default value is False
returns:
response code(0-success, others-failure) or self | entailment |
def msg(self, msg=None, ret_r=False):
'''code's message'''
if msg or ret_r:
self._msg = msg
return self
return self._msg | code's message | entailment |
def detail(self, detail=None, ret_r=False):
'''code's detail'''
if detail or ret_r:
self._detail = detail
return self
return self._detail | code's detail | entailment |
def data(self, data=None, ret_r=False):
'''response data'''
if data or ret_r:
self._data = data
return self
return self._data | response data | entailment |
def get(self, param=None, must=[APIKEY]):
'''查账户信息
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
Args:
param: (Optional)
Results:
Result
'''
param = {} if param is None else param
r = self.verify_param(param, must)
if not r.is_succ():
return r
handle = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(USER), VERSION_V2:rsp}[self.version()])
return self.path('get.json').post(param, handle, r) | 查账户信息
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
Args:
param: (Optional)
Results:
Result | entailment |
def _init(self, clnt):
'''initialize api by YunpianClient'''
assert clnt, "clnt is None"
self._clnt = clnt
self._apikey = clnt.apikey()
self._version = clnt.conf(YP_VERSION, defval=VERSION_V2)
self._charset = clnt.conf(HTTP_CHARSET, defval=CHARSET_UTF8)
self._name = self.__class__.__module__.split('.')[-1] | initialize api by YunpianClient | entailment |
def name(self, name=None):
'''api name, default is module.__name__'''
if name:
self._name = name
return self
return self._name | api name, default is module.__name__ | entailment |
def post(self, param, h, r):
'''
Args:
param: request parameters
h: ResultHandler
r: YunpianApiResult
'''
try:
rsp = self.client().post(self.uri(), param)
# print(rsp)
return self.result(rsp, h, r)
except ValueError as err:
return h.catch_exception(err, r) | Args:
param: request parameters
h: ResultHandler
r: YunpianApiResult | entailment |
def verify_param(self, param, must=[], r=None):
'''return Code.ARGUMENT_MISSING if every key in must not found in param'''
if APIKEY not in param:
param[APIKEY] = self.apikey()
r = Result() if r is None else r
for p in must:
if p not in param:
r.code(Code.ARGUMENT_MISSING).detail('missing-' + p)
break
return r | return Code.ARGUMENT_MISSING if every key in must not found in param | entailment |
def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self | custom apikey and http parameters | entailment |
def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) | get config | entailment |
def api(self, name):
'''return special API by package's name'''
assert name, 'name is none'
if flow.__name__ == name:
api = flow.FlowApi()
elif sign.__name__ == name:
api = sign.SignApi()
elif sms.__name__ == name:
api = sms.SmsApi()
elif tpl.__name__ == name:
api = tpl.TplApi()
elif user.__name__ == name:
api = user.UserApi()
elif voice.__name__ == name:
api = voice.VoiceApi()
assert api, "not found api-" + name
api._init(self._clnt)
return api | return special API by package's name | entailment |
def conf(self, key=None, defval=None):
'''return YunpianConf if key=None, else return value in YunpianConf'''
if key is None:
return self._ypconf
val = self._ypconf.conf(key)
return defval if val is None else val | return YunpianConf if key=None, else return value in YunpianConf | entailment |
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
'''response json text'''
if 'Api-Lang' not in headers:
headers['Api-Lang'] = 'python'
if 'Content-Type' not in headers:
headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset
rsp = requests.post(url, data, headers=headers,
timeout=(int(self.conf(HTTP_CONN_TIMEOUT, '10')), int(self.conf(HTTP_SO_TIMEOUT, '30'))))
return json.loads(rsp.text) | response json text | entailment |
def urlEncodeAndJoin(self, seq, sepr=','):
'''sepr.join(urlencode(seq))
Args:
seq: string list to be urlencoded
sepr: join seq with sepr
Returns:
str
'''
try:
from urllib.parse import quote_plus as encode
return sepr.join([encode(x, encoding=CHARSET_UTF8) for x in seq])
except ImportError:
from urllib import quote as encode
return sepr.join([i for i in map(lambda x: encode(x), seq)]) | sepr.join(urlencode(seq))
Args:
seq: string list to be urlencoded
sepr: join seq with sepr
Returns:
str | entailment |
def send(self, param, must=[APIKEY, MOBILE, CODE]):
'''发语音验证码
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号、固话(需加区号) 15205201314 01088880000
code String 是 验证码,支持4~6位阿拉伯数字 1234
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
callback_url String 否 本条语音验证码状态报告推送地址 http://your_receive_url_address
display_num String 否 透传号码,为保证全国范围的呼通率,云片会自动选择最佳的线路,透传的主叫号码也会相应变化。
如需透传固定号码则需要单独注册报备,为了确保号码真实有效,客服将要求您使用报备的号码拨打一次客服电话
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp.get(RESULT), VERSION_V2:rsp}[self.version()])
return self.path('send.json').post(param, h, r) | 发语音验证码
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号、固话(需加区号) 15205201314 01088880000
code String 是 验证码,支持4~6位阿拉伯数字 1234
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
callback_url String 否 本条语音验证码状态报告推送地址 http://your_receive_url_address
display_num String 否 透传号码,为保证全国范围的呼通率,云片会自动选择最佳的线路,透传的主叫号码也会相应变化。
如需透传固定号码则需要单独注册报备,为了确保号码真实有效,客服将要求您使用报备的号码拨打一次客服电话
Args:
param:
Results:
Result | entailment |
def single_send(self, param, must=[APIKEY, MOBILE, TEXT]):
'''单条发送
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是"+"号开头("+"号需要urlencode处理,否则会出现格式错误),国际号码不以"+"开头将被认为是中国地区的号码
(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 国内号码:15205201314
国际号码:urlencode("+93701234567");
text String 是 短信内容 【云片网】您的验证码是1234
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 该条短信在您业务系统内的ID,比如订单号或者短信发送记录的流水号。填写后发送状态返回值内将包含这个ID
默认不开放,如有需要请联系客服申请 10001
callback_url String 否
本条短信状态报告推送地址。短信发送后将向这个地址推送短信发送报告。"后台-系统设置-数据推送与获取”可以做批量设置。如果后台已经设置地址的情况下,单次请求内也包含此参数,将以请求内的推送地址为准。
http://your_receive_url_address
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V2:rsp}[self.version()])
return self.path('single_send.json').post(param, h, r) | 单条发送
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号;仅支持单号码发送;国际号码需包含国际地区前缀号码,格式必须是"+"号开头("+"号需要urlencode处理,否则会出现格式错误),国际号码不以"+"开头将被认为是中国地区的号码
(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 国内号码:15205201314
国际号码:urlencode("+93701234567");
text String 是 短信内容 【云片网】您的验证码是1234
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 该条短信在您业务系统内的ID,比如订单号或者短信发送记录的流水号。填写后发送状态返回值内将包含这个ID
默认不开放,如有需要请联系客服申请 10001
callback_url String 否
本条短信状态报告推送地址。短信发送后将向这个地址推送短信发送报告。"后台-系统设置-数据推送与获取”可以做批量设置。如果后台已经设置地址的情况下,单次请求内也包含此参数,将以请求内的推送地址为准。
http://your_receive_url_address
Args:
param:
Results:
Result | entailment |
def pull_reply(self, param=None, must=[APIKEY]):
'''获取回复短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size Integer 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result
'''
param = {} if param is None else param
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS_REPLY] if SMS_REPLY in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('pull_reply.json').post(param, h, r) | 获取回复短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size Integer 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result | entailment |
def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]):
'''查回复的短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信回复开始时间 2013-08-11 00:00:00
end_time String 是 短信回复结束时间 2013-08-12 00:00:00
page_num Integer 是 页码,默认值为1 1
page_size Integer 是 每页个数,最大100个 20
mobile String 否 填写时只查该手机号的回复,不填时查所有的回复 15205201314
return_fields 否 返回字段(暂未开放
sort_fields 否 排序字段(暂未开放) 默认按提交时间降序
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS_REPLY] if SMS_REPLY in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('get_reply.json').post(param, h, r) | 查回复的短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信回复开始时间 2013-08-11 00:00:00
end_time String 是 短信回复结束时间 2013-08-12 00:00:00
page_num Integer 是 页码,默认值为1 1
page_size Integer 是 每页个数,最大100个 20
mobile String 否 填写时只查该手机号的回复,不填时查所有的回复 15205201314
return_fields 否 返回字段(暂未开放
sort_fields 否 排序字段(暂未开放) 默认按提交时间降序
Args:
param:
Results:
Result | entailment |
def get_record(self, param, must=[APIKEY, START_TIME, END_TIME]):
'''查短信发送记录
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 否 需要查询的手机号 15205201314
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
page_num Integer 否 页码,默认值为1 1
page_size Integer 否 每页个数,最大100个 20
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS] if SMS in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('get_record.json').post(param, h, r) | 查短信发送记录
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 否 需要查询的手机号 15205201314
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
page_num Integer 否 页码,默认值为1 1
page_size Integer 否 每页个数,最大100个 20
Args:
param:
Results:
Result | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.