repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | parse_intf_section | 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}
} | python | 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}
} | [
"def",
"parse_intf_section",
"(",
"interface",
")",
":",
"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') | [
"Parse",
"a",
"single",
"entry",
"from",
"show",
"interfaces",
"output",
"."
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L74-L169 | train |
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | NXOSSSHDriver._get_diff | 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) | python | 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) | [
"def",
"_get_diff",
"(",
"self",
")",
":",
"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. | [
"Get",
"a",
"diff",
"between",
"running",
"config",
"and",
"a",
"proposed",
"file",
"."
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L595-L613 | train |
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | NXOSSSHDriver._save_to_checkpoint | 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) | python | 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) | [
"def",
"_save_to_checkpoint",
"(",
"self",
",",
"filename",
")",
":",
"command",
"=",
"'checkpoint file {}'",
".",
"format",
"(",
"filename",
")",
"self",
".",
"device",
".",
"send_command",
"(",
"command",
")"
] | Save the current running config to the given file. | [
"Save",
"the",
"current",
"running",
"config",
"to",
"the",
"given",
"file",
"."
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L657-L660 | train |
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | NXOSSSHDriver.get_facts | 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
} | python | 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
} | [
"def",
"get_facts",
"(",
"self",
")",
":",
"# 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. | [
"Return",
"a",
"set",
"of",
"facts",
"from",
"the",
"devices",
"."
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L736-L799 | train |
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | NXOSSSHDriver.get_arp_table | 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 | python | 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 | [
"def",
"get_arp_table",
"(",
"self",
")",
":",
"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
}
] | [
"Get",
"arp",
"table",
"information",
"."
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L1037-L1105 | train |
napalm-automation/napalm-nxos | napalm_nxos_ssh/nxos_ssh.py | NXOSSSHDriver.get_mac_address_table | 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 | python | 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 | [
"def",
"get_mac_address_table",
"(",
"self",
")",
":",
"# 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 | [
"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",
":"
] | 936d641c99e068817abf247e0e5571fc31b3a92a | https://github.com/napalm-automation/napalm-nxos/blob/936d641c99e068817abf247e0e5571fc31b3a92a/napalm_nxos_ssh/nxos_ssh.py#L1220-L1320 | train |
celiao/django-rest-authemail | authemail/views.py | Logout.get | 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) | python | 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) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"format",
"=",
"None",
")",
":",
"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. | [
"Remove",
"all",
"auth",
"tokens",
"owned",
"by",
"request",
".",
"user",
"."
] | 7295a4061a46b058595dae19b14c612f0eb0393a | https://github.com/celiao/django-rest-authemail/blob/7295a4061a46b058595dae19b14c612f0eb0393a/authemail/views.py#L130-L138 | train |
celiao/django-rest-authemail | authemail/wrapper.py | API._set_attrs_to_values | 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]) | python | 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]) | [
"def",
"_set_attrs_to_values",
"(",
"self",
",",
"response",
"=",
"{",
"}",
")",
":",
"for",
"key",
"in",
"response",
".",
"keys",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"response",
"[",
"key",
"]",
")"
] | Set attributes to dictionary values so can access via dot notation. | [
"Set",
"attributes",
"to",
"dictionary",
"values",
"so",
"can",
"access",
"via",
"dot",
"notation",
"."
] | 7295a4061a46b058595dae19b14c612f0eb0393a | https://github.com/celiao/django-rest-authemail/blob/7295a4061a46b058595dae19b14c612f0eb0393a/authemail/wrapper.py#L47-L52 | train |
acoomans/flask-autodoc | flask_autodoc/autodoc.py | Autodoc.add_custom_nl2br_filters | 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 | python | 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 | [
"def",
"add_custom_nl2br_filters",
"(",
"self",
",",
"app",
")",
":",
"_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> | [
"Add",
"a",
"custom",
"filter",
"nl2br",
"to",
"jinja2",
"Replaces",
"all",
"newline",
"to",
"<BR",
">"
] | 6c77c8935b71fbf3243b5e589c5c255d0299d853 | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/flask_autodoc/autodoc.py#L51-L62 | train |
acoomans/flask-autodoc | flask_autodoc/autodoc.py | Autodoc.doc | 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 | python | 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 | [
"def",
"doc",
"(",
"self",
",",
"groups",
"=",
"None",
",",
"set_location",
"=",
"True",
",",
"*",
"*",
"properties",
")",
":",
"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. | [
"Add",
"flask",
"route",
"to",
"autodoc",
"for",
"automatic",
"documentation"
] | 6c77c8935b71fbf3243b5e589c5c255d0299d853 | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/flask_autodoc/autodoc.py#L64-L111 | train |
acoomans/flask-autodoc | flask_autodoc/autodoc.py | Autodoc.generate | 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')) | python | 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')) | [
"def",
"generate",
"(",
"self",
",",
"groups",
"=",
"'all'",
",",
"sort",
"=",
"None",
")",
":",
"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. | [
"Return",
"a",
"list",
"of",
"dict",
"describing",
"the",
"routes",
"specified",
"by",
"the",
"doc",
"()",
"method"
] | 6c77c8935b71fbf3243b5e589c5c255d0299d853 | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/flask_autodoc/autodoc.py#L113-L166 | train |
acoomans/flask-autodoc | flask_autodoc/autodoc.py | Autodoc.html | 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) | python | 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) | [
"def",
"html",
"(",
"self",
",",
"groups",
"=",
"'all'",
",",
"template",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"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. | [
"Return",
"an",
"html",
"string",
"of",
"the",
"routes",
"specified",
"by",
"the",
"doc",
"()",
"method"
] | 6c77c8935b71fbf3243b5e589c5c255d0299d853 | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/flask_autodoc/autodoc.py#L168-L194 | train |
jim-easterbrook/Photini | src/photini/imagelist.py | ImageList.unsaved_files_dialog | 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 | python | 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 | [
"def",
"unsaved_files_dialog",
"(",
"self",
",",
"all_files",
"=",
"False",
",",
"with_cancel",
"=",
"True",
",",
"with_discard",
"=",
"True",
")",
":",
"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 | [
"Return",
"true",
"if",
"OK",
"to",
"continue",
"with",
"close",
"or",
"quit",
"or",
"whatever"
] | 06f1b1988db23a5cad98bbc6c16406a64a6c556d | https://github.com/jim-easterbrook/Photini/blob/06f1b1988db23a5cad98bbc6c16406a64a6c556d/src/photini/imagelist.py#L748-L772 | train |
jim-easterbrook/Photini | src/photini/metadata.py | DateTime.from_ISO_8601 | 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)) | python | 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)) | [
"def",
"from_ISO_8601",
"(",
"cls",
",",
"date_string",
",",
"time_string",
",",
"tz_string",
")",
":",
"# 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 | [
"Sufficiently",
"general",
"ISO",
"8601",
"parser",
"."
] | 06f1b1988db23a5cad98bbc6c16406a64a6c556d | https://github.com/jim-easterbrook/Photini/blob/06f1b1988db23a5cad98bbc6c16406a64a6c556d/src/photini/metadata.py#L412-L436 | train |
acoomans/flask-autodoc | examples/factory/blog/frontend.py | post_post | 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") | python | 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") | [
"def",
"post_post",
"(",
")",
":",
"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. | [
"Create",
"a",
"new",
"post",
".",
"Form",
"Data",
":",
"title",
"content",
"authorid",
"."
] | 6c77c8935b71fbf3243b5e589c5c255d0299d853 | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/examples/factory/blog/frontend.py#L59-L67 | train |
niklasb/webkit-server | webkit_server.py | SelectionMixin.xpath | 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] | python | 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] | [
"def",
"xpath",
"(",
"self",
",",
"xpath",
")",
":",
"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. | [
"Finds",
"another",
"node",
"by",
"XPath",
"originating",
"at",
"the",
"current",
"node",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L21-L25 | train |
niklasb/webkit-server | webkit_server.py | SelectionMixin.css | 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] | python | 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] | [
"def",
"css",
"(",
"self",
",",
"css",
")",
":",
"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. | [
"Finds",
"another",
"node",
"by",
"a",
"CSS",
"selector",
"relative",
"to",
"the",
"current",
"node",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L27-L31 | train |
niklasb/webkit-server | webkit_server.py | Node.get_bool_attr | 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) | python | 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) | [
"def",
"get_bool_attr",
"(",
"self",
",",
"name",
")",
":",
"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` | [
"Returns",
"the",
"value",
"of",
"a",
"boolean",
"HTML",
"attribute",
"like",
"checked",
"or",
"disabled"
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L68-L72 | train |
niklasb/webkit-server | webkit_server.py | Node.set_attr | def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value))) | python | def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value))) | [
"def",
"set_attr",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"exec_script",
"(",
"\"node.setAttribute(%s, %s)\"",
"%",
"(",
"repr",
"(",
"name",
")",
",",
"repr",
"(",
"value",
")",
")",
")"
] | Sets the value of an attribute. | [
"Sets",
"the",
"value",
"of",
"an",
"attribute",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L78-L80 | train |
niklasb/webkit-server | webkit_server.py | Node.value | 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") | python | 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") | [
"def",
"value",
"(",
"self",
")",
":",
"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. | [
"Returns",
"the",
"node",
"s",
"value",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L82-L89 | train |
niklasb/webkit-server | webkit_server.py | Client.set_header | def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value) | python | def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value) | [
"def",
"set_header",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"conn",
".",
"issue_command",
"(",
"\"Header\"",
",",
"_normalize_header",
"(",
"key",
")",
",",
"value",
")"
] | Sets a HTTP header for future requests. | [
"Sets",
"a",
"HTTP",
"header",
"for",
"future",
"requests",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L250-L252 | train |
niklasb/webkit-server | webkit_server.py | Client.headers | 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 | python | 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 | [
"def",
"headers",
"(",
"self",
")",
":",
"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`. | [
"Returns",
"a",
"list",
"of",
"the",
"last",
"HTTP",
"response",
"headers",
".",
"Header",
"keys",
"are",
"normalized",
"to",
"capitalized",
"form",
"as",
"in",
"User",
"-",
"Agent",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L262-L272 | train |
niklasb/webkit-server | webkit_server.py | Client.eval_script | 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] | python | 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] | [
"def",
"eval_script",
"(",
"self",
",",
"expr",
")",
":",
"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. | [
"Evaluates",
"a",
"piece",
"of",
"Javascript",
"in",
"the",
"context",
"of",
"the",
"current",
"page",
"and",
"returns",
"its",
"value",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L274-L278 | train |
niklasb/webkit-server | webkit_server.py | Client.render | 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) | python | 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) | [
"def",
"render",
"(",
"self",
",",
"path",
",",
"width",
"=",
"1024",
",",
"height",
"=",
"1024",
")",
":",
"self",
".",
"conn",
".",
"issue_command",
"(",
"\"Render\"",
",",
"path",
",",
"width",
",",
"height",
")"
] | Renders the current page to a PNG file (viewport size in pixels). | [
"Renders",
"the",
"current",
"page",
"to",
"a",
"PNG",
"file",
"(",
"viewport",
"size",
"in",
"pixels",
")",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L284-L286 | train |
niklasb/webkit-server | webkit_server.py | Client.cookies | 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()] | python | 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()] | [
"def",
"cookies",
"(",
"self",
")",
":",
"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. | [
"Returns",
"a",
"list",
"of",
"all",
"cookies",
"in",
"cookie",
"string",
"format",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L301-L305 | train |
niklasb/webkit-server | webkit_server.py | Client.set_attribute | 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) | python | 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) | [
"def",
"set_attribute",
"(",
"self",
",",
"attr",
",",
"value",
"=",
"True",
")",
":",
"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>`_. | [
"Sets",
"a",
"custom",
"attribute",
"for",
"our",
"Webkit",
"instance",
".",
"Possible",
"attributes",
"are",
":"
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L314-L339 | train |
niklasb/webkit-server | webkit_server.py | Client.set_html | 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) | python | 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) | [
"def",
"set_html",
"(",
"self",
",",
"html",
",",
"url",
"=",
"None",
")",
":",
"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. | [
"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",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L347-L354 | train |
niklasb/webkit-server | webkit_server.py | Client.set_proxy | 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) | python | 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) | [
"def",
"set_proxy",
"(",
"self",
",",
"host",
"=",
"\"localhost\"",
",",
"port",
"=",
"0",
",",
"user",
"=",
"\"\"",
",",
"password",
"=",
"\"\"",
")",
":",
"self",
".",
"conn",
".",
"issue_command",
"(",
"\"SetProxy\"",
",",
"host",
",",
"port",
",",
"user",
",",
"password",
")"
] | Sets a custom HTTP proxy to use for future requests. | [
"Sets",
"a",
"custom",
"HTTP",
"proxy",
"to",
"use",
"for",
"future",
"requests",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L356-L361 | train |
niklasb/webkit-server | webkit_server.py | Server.connect | 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 | python | 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 | [
"def",
"connect",
"(",
"self",
")",
":",
"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. | [
"Returns",
"a",
"new",
"socket",
"connection",
"to",
"this",
"server",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L437-L441 | train |
niklasb/webkit-server | webkit_server.py | SocketBuffer.read_line | 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 | python | 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 | [
"def",
"read_line",
"(",
"self",
")",
":",
"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. | [
"Consume",
"one",
"line",
"from",
"the",
"stream",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L475-L486 | train |
niklasb/webkit-server | webkit_server.py | SocketBuffer.read | 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 | python | 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 | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"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. | [
"Consume",
"n",
"characters",
"from",
"the",
"stream",
"."
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L488-L496 | train |
niklasb/webkit-server | webkit_server.py | ServerConnection.issue_command | 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() | python | 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() | [
"def",
"issue_command",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
")",
":",
"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 | [
"Sends",
"and",
"receives",
"a",
"message",
"to",
"/",
"from",
"the",
"server"
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L511-L520 | train |
niklasb/webkit-server | webkit_server.py | ServerConnection._read_response | 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 | python | 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 | [
"def",
"_read_response",
"(",
"self",
")",
":",
"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 | [
"Reads",
"a",
"complete",
"response",
"packet",
"from",
"the",
"server"
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L522-L532 | train |
niklasb/webkit-server | webkit_server.py | ServerConnection._read_message | 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") | python | 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") | [
"def",
"_read_message",
"(",
"self",
")",
":",
"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 | [
"Reads",
"a",
"single",
"size",
"-",
"annotated",
"message",
"from",
"the",
"server"
] | c9e3a8394b8c51000c35f8a56fb770580562b544 | https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L534-L537 | train |
hanneshapke/pyzillow | pyzillow/pyzillow.py | ZillowWrapper.get_deep_search_results | 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) | python | 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) | [
"def",
"get_deep_search_results",
"(",
"self",
",",
"address",
",",
"zipcode",
")",
":",
"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 | [
"GetDeepSearchResults",
"API"
] | 1de937669da4ec1eb779b4615f903d3e5bd0eca6 | https://github.com/hanneshapke/pyzillow/blob/1de937669da4ec1eb779b4615f903d3e5bd0eca6/pyzillow/pyzillow.py#L20-L31 | train |
hanneshapke/pyzillow | pyzillow/pyzillow.py | ZillowWrapper.get_updated_property_details | 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) | python | 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) | [
"def",
"get_updated_property_details",
"(",
"self",
",",
"zpid",
")",
":",
"url",
"=",
"'http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm'",
"params",
"=",
"{",
"'zpid'",
":",
"zpid",
",",
"'zws-id'",
":",
"self",
".",
"api_key",
"}",
"return",
"self",
".",
"get_data",
"(",
"url",
",",
"params",
")"
] | GetUpdatedPropertyDetails API | [
"GetUpdatedPropertyDetails",
"API"
] | 1de937669da4ec1eb779b4615f903d3e5bd0eca6 | https://github.com/hanneshapke/pyzillow/blob/1de937669da4ec1eb779b4615f903d3e5bd0eca6/pyzillow/pyzillow.py#L33-L43 | train |
kylefox/python-image-orientation-patch | img_rotate/__init__.py | fix_orientation | 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) | python | 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) | [
"def",
"fix_orientation",
"(",
"img",
",",
"save_over",
"=",
"False",
")",
":",
"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. | [
"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",
"."
] | 7941763d732a3bec0497991479be3c57aedd3415 | https://github.com/kylefox/python-image-orientation-patch/blob/7941763d732a3bec0497991479be3c57aedd3415/img_rotate/__init__.py#L25-L54 | train |
anfema/integrate | integrate/check.py | Check.log_error | 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
}) | python | 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
}) | [
"def",
"log_error",
"(",
"self",
",",
"error",
",",
"message",
",",
"detail",
"=",
"None",
",",
"strip",
"=",
"4",
")",
":",
"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 | [
"Add",
"an",
"error",
"message",
"and",
"optional",
"user",
"message",
"to",
"the",
"error",
"list"
] | e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7 | https://github.com/anfema/integrate/blob/e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7/integrate/check.py#L12-L29 | train |
anfema/integrate | integrate/check.py | Check.equal | 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 | python | 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 | [
"def",
"equal",
"(",
"self",
",",
"a",
",",
"b",
",",
"message",
"=",
"None",
")",
":",
"if",
"a",
"!=",
"b",
":",
"self",
".",
"log_error",
"(",
"\"{} != {}\"",
".",
"format",
"(",
"str",
"(",
"a",
")",
",",
"str",
"(",
"b",
")",
")",
",",
"message",
")",
"return",
"False",
"return",
"True"
] | Check if two values are equal | [
"Check",
"if",
"two",
"values",
"are",
"equal"
] | e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7 | https://github.com/anfema/integrate/blob/e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7/integrate/check.py#L35-L40 | train |
anfema/integrate | integrate/check.py | Check.is_not_none | 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 | python | 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 | [
"def",
"is_not_none",
"(",
"self",
",",
"a",
",",
"message",
"=",
"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 | [
"Check",
"if",
"a",
"value",
"is",
"not",
"None"
] | e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7 | https://github.com/anfema/integrate/blob/e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7/integrate/check.py#L56-L61 | train |
anfema/integrate | integrate/check.py | Check.raises | 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) | python | 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) | [
"def",
"raises",
"(",
"self",
",",
"exception_type",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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 | [
"Check",
"if",
"a",
"function",
"raises",
"a",
"specified",
"exception",
"type",
"*",
"args",
"and",
"**",
"kwargs",
"are",
"forwarded",
"to",
"the",
"function"
] | e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7 | https://github.com/anfema/integrate/blob/e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7/integrate/check.py#L82-L99 | train |
anfema/integrate | integrate/check.py | Check.does_not_raise | 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) | python | 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) | [
"def",
"does_not_raise",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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 | [
"Check",
"if",
"a",
"function",
"does",
"not",
"raise",
"an",
"exception",
"*",
"args",
"and",
"**",
"kwargs",
"are",
"forwarded",
"to",
"the",
"function"
] | e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7 | https://github.com/anfema/integrate/blob/e9d3bb8f0613e82184735ee67a42ea01b1a9b1b7/integrate/check.py#L101-L112 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | calculate_color_temperature | 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) | python | 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) | [
"def",
"calculate_color_temperature",
"(",
"r",
",",
"g",
",",
"b",
")",
":",
"# 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. | [
"Converts",
"the",
"raw",
"R",
"/",
"G",
"/",
"B",
"values",
"to",
"color",
"temperature",
"in",
"degrees",
"Kelvin",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L102-L124 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | calculate_lux | 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) | python | 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) | [
"def",
"calculate_lux",
"(",
"r",
",",
"g",
",",
"b",
")",
":",
"illuminance",
"=",
"(",
"-",
"0.32466",
"*",
"r",
")",
"+",
"(",
"1.57837",
"*",
"g",
")",
"+",
"(",
"-",
"0.73191",
"*",
"b",
")",
"return",
"int",
"(",
"illuminance",
")"
] | Converts the raw R/G/B values to luminosity in lux. | [
"Converts",
"the",
"raw",
"R",
"/",
"G",
"/",
"B",
"values",
"to",
"luminosity",
"in",
"lux",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L126-L129 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725._write8 | def _write8(self, reg, value):
"""Write a 8-bit value to a register."""
self._device.write8(TCS34725_COMMAND_BIT | reg, value) | python | def _write8(self, reg, value):
"""Write a 8-bit value to a register."""
self._device.write8(TCS34725_COMMAND_BIT | reg, value) | [
"def",
"_write8",
"(",
"self",
",",
"reg",
",",
"value",
")",
":",
"self",
".",
"_device",
".",
"write8",
"(",
"TCS34725_COMMAND_BIT",
"|",
"reg",
",",
"value",
")"
] | Write a 8-bit value to a register. | [
"Write",
"a",
"8",
"-",
"bit",
"value",
"to",
"a",
"register",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L161-L163 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.enable | 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)) | python | 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)) | [
"def",
"enable",
"(",
"self",
")",
":",
"# 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. | [
"Enable",
"the",
"chip",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L165-L170 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.disable | 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) | python | 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) | [
"def",
"disable",
"(",
"self",
")",
":",
"# 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). | [
"Disable",
"the",
"chip",
"(",
"power",
"down",
")",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L172-L177 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.set_integration_time | 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) | python | 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) | [
"def",
"set_integration_time",
"(",
"self",
",",
"integration_time",
")",
":",
"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 | [
"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"
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L179-L190 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.get_raw_data | 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) | python | 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) | [
"def",
"get_raw_data",
"(",
"self",
")",
":",
"# 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). | [
"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",
")",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L214-L226 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.set_interrupt | 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) | python | 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) | [
"def",
"set_interrupt",
"(",
"self",
",",
"enabled",
")",
":",
"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. | [
"Enable",
"or",
"disable",
"interrupts",
"by",
"setting",
"enabled",
"to",
"True",
"or",
"False",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L228-L236 | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | TCS34725.set_interrupt_limits | 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) | python | 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) | [
"def",
"set_interrupt_limits",
"(",
"self",
",",
"low",
",",
"high",
")",
":",
"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. | [
"Set",
"the",
"interrupt",
"limits",
"to",
"provied",
"unsigned",
"16",
"-",
"bit",
"threshold",
"values",
"."
] | 996396cd095522d788b7b15d20fd44e566c8464e | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L242-L248 | train |
latture/json2table | json2table/json2table.py | convert | 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) | python | 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) | [
"def",
"convert",
"(",
"json_input",
",",
"build_direction",
"=",
"\"LEFT_TO_RIGHT\"",
",",
"table_attributes",
"=",
"None",
")",
":",
"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>" | [
"Converts",
"JSON",
"to",
"HTML",
"Table",
"format",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L12-L48 | train |
latture/json2table | json2table/json2table.py | JsonConverter.convert | 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 | python | 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 | [
"def",
"convert",
"(",
"self",
",",
"json_input",
")",
":",
"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. | [
"Converts",
"JSON",
"to",
"HTML",
"Table",
"format",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L73-L109 | train |
latture/json2table | json2table/json2table.py | JsonConverter._dict_to_html_attributes | 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())) | python | 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())) | [
"def",
"_dict_to_html_attributes",
"(",
"d",
")",
":",
"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. | [
"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",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L144-L164 | train |
latture/json2table | json2table/json2table.py | JsonConverter._list_of_dicts_to_column_headers | 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 | python | 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 | [
"def",
"_list_of_dicts_to_column_headers",
"(",
"list_of_dicts",
")",
":",
"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. | [
"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",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L167-L190 | train |
latture/json2table | json2table/json2table.py | JsonConverter._markup | 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) | python | 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) | [
"def",
"_markup",
"(",
"self",
",",
"entry",
")",
":",
"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. | [
"Recursively",
"generates",
"HTML",
"for",
"the",
"current",
"entry",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L192-L218 | train |
latture/json2table | json2table/json2table.py | JsonConverter._maybe_club | 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) | python | 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) | [
"def",
"_maybe_club",
"(",
"self",
",",
"list_of_dicts",
")",
":",
"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``. | [
"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",
"."
] | 8bd1363f54ee4fd608ffb7677761526184a9da83 | https://github.com/latture/json2table/blob/8bd1363f54ee4fd608ffb7677761526184a9da83/json2table/json2table.py#L220-L272 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/tpl.py | TplApi.update_voice_notify | 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) | python | 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) | [
"def",
"update_voice_notify",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"TPL_ID",
",",
"TPL_CONTENT",
"]",
")",
":",
"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 | [
"修改语音通知模版",
"注意:模板成功修改之后需要重新审核才能使用!同时提醒您如果修改了变量,务必重新测试,以免替换出错!",
"参数:",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"tpl_id",
"Long",
"是",
"模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板",
"9527",
"tpl_content",
"String",
"是",
"模板id,64位长整形。指定id时返回id对应的模板。未指定时返回所有模板模板内容",
"您的验证码是#code#",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/tpl.py#L144-L163 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/model/result.py | Result.code | 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 | python | 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 | [
"def",
"code",
"(",
"self",
",",
"code",
"=",
"None",
",",
"ret_r",
"=",
"False",
")",
":",
"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 | [
"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"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/model/result.py#L33-L44 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/model/result.py | Result.msg | def msg(self, msg=None, ret_r=False):
'''code's message'''
if msg or ret_r:
self._msg = msg
return self
return self._msg | python | def msg(self, msg=None, ret_r=False):
'''code's message'''
if msg or ret_r:
self._msg = msg
return self
return self._msg | [
"def",
"msg",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"ret_r",
"=",
"False",
")",
":",
"if",
"msg",
"or",
"ret_r",
":",
"self",
".",
"_msg",
"=",
"msg",
"return",
"self",
"return",
"self",
".",
"_msg"
] | code's message | [
"code",
"s",
"message"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/model/result.py#L46-L51 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/model/result.py | Result.detail | def detail(self, detail=None, ret_r=False):
'''code's detail'''
if detail or ret_r:
self._detail = detail
return self
return self._detail | python | def detail(self, detail=None, ret_r=False):
'''code's detail'''
if detail or ret_r:
self._detail = detail
return self
return self._detail | [
"def",
"detail",
"(",
"self",
",",
"detail",
"=",
"None",
",",
"ret_r",
"=",
"False",
")",
":",
"if",
"detail",
"or",
"ret_r",
":",
"self",
".",
"_detail",
"=",
"detail",
"return",
"self",
"return",
"self",
".",
"_detail"
] | code's detail | [
"code",
"s",
"detail"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/model/result.py#L53-L58 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/model/result.py | Result.data | def data(self, data=None, ret_r=False):
'''response data'''
if data or ret_r:
self._data = data
return self
return self._data | python | def data(self, data=None, ret_r=False):
'''response data'''
if data or ret_r:
self._data = data
return self
return self._data | [
"def",
"data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"ret_r",
"=",
"False",
")",
":",
"if",
"data",
"or",
"ret_r",
":",
"self",
".",
"_data",
"=",
"data",
"return",
"self",
"return",
"self",
".",
"_data"
] | response data | [
"response",
"data"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/model/result.py#L60-L65 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/user.py | UserApi.get | 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) | python | 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) | [
"def",
"get",
"(",
"self",
",",
"param",
"=",
"None",
",",
"must",
"=",
"[",
"APIKEY",
"]",
")",
":",
"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 | [
"查账户信息",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"Args",
":",
"param",
":",
"(",
"Optional",
")",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/user.py#L19-L35 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/ypapi.py | YunpianApi._init | 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] | python | 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] | [
"def",
"_init",
"(",
"self",
",",
"clnt",
")",
":",
"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 | [
"initialize",
"api",
"by",
"YunpianClient"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/ypapi.py#L94-L101 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/ypapi.py | YunpianApi.name | def name(self, name=None):
'''api name, default is module.__name__'''
if name:
self._name = name
return self
return self._name | python | def name(self, name=None):
'''api name, default is module.__name__'''
if name:
self._name = name
return self
return self._name | [
"def",
"name",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"self",
".",
"_name",
"=",
"name",
"return",
"self",
"return",
"self",
".",
"_name"
] | api name, default is module.__name__ | [
"api",
"name",
"default",
"is",
"module",
".",
"__name__"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/ypapi.py#L139-L144 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/ypapi.py | YunpianApi.post | 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) | python | 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) | [
"def",
"post",
"(",
"self",
",",
"param",
",",
"h",
",",
"r",
")",
":",
"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 | [
"Args",
":",
"param",
":",
"request",
"parameters",
"h",
":",
"ResultHandler",
"r",
":",
"YunpianApiResult"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/ypapi.py#L150-L162 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/ypapi.py | YunpianApi.verify_param | 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 | python | 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 | [
"def",
"verify_param",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"]",
",",
"r",
"=",
"None",
")",
":",
"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 | [
"return",
"Code",
".",
"ARGUMENT_MISSING",
"if",
"every",
"key",
"in",
"must",
"not",
"found",
"in",
"param"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/ypapi.py#L180-L191 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | _YunpianConf.custom_conf | def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self | python | def custom_conf(self, conf):
'''custom apikey and http parameters'''
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self | [
"def",
"custom_conf",
"(",
"self",
",",
"conf",
")",
":",
"if",
"conf",
":",
"for",
"(",
"key",
",",
"val",
")",
"in",
"conf",
".",
"items",
"(",
")",
":",
"self",
".",
"__conf",
"[",
"key",
"]",
"=",
"val",
"return",
"self"
] | custom apikey and http parameters | [
"custom",
"apikey",
"and",
"http",
"parameters"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L59-L64 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | _YunpianConf.conf | def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) | python | def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) | [
"def",
"conf",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"__conf",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"__conf",
"else",
"_YunpianConf",
".",
"YP_CONF",
".",
"get",
"(",
"key",
")"
] | get config | [
"get",
"config"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L73-L75 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | _ApiFactory.api | 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 | python | 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 | [
"def",
"api",
"(",
"self",
",",
"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 | [
"return",
"special",
"API",
"by",
"package",
"s",
"name"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L85-L105 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | YunpianClient.conf | 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 | python | 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 | [
"def",
"conf",
"(",
"self",
",",
"key",
"=",
"None",
",",
"defval",
"=",
"None",
")",
":",
"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 | [
"return",
"YunpianConf",
"if",
"key",
"=",
"None",
"else",
"return",
"value",
"in",
"YunpianConf"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L175-L180 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | YunpianClient.post | 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) | python | 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) | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"data",
",",
"charset",
"=",
"CHARSET_UTF8",
",",
"headers",
"=",
"{",
"}",
")",
":",
"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 | [
"response",
"json",
"text"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L185-L193 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/ypclient.py | YunpianClient.urlEncodeAndJoin | 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)]) | python | 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)]) | [
"def",
"urlEncodeAndJoin",
"(",
"self",
",",
"seq",
",",
"sepr",
"=",
"','",
")",
":",
"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 | [
"sepr",
".",
"join",
"(",
"urlencode",
"(",
"seq",
"))",
"Args",
":",
"seq",
":",
"string",
"list",
"to",
"be",
"urlencoded",
"sepr",
":",
"join",
"seq",
"with",
"sepr",
"Returns",
":",
"str"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L195-L208 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/voice.py | VoiceApi.send | 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) | python | 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) | [
"def",
"send",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"MOBILE",
",",
"CODE",
"]",
")",
":",
"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 | [
"发语音验证码"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/voice.py#L20-L42 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.single_send | 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) | python | 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) | [
"def",
"single_send",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"MOBILE",
",",
"TEXT",
"]",
")",
":",
"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 | [
"单条发送",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"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"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L50-L77 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.pull_reply | 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) | python | 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) | [
"def",
"pull_reply",
"(",
"self",
",",
"param",
"=",
"None",
",",
"must",
"=",
"[",
"APIKEY",
"]",
")",
":",
"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 | [
"获取回复短信",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"page_size",
"Integer",
"否",
"每页个数,最大100个,默认20个",
"20",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L157-L174 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.get_reply | 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) | python | 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) | [
"def",
"get_reply",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"START_TIME",
",",
"END_TIME",
",",
"PAGE_NUM",
",",
"PAGE_SIZE",
"]",
")",
":",
"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 | [
"查回复的短信",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"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"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L177-L199 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.get_record | 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) | python | 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) | [
"def",
"get_record",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"START_TIME",
",",
"END_TIME",
"]",
")",
":",
"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 | [
"查短信发送记录",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"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"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L220-L240 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.count | def count(self, param, must=[APIKEY, START_TIME, END_TIME]):
'''统计短信条数
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
mobile String 否 需要查询的手机号 15205201314
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: int(rsp[TOTAL]) if TOTAL in rsp else 0)
return self.path('count.json').post(param, h, r) | python | def count(self, param, must=[APIKEY, START_TIME, END_TIME]):
'''统计短信条数
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信发送开始时间 2013-08-11 00:00:00
end_time String 是 短信发送结束时间 2013-08-12 00:00:00
mobile String 否 需要查询的手机号 15205201314
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: int(rsp[TOTAL]) if TOTAL in rsp else 0)
return self.path('count.json').post(param, h, r) | [
"def",
"count",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"START_TIME",
",",
"END_TIME",
"]",
")",
":",
"r",
"=",
"self",
".",
"verify_param",
"(",
"param",
",",
"must",
")",
"if",
"not",
"r",
".",
"is_succ",
"(",
")",
":",
"return",
"r",
"h",
"=",
"CommonResultHandler",
"(",
"lambda",
"rsp",
":",
"int",
"(",
"rsp",
"[",
"TOTAL",
"]",
")",
"if",
"TOTAL",
"in",
"rsp",
"else",
"0",
")",
"return",
"self",
".",
"path",
"(",
"'count.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
mobile String 否 需要查询的手机号 15205201314
page_num Integer 否 页码,默认值为1 1
page_size Integer 否 每页个数,最大100个 20
Args:
param:
Results:
Result | [
"统计短信条数",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"start_time",
"String",
"是",
"短信发送开始时间",
"2013",
"-",
"08",
"-",
"11",
"00",
":",
"00",
":",
"00",
"end_time",
"String",
"是",
"短信发送结束时间",
"2013",
"-",
"08",
"-",
"12",
"00",
":",
"00",
":",
"00",
"mobile",
"String",
"否",
"需要查询的手机号",
"15205201314",
"page_num",
"Integer",
"否",
"页码,默认值为1",
"1",
"page_size",
"Integer",
"否",
"每页个数,最大100个",
"20",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L242-L262 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.tpl_send | def tpl_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板发送 only v1 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
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)}[self.version()])
return self.path('tpl_send.json').post(param, h, r) | python | def tpl_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板发送 only v1 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
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)}[self.version()])
return self.path('tpl_send.json').post(param, h, r) | [
"def",
"tpl_send",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"MOBILE",
",",
"TPL_ID",
",",
"TPL_VALUE",
"]",
")",
":",
"r",
"=",
"self",
".",
"verify_param",
"(",
"param",
",",
"must",
")",
"if",
"not",
"r",
".",
"is_succ",
"(",
")",
":",
"return",
"r",
"h",
"=",
"CommonResultHandler",
"(",
"lambda",
"rsp",
":",
"{",
"VERSION_V1",
":",
"rsp",
".",
"get",
"(",
"RESULT",
")",
"}",
"[",
"self",
".",
"version",
"(",
")",
"]",
")",
"return",
"self",
".",
"path",
"(",
"'tpl_send.json'",
")",
".",
"post",
"(",
"param",
",",
"h",
",",
"r",
")"
] | 指定模板发送 only v1 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
Args:
param:
Results:
Result | [
"指定模板发送",
"only",
"v1",
"deprecated",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"mobile",
"String",
"是",
"接收的手机号",
"15205201314",
"tpl_id",
"Long",
"是",
"模板id",
"1",
"tpl_value",
"String",
"是",
"变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。",
"注:变量名和变量值都不能为空",
"模板:",
"【#company#】您的验证码是#code#。",
"最终发送结果:",
"【云片网】您的验证码是1234。",
"tplvalue",
"=",
"urlencode",
"(",
"#code#",
")",
"+",
"=",
"+",
"urlencode",
"(",
"1234",
")",
"+",
"&",
";",
"+",
"urlencode",
"(",
"#company#",
")",
"+",
"=",
"+",
"urlencode",
"(",
"云片网",
")",
";",
"若您直接发送报文请求则使用下面这种形式",
"tplvalue",
"=",
"urlencode",
"(",
"urlencode",
"(",
"#code#",
")",
"+",
"=",
"+",
"urlencode",
"(",
"1234",
")",
"+",
"&",
";",
"+",
"urlencode",
"(",
"#company#",
")",
"+",
"=",
"+",
"urlencode",
"(",
"云片网",
"))",
";",
"extend",
"String",
"否",
"扩展号。默认不开放,如有需要请联系客服申请",
"001",
"uid",
"String",
"否",
"用户自定义唯一id。最大长度不超过256的字符串。",
"默认不开放,如有需要请联系客服申请",
"10001",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L264-L289 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/sms.py | SmsApi.tpl_single_send | def tpl_single_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板单发 only v2 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
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('tpl_single_send.json').post(param, h, r) | python | def tpl_single_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]):
'''指定模板单发 only v2 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
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('tpl_single_send.json').post(param, h, r) | [
"def",
"tpl_single_send",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"MOBILE",
",",
"TPL_ID",
",",
"TPL_VALUE",
"]",
")",
":",
"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",
"(",
"'tpl_single_send.json'",
")",
".",
"post",
"(",
"param",
",",
"h",
",",
"r",
")"
] | 指定模板单发 only v2 deprecated
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是
接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见:
https://en.wikipedia.org/wiki/E.164) 15205201314
tpl_id Long 是 模板id 1
tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。
注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#code#。 最终发送结果: 【云片网】您的验证码是1234。
tplvalue=urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"); 若您直接发送报文请求则使用下面这种形式
tplvalue=urlencode(urlencode("#code#") + "=" + urlencode("1234") + "&" +
urlencode("#company#") + "=" + urlencode("云片网"));
extend String 否 扩展号。默认不开放,如有需要请联系客服申请 001
uid String 否 用户自定义唯一id。最大长度不超过256的字符串。 默认不开放,如有需要请联系客服申请 10001
Args:
param:
Results:
Result | [
"指定模板单发",
"only",
"v2",
"deprecated"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/sms.py#L291-L318 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/flow.py | FlowApi.get_package | def get_package(self, param=None, must=[APIKEY]):
'''查询流量包
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000
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[FLOW_PACKAGE] if FLOW_PACKAGE in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('get_package.json').post(param, h, r) | python | def get_package(self, param=None, must=[APIKEY]):
'''查询流量包
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000
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[FLOW_PACKAGE] if FLOW_PACKAGE in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('get_package.json').post(param, h, r) | [
"def",
"get_package",
"(",
"self",
",",
"param",
"=",
"None",
",",
"must",
"=",
"[",
"APIKEY",
"]",
")",
":",
"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",
"[",
"FLOW_PACKAGE",
"]",
"if",
"FLOW_PACKAGE",
"in",
"rsp",
"else",
"None",
",",
"VERSION_V2",
":",
"rsp",
"}",
"[",
"self",
".",
"version",
"(",
")",
"]",
")",
"return",
"self",
".",
"path",
"(",
"'get_package.json'",
")",
".",
"post",
"(",
"param",
",",
"h",
",",
"r",
")"
] | 查询流量包
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000
Args:
param:
Results:
Result | [
"查询流量包",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"carrier",
"String",
"否",
"运营商ID",
"传入该参数则获取指定运营商的流量包,",
"否则获取所有运营商的流量包",
"移动:10086",
"联通:10010",
"电信:10000",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L19-L36 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/flow.py | FlowApi.recharge | def recharge(self, param, must=[APIKEY, MOBILE, SN]):
'''充值流量
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号(仅支持大陆号码) 15205201314
sn String 是 流量包的唯一ID 点击查看 1008601
callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[RESULT] if RESULT in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('recharge.json').post(param, h, r) | python | def recharge(self, param, must=[APIKEY, MOBILE, SN]):
'''充值流量
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号(仅支持大陆号码) 15205201314
sn String 是 流量包的唯一ID 点击查看 1008601
callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
Args:
param:
Results:
Result
'''
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[RESULT] if RESULT in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('recharge.json').post(param, h, r) | [
"def",
"recharge",
"(",
"self",
",",
"param",
",",
"must",
"=",
"[",
"APIKEY",
",",
"MOBILE",
",",
"SN",
"]",
")",
":",
"r",
"=",
"self",
".",
"verify_param",
"(",
"param",
",",
"must",
")",
"if",
"not",
"r",
".",
"is_succ",
"(",
")",
":",
"return",
"r",
"h",
"=",
"CommonResultHandler",
"(",
"lambda",
"rsp",
":",
"{",
"VERSION_V1",
":",
"rsp",
"[",
"RESULT",
"]",
"if",
"RESULT",
"in",
"rsp",
"else",
"None",
",",
"VERSION_V2",
":",
"rsp",
"}",
"[",
"self",
".",
"version",
"(",
")",
"]",
")",
"return",
"self",
".",
"path",
"(",
"'recharge.json'",
")",
".",
"post",
"(",
"param",
",",
"h",
",",
"r",
")"
] | 充值流量
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
mobile String 是 接收的手机号(仅支持大陆号码) 15205201314
sn String 是 流量包的唯一ID 点击查看 1008601
callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address
encrypt String 否 加密方式 使用加密 tea (不再使用)
_sign String 否 签名字段 参考使用加密 393d079e0a00912335adfe46f4a2e10f (不再使用)
Args:
param:
Results:
Result | [
"充值流量",
"参数名",
"类型",
"是否必须",
"描述",
"示例",
"apikey",
"String",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"mobile",
"String",
"是",
"接收的手机号(仅支持大陆号码)",
"15205201314",
"sn",
"String",
"是",
"流量包的唯一ID",
"点击查看",
"1008601",
"callback_url",
"String",
"否",
"本条流量充值的状态报告推送地址",
"http",
":",
"//",
"your_receive_url_address",
"encrypt",
"String",
"否",
"加密方式",
"使用加密",
"tea",
"(",
"不再使用",
")",
"_sign",
"String",
"否",
"签名字段",
"参考使用加密",
"393d079e0a00912335adfe46f4a2e10f",
"(",
"不再使用",
")",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L38-L58 | train |
yunpian/yunpian-python-sdk | yunpian_python_sdk/api/flow.py | FlowApi.pull_status | def pull_status(self, param=None, must=[APIKEY]):
'''获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大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[FLOW_STATUS] if FLOW_STATUS in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('pull_status.json').post(param, h, r) | python | def pull_status(self, param=None, must=[APIKEY]):
'''获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大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[FLOW_STATUS] if FLOW_STATUS in rsp else None, VERSION_V2:rsp}[self.version()])
return self.path('pull_status.json').post(param, h, r) | [
"def",
"pull_status",
"(",
"self",
",",
"param",
"=",
"None",
",",
"must",
"=",
"[",
"APIKEY",
"]",
")",
":",
"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",
"[",
"FLOW_STATUS",
"]",
"if",
"FLOW_STATUS",
"in",
"rsp",
"else",
"None",
",",
"VERSION_V2",
":",
"rsp",
"}",
"[",
"self",
".",
"version",
"(",
")",
"]",
")",
"return",
"self",
".",
"path",
"(",
"'pull_status.json'",
")",
".",
"post",
"(",
"param",
",",
"h",
",",
"r",
")"
] | 获取状态报告
参数名 是否必须 描述 示例
apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
page_size 否 每页个数,最大100个,默认20个 20
Args:
param:
Results:
Result | [
"获取状态报告",
"参数名",
"是否必须",
"描述",
"示例",
"apikey",
"是",
"用户唯一标识",
"9b11127a9701975c734b8aee81ee3526",
"page_size",
"否",
"每页个数,最大100个,默认20个",
"20",
"Args",
":",
"param",
":",
"Results",
":",
"Result"
] | 405a1196ec83fdf29ff454f74ef036974be11970 | https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/api/flow.py#L60-L77 | train |
doconix/django-mako-plus | django_mako_plus/command.py | run_command | def run_command(*args, raise_exception=True, cwd=None):
'''
Runs a command, piping all output to the DMP log.
The args should be separate arguments so paths and subcommands can have spaces in them:
ret = run_command('ls', '-l', '/Users/me/My Documents')
print(ret.code)
print(ret.stdout)
print(ret.stderr)
On Windows, the PATH is not followed. This can be overcome with:
import shutil
run_command(shutil.which('program'), '-l', '/Users/me/My Documents')
'''
args = [ str(a) for a in args ]
log.info('running %s', ' '.join(args))
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd)
stdout, stderr = p.communicate()
returninfo = ReturnInfo(p.returncode, stdout.decode('utf8'), stderr.decode('utf8'))
if stdout:
log.info('%s', returninfo.stdout)
if raise_exception and returninfo.code != 0:
raise CommandError(' '.join(args), returninfo)
return returninfo | python | def run_command(*args, raise_exception=True, cwd=None):
'''
Runs a command, piping all output to the DMP log.
The args should be separate arguments so paths and subcommands can have spaces in them:
ret = run_command('ls', '-l', '/Users/me/My Documents')
print(ret.code)
print(ret.stdout)
print(ret.stderr)
On Windows, the PATH is not followed. This can be overcome with:
import shutil
run_command(shutil.which('program'), '-l', '/Users/me/My Documents')
'''
args = [ str(a) for a in args ]
log.info('running %s', ' '.join(args))
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd)
stdout, stderr = p.communicate()
returninfo = ReturnInfo(p.returncode, stdout.decode('utf8'), stderr.decode('utf8'))
if stdout:
log.info('%s', returninfo.stdout)
if raise_exception and returninfo.code != 0:
raise CommandError(' '.join(args), returninfo)
return returninfo | [
"def",
"run_command",
"(",
"*",
"args",
",",
"raise_exception",
"=",
"True",
",",
"cwd",
"=",
"None",
")",
":",
"args",
"=",
"[",
"str",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"log",
".",
"info",
"(",
"'running %s'",
",",
"' '",
".",
"join",
"(",
"args",
")",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"cwd",
"=",
"cwd",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"returninfo",
"=",
"ReturnInfo",
"(",
"p",
".",
"returncode",
",",
"stdout",
".",
"decode",
"(",
"'utf8'",
")",
",",
"stderr",
".",
"decode",
"(",
"'utf8'",
")",
")",
"if",
"stdout",
":",
"log",
".",
"info",
"(",
"'%s'",
",",
"returninfo",
".",
"stdout",
")",
"if",
"raise_exception",
"and",
"returninfo",
".",
"code",
"!=",
"0",
":",
"raise",
"CommandError",
"(",
"' '",
".",
"join",
"(",
"args",
")",
",",
"returninfo",
")",
"return",
"returninfo"
] | Runs a command, piping all output to the DMP log.
The args should be separate arguments so paths and subcommands can have spaces in them:
ret = run_command('ls', '-l', '/Users/me/My Documents')
print(ret.code)
print(ret.stdout)
print(ret.stderr)
On Windows, the PATH is not followed. This can be overcome with:
import shutil
run_command(shutil.which('program'), '-l', '/Users/me/My Documents') | [
"Runs",
"a",
"command",
"piping",
"all",
"output",
"to",
"the",
"DMP",
"log",
".",
"The",
"args",
"should",
"be",
"separate",
"arguments",
"so",
"paths",
"and",
"subcommands",
"can",
"have",
"spaces",
"in",
"them",
":"
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/command.py#L13-L37 | train |
doconix/django-mako-plus | django_mako_plus/template/loader.py | MakoTemplateLoader.get_template | def get_template(self, template, def_name=None):
'''Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
If def_name is provided, template rendering will be limited to the named def/block (see Mako docs).
This method corresponds to the Django templating system API.
A Django exception is raised if the template is not found or cannot compile.
'''
try:
# wrap the mako template in an adapter that gives the Django template API
return MakoTemplateAdapter(self.get_mako_template(template), def_name)
except (TopLevelLookupException, TemplateLookupException) as e: # Mako exception raised
tdne = TemplateDoesNotExist('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
if settings.DEBUG:
tdne.template_debug = get_template_debug(template, e)
raise tdne from e
except (CompileException, SyntaxException) as e: # Mako exception raised
tse = TemplateSyntaxError('Template "%s" raised an error: %s' % (template, e))
if settings.DEBUG:
tse.template_debug = get_template_debug(template, e)
raise tse from e | python | def get_template(self, template, def_name=None):
'''Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
If def_name is provided, template rendering will be limited to the named def/block (see Mako docs).
This method corresponds to the Django templating system API.
A Django exception is raised if the template is not found or cannot compile.
'''
try:
# wrap the mako template in an adapter that gives the Django template API
return MakoTemplateAdapter(self.get_mako_template(template), def_name)
except (TopLevelLookupException, TemplateLookupException) as e: # Mako exception raised
tdne = TemplateDoesNotExist('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
if settings.DEBUG:
tdne.template_debug = get_template_debug(template, e)
raise tdne from e
except (CompileException, SyntaxException) as e: # Mako exception raised
tse = TemplateSyntaxError('Template "%s" raised an error: %s' % (template, e))
if settings.DEBUG:
tse.template_debug = get_template_debug(template, e)
raise tse from e | [
"def",
"get_template",
"(",
"self",
",",
"template",
",",
"def_name",
"=",
"None",
")",
":",
"try",
":",
"# wrap the mako template in an adapter that gives the Django template API",
"return",
"MakoTemplateAdapter",
"(",
"self",
".",
"get_mako_template",
"(",
"template",
")",
",",
"def_name",
")",
"except",
"(",
"TopLevelLookupException",
",",
"TemplateLookupException",
")",
"as",
"e",
":",
"# Mako exception raised",
"tdne",
"=",
"TemplateDoesNotExist",
"(",
"'Template \"%s\" not found in search path: %s.'",
"%",
"(",
"template",
",",
"self",
".",
"template_search_dirs",
")",
")",
"if",
"settings",
".",
"DEBUG",
":",
"tdne",
".",
"template_debug",
"=",
"get_template_debug",
"(",
"template",
",",
"e",
")",
"raise",
"tdne",
"from",
"e",
"except",
"(",
"CompileException",
",",
"SyntaxException",
")",
"as",
"e",
":",
"# Mako exception raised",
"tse",
"=",
"TemplateSyntaxError",
"(",
"'Template \"%s\" raised an error: %s'",
"%",
"(",
"template",
",",
"e",
")",
")",
"if",
"settings",
".",
"DEBUG",
":",
"tse",
".",
"template_debug",
"=",
"get_template_debug",
"(",
"template",
",",
"e",
")",
"raise",
"tse",
"from",
"e"
] | Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir
settings in this object. This method still uses the corresponding Mako template and engine, but it
gives a Django API wrapper around it so you can use it the same as any Django template.
If def_name is provided, template rendering will be limited to the named def/block (see Mako docs).
This method corresponds to the Django templating system API.
A Django exception is raised if the template is not found or cannot compile. | [
"Retrieve",
"a",
"*",
"Django",
"*",
"API",
"template",
"object",
"for",
"the",
"given",
"template",
"name",
"using",
"the",
"app_path",
"and",
"template_subdir",
"settings",
"in",
"this",
"object",
".",
"This",
"method",
"still",
"uses",
"the",
"corresponding",
"Mako",
"template",
"and",
"engine",
"but",
"it",
"gives",
"a",
"Django",
"API",
"wrapper",
"around",
"it",
"so",
"you",
"can",
"use",
"it",
"the",
"same",
"as",
"any",
"Django",
"template",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/loader.py#L71-L95 | train |
doconix/django-mako-plus | django_mako_plus/template/loader.py | MakoTemplateLoader.get_mako_template | def get_mako_template(self, template, force=False):
'''Retrieve the real *Mako* template object for the given template name without any wrapper,
using the app_path and template_subdir settings in this object.
This method is an alternative to get_template(). Use it when you need the actual Mako template object.
This method raises a Mako exception if the template is not found or cannot compile.
If force is True, an empty Mako template will be created when the file does not exist.
This option is used by the providers part of DMP and normally be left False.
'''
if template is None:
raise TemplateLookupException('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
# get the template
try:
template_obj = self.tlookup.get_template(template)
except TemplateLookupException:
if not force:
raise
template_obj = Template('', filename=os.path.join(self.template_dir, template))
# get the template
return template_obj | python | def get_mako_template(self, template, force=False):
'''Retrieve the real *Mako* template object for the given template name without any wrapper,
using the app_path and template_subdir settings in this object.
This method is an alternative to get_template(). Use it when you need the actual Mako template object.
This method raises a Mako exception if the template is not found or cannot compile.
If force is True, an empty Mako template will be created when the file does not exist.
This option is used by the providers part of DMP and normally be left False.
'''
if template is None:
raise TemplateLookupException('Template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
# get the template
try:
template_obj = self.tlookup.get_template(template)
except TemplateLookupException:
if not force:
raise
template_obj = Template('', filename=os.path.join(self.template_dir, template))
# get the template
return template_obj | [
"def",
"get_mako_template",
"(",
"self",
",",
"template",
",",
"force",
"=",
"False",
")",
":",
"if",
"template",
"is",
"None",
":",
"raise",
"TemplateLookupException",
"(",
"'Template \"%s\" not found in search path: %s.'",
"%",
"(",
"template",
",",
"self",
".",
"template_search_dirs",
")",
")",
"# get the template",
"try",
":",
"template_obj",
"=",
"self",
".",
"tlookup",
".",
"get_template",
"(",
"template",
")",
"except",
"TemplateLookupException",
":",
"if",
"not",
"force",
":",
"raise",
"template_obj",
"=",
"Template",
"(",
"''",
",",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"template_dir",
",",
"template",
")",
")",
"# get the template",
"return",
"template_obj"
] | Retrieve the real *Mako* template object for the given template name without any wrapper,
using the app_path and template_subdir settings in this object.
This method is an alternative to get_template(). Use it when you need the actual Mako template object.
This method raises a Mako exception if the template is not found or cannot compile.
If force is True, an empty Mako template will be created when the file does not exist.
This option is used by the providers part of DMP and normally be left False. | [
"Retrieve",
"the",
"real",
"*",
"Mako",
"*",
"template",
"object",
"for",
"the",
"given",
"template",
"name",
"without",
"any",
"wrapper",
"using",
"the",
"app_path",
"and",
"template_subdir",
"settings",
"in",
"this",
"object",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/loader.py#L98-L119 | train |
doconix/django-mako-plus | django_mako_plus/router/resolver.py | app_resolver | def app_resolver(app_name=None, pattern_kwargs=None, name=None):
'''
Registers the given app_name with DMP and adds convention-based
url patterns for it.
This function is meant to be called in a project's urls.py.
'''
urlconf = URLConf(app_name, pattern_kwargs)
resolver = re_path(
'^{}/?'.format(app_name) if app_name is not None else '',
include(urlconf),
name=urlconf.app_name,
)
# this next line is a workaround for Django's URLResolver class not having
# a `name` attribute, which is expected in Django's technical_404.html.
resolver.name = getattr(resolver, 'name', name or app_name)
return resolver | python | def app_resolver(app_name=None, pattern_kwargs=None, name=None):
'''
Registers the given app_name with DMP and adds convention-based
url patterns for it.
This function is meant to be called in a project's urls.py.
'''
urlconf = URLConf(app_name, pattern_kwargs)
resolver = re_path(
'^{}/?'.format(app_name) if app_name is not None else '',
include(urlconf),
name=urlconf.app_name,
)
# this next line is a workaround for Django's URLResolver class not having
# a `name` attribute, which is expected in Django's technical_404.html.
resolver.name = getattr(resolver, 'name', name or app_name)
return resolver | [
"def",
"app_resolver",
"(",
"app_name",
"=",
"None",
",",
"pattern_kwargs",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"urlconf",
"=",
"URLConf",
"(",
"app_name",
",",
"pattern_kwargs",
")",
"resolver",
"=",
"re_path",
"(",
"'^{}/?'",
".",
"format",
"(",
"app_name",
")",
"if",
"app_name",
"is",
"not",
"None",
"else",
"''",
",",
"include",
"(",
"urlconf",
")",
",",
"name",
"=",
"urlconf",
".",
"app_name",
",",
")",
"# this next line is a workaround for Django's URLResolver class not having",
"# a `name` attribute, which is expected in Django's technical_404.html.",
"resolver",
".",
"name",
"=",
"getattr",
"(",
"resolver",
",",
"'name'",
",",
"name",
"or",
"app_name",
")",
"return",
"resolver"
] | Registers the given app_name with DMP and adds convention-based
url patterns for it.
This function is meant to be called in a project's urls.py. | [
"Registers",
"the",
"given",
"app_name",
"with",
"DMP",
"and",
"adds",
"convention",
"-",
"based",
"url",
"patterns",
"for",
"it",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L30-L46 | train |
doconix/django-mako-plus | django_mako_plus/router/resolver.py | dmp_paths_for_app | def dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None):
'''Utility function that creates the default patterns for an app'''
dmp = apps.get_app_config('django_mako_plus')
# Because these patterns are subpatterns within the app's resolver,
# we don't include the /app/ in the pattern -- it's already been
# handled by the app's resolver.
#
# Also note how the each pattern below defines the four kwargs--
# either as 1) a regex named group or 2) in kwargs.
return [
# page.function/urlparams
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/(?P<dmp_urlparams>.+?)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
}, pattern_kwargs),
'DMP /{}/page.function/urlparams'.format(pretty_app_name),
app_name,
),
# page.function
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_urlparams': '',
}, pattern_kwargs),
'DMP /{}/page.function'.format(pretty_app_name),
app_name,
),
# page/urlparams
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/(?P<dmp_urlparams>.+?)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
}, pattern_kwargs),
'DMP /{}/page/urlparams'.format(pretty_app_name),
app_name,
),
# page
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
'dmp_urlparams': '',
}, pattern_kwargs),
'DMP /{}/page'.format(pretty_app_name),
app_name,
),
# empty
dmp_path(
r'^$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
'dmp_urlparams': '',
'dmp_page': dmp.options['DEFAULT_PAGE'],
}, pattern_kwargs),
'DMP /{}'.format(pretty_app_name),
app_name,
),
] | python | def dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None):
'''Utility function that creates the default patterns for an app'''
dmp = apps.get_app_config('django_mako_plus')
# Because these patterns are subpatterns within the app's resolver,
# we don't include the /app/ in the pattern -- it's already been
# handled by the app's resolver.
#
# Also note how the each pattern below defines the four kwargs--
# either as 1) a regex named group or 2) in kwargs.
return [
# page.function/urlparams
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/(?P<dmp_urlparams>.+?)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
}, pattern_kwargs),
'DMP /{}/page.function/urlparams'.format(pretty_app_name),
app_name,
),
# page.function
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)\.(?P<dmp_function>[_a-zA-Z0-9\.\-]+)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_urlparams': '',
}, pattern_kwargs),
'DMP /{}/page.function'.format(pretty_app_name),
app_name,
),
# page/urlparams
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/(?P<dmp_urlparams>.+?)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
}, pattern_kwargs),
'DMP /{}/page/urlparams'.format(pretty_app_name),
app_name,
),
# page
dmp_path(
r'^(?P<dmp_page>[_a-zA-Z0-9\-]+)/?$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
'dmp_urlparams': '',
}, pattern_kwargs),
'DMP /{}/page'.format(pretty_app_name),
app_name,
),
# empty
dmp_path(
r'^$',
merge_dicts({
'dmp_app': app_name or dmp.options['DEFAULT_APP'],
'dmp_function': 'process_request',
'dmp_urlparams': '',
'dmp_page': dmp.options['DEFAULT_PAGE'],
}, pattern_kwargs),
'DMP /{}'.format(pretty_app_name),
app_name,
),
] | [
"def",
"dmp_paths_for_app",
"(",
"app_name",
",",
"pattern_kwargs",
"=",
"None",
",",
"pretty_app_name",
"=",
"None",
")",
":",
"dmp",
"=",
"apps",
".",
"get_app_config",
"(",
"'django_mako_plus'",
")",
"# Because these patterns are subpatterns within the app's resolver,",
"# we don't include the /app/ in the pattern -- it's already been",
"# handled by the app's resolver.",
"#",
"# Also note how the each pattern below defines the four kwargs--",
"# either as 1) a regex named group or 2) in kwargs.",
"return",
"[",
"# page.function/urlparams",
"dmp_path",
"(",
"r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)\\.(?P<dmp_function>[_a-zA-Z0-9\\.\\-]+)/(?P<dmp_urlparams>.+?)/?$'",
",",
"merge_dicts",
"(",
"{",
"'dmp_app'",
":",
"app_name",
"or",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"}",
",",
"pattern_kwargs",
")",
",",
"'DMP /{}/page.function/urlparams'",
".",
"format",
"(",
"pretty_app_name",
")",
",",
"app_name",
",",
")",
",",
"# page.function",
"dmp_path",
"(",
"r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)\\.(?P<dmp_function>[_a-zA-Z0-9\\.\\-]+)/?$'",
",",
"merge_dicts",
"(",
"{",
"'dmp_app'",
":",
"app_name",
"or",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"'dmp_urlparams'",
":",
"''",
",",
"}",
",",
"pattern_kwargs",
")",
",",
"'DMP /{}/page.function'",
".",
"format",
"(",
"pretty_app_name",
")",
",",
"app_name",
",",
")",
",",
"# page/urlparams",
"dmp_path",
"(",
"r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)/(?P<dmp_urlparams>.+?)/?$'",
",",
"merge_dicts",
"(",
"{",
"'dmp_app'",
":",
"app_name",
"or",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"'dmp_function'",
":",
"'process_request'",
",",
"}",
",",
"pattern_kwargs",
")",
",",
"'DMP /{}/page/urlparams'",
".",
"format",
"(",
"pretty_app_name",
")",
",",
"app_name",
",",
")",
",",
"# page",
"dmp_path",
"(",
"r'^(?P<dmp_page>[_a-zA-Z0-9\\-]+)/?$'",
",",
"merge_dicts",
"(",
"{",
"'dmp_app'",
":",
"app_name",
"or",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"'dmp_function'",
":",
"'process_request'",
",",
"'dmp_urlparams'",
":",
"''",
",",
"}",
",",
"pattern_kwargs",
")",
",",
"'DMP /{}/page'",
".",
"format",
"(",
"pretty_app_name",
")",
",",
"app_name",
",",
")",
",",
"# empty",
"dmp_path",
"(",
"r'^$'",
",",
"merge_dicts",
"(",
"{",
"'dmp_app'",
":",
"app_name",
"or",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"'dmp_function'",
":",
"'process_request'",
",",
"'dmp_urlparams'",
":",
"''",
",",
"'dmp_page'",
":",
"dmp",
".",
"options",
"[",
"'DEFAULT_PAGE'",
"]",
",",
"}",
",",
"pattern_kwargs",
")",
",",
"'DMP /{}'",
".",
"format",
"(",
"pretty_app_name",
")",
",",
"app_name",
",",
")",
",",
"]"
] | Utility function that creates the default patterns for an app | [
"Utility",
"function",
"that",
"creates",
"the",
"default",
"patterns",
"for",
"an",
"app"
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L65-L131 | train |
doconix/django-mako-plus | django_mako_plus/router/resolver.py | dmp_path | def dmp_path(regex, kwargs=None, name=None, app_name=None):
'''
Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should resolve to a name in INSTALLED_APPS.
If missing, defaults to DEFAULT_APP.
dmp_page The page name, which should resolve to a module:
project_dir/{dmp_app}/views/{dmp_page}.py
If missing, defaults to DEFAULT_PAGE.
dmp_function The function name (or View class name) within the module.
If missing, defaults to 'process_request'
dmp_urlparams The urlparams string to parse.
If missing, defaults to ''.
The reason for this convenience function is to be similar to
Django functions like url(), re_path(), and path().
'''
return PagePattern(regex, kwargs, name, app_name) | python | def dmp_path(regex, kwargs=None, name=None, app_name=None):
'''
Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should resolve to a name in INSTALLED_APPS.
If missing, defaults to DEFAULT_APP.
dmp_page The page name, which should resolve to a module:
project_dir/{dmp_app}/views/{dmp_page}.py
If missing, defaults to DEFAULT_PAGE.
dmp_function The function name (or View class name) within the module.
If missing, defaults to 'process_request'
dmp_urlparams The urlparams string to parse.
If missing, defaults to ''.
The reason for this convenience function is to be similar to
Django functions like url(), re_path(), and path().
'''
return PagePattern(regex, kwargs, name, app_name) | [
"def",
"dmp_path",
"(",
"regex",
",",
"kwargs",
"=",
"None",
",",
"name",
"=",
"None",
",",
"app_name",
"=",
"None",
")",
":",
"return",
"PagePattern",
"(",
"regex",
",",
"kwargs",
",",
"name",
",",
"app_name",
")"
] | Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should resolve to a name in INSTALLED_APPS.
If missing, defaults to DEFAULT_APP.
dmp_page The page name, which should resolve to a module:
project_dir/{dmp_app}/views/{dmp_page}.py
If missing, defaults to DEFAULT_PAGE.
dmp_function The function name (or View class name) within the module.
If missing, defaults to 'process_request'
dmp_urlparams The urlparams string to parse.
If missing, defaults to ''.
The reason for this convenience function is to be similar to
Django functions like url(), re_path(), and path(). | [
"Creates",
"a",
"DMP",
"-",
"style",
"convention",
"-",
"based",
"pattern",
"that",
"resolves",
"to",
"various",
"view",
"functions",
"based",
"on",
"the",
"dmp_page",
"value",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L140-L160 | train |
doconix/django-mako-plus | django_mako_plus/router/resolver.py | PagePattern.resolve | def resolve(self, path):
'''
Different from Django, this method matches by /app/page/ convention
using its pattern. The pattern should create keyword arguments for
dmp_app, dmp_page.
'''
match = super().resolve(path)
if match:
try:
routing_data = RoutingData(
match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'],
match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'],
match.kwargs.pop('dmp_function', None) or 'process_request',
match.kwargs.pop('dmp_urlparams', '').strip(),
)
if VERSION < (2, 2):
return ResolverMatch(
RequestViewWrapper(routing_data),
match.args,
match.kwargs,
url_name=match.url_name,
app_names=routing_data.app,
)
else:
return ResolverMatch(
RequestViewWrapper(routing_data),
match.args,
match.kwargs,
url_name=match.url_name,
app_names=routing_data.app,
route=str(self.pattern),
)
except ViewDoesNotExist as vdne:
# we had a pattern match, but we couldn't get a callable using kwargs from the pattern
# create a "pattern" so the programmer can see what happened
# this is a hack, but the resolver error page doesn't give other options.
# the sad face is to catch the dev's attention in Django's printout
msg = "◉︵◉ Pattern matched, but discovery failed: {}".format(vdne)
log.debug("%s %s", match.url_name, msg)
raise Resolver404({
# this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x
'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]],
'path': path,
})
raise Resolver404({'path': path}) | python | def resolve(self, path):
'''
Different from Django, this method matches by /app/page/ convention
using its pattern. The pattern should create keyword arguments for
dmp_app, dmp_page.
'''
match = super().resolve(path)
if match:
try:
routing_data = RoutingData(
match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'],
match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'],
match.kwargs.pop('dmp_function', None) or 'process_request',
match.kwargs.pop('dmp_urlparams', '').strip(),
)
if VERSION < (2, 2):
return ResolverMatch(
RequestViewWrapper(routing_data),
match.args,
match.kwargs,
url_name=match.url_name,
app_names=routing_data.app,
)
else:
return ResolverMatch(
RequestViewWrapper(routing_data),
match.args,
match.kwargs,
url_name=match.url_name,
app_names=routing_data.app,
route=str(self.pattern),
)
except ViewDoesNotExist as vdne:
# we had a pattern match, but we couldn't get a callable using kwargs from the pattern
# create a "pattern" so the programmer can see what happened
# this is a hack, but the resolver error page doesn't give other options.
# the sad face is to catch the dev's attention in Django's printout
msg = "◉︵◉ Pattern matched, but discovery failed: {}".format(vdne)
log.debug("%s %s", match.url_name, msg)
raise Resolver404({
# this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x
'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]],
'path': path,
})
raise Resolver404({'path': path}) | [
"def",
"resolve",
"(",
"self",
",",
"path",
")",
":",
"match",
"=",
"super",
"(",
")",
".",
"resolve",
"(",
"path",
")",
"if",
"match",
":",
"try",
":",
"routing_data",
"=",
"RoutingData",
"(",
"match",
".",
"kwargs",
".",
"pop",
"(",
"'dmp_app'",
",",
"None",
")",
"or",
"self",
".",
"dmp",
".",
"options",
"[",
"'DEFAULT_APP'",
"]",
",",
"match",
".",
"kwargs",
".",
"pop",
"(",
"'dmp_page'",
",",
"None",
")",
"or",
"self",
".",
"dmp",
".",
"options",
"[",
"'DEFAULT_PAGE'",
"]",
",",
"match",
".",
"kwargs",
".",
"pop",
"(",
"'dmp_function'",
",",
"None",
")",
"or",
"'process_request'",
",",
"match",
".",
"kwargs",
".",
"pop",
"(",
"'dmp_urlparams'",
",",
"''",
")",
".",
"strip",
"(",
")",
",",
")",
"if",
"VERSION",
"<",
"(",
"2",
",",
"2",
")",
":",
"return",
"ResolverMatch",
"(",
"RequestViewWrapper",
"(",
"routing_data",
")",
",",
"match",
".",
"args",
",",
"match",
".",
"kwargs",
",",
"url_name",
"=",
"match",
".",
"url_name",
",",
"app_names",
"=",
"routing_data",
".",
"app",
",",
")",
"else",
":",
"return",
"ResolverMatch",
"(",
"RequestViewWrapper",
"(",
"routing_data",
")",
",",
"match",
".",
"args",
",",
"match",
".",
"kwargs",
",",
"url_name",
"=",
"match",
".",
"url_name",
",",
"app_names",
"=",
"routing_data",
".",
"app",
",",
"route",
"=",
"str",
"(",
"self",
".",
"pattern",
")",
",",
")",
"except",
"ViewDoesNotExist",
"as",
"vdne",
":",
"# we had a pattern match, but we couldn't get a callable using kwargs from the pattern",
"# create a \"pattern\" so the programmer can see what happened",
"# this is a hack, but the resolver error page doesn't give other options.",
"# the sad face is to catch the dev's attention in Django's printout",
"msg",
"=",
"\"◉︵◉ Pattern matched, but discovery failed: {}\".forma",
"t",
"(vdne)",
"",
"",
"",
"log",
".",
"debug",
"(",
"\"%s %s\"",
",",
"match",
".",
"url_name",
",",
"msg",
")",
"raise",
"Resolver404",
"(",
"{",
"# this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x",
"'tried'",
":",
"[",
"[",
"PatternStub",
"(",
"match",
".",
"url_name",
",",
"msg",
",",
"PatternStub",
"(",
"match",
".",
"url_name",
",",
"msg",
",",
"None",
")",
")",
"]",
"]",
",",
"'path'",
":",
"path",
",",
"}",
")",
"raise",
"Resolver404",
"(",
"{",
"'path'",
":",
"path",
"}",
")"
] | Different from Django, this method matches by /app/page/ convention
using its pattern. The pattern should create keyword arguments for
dmp_app, dmp_page. | [
"Different",
"from",
"Django",
"this",
"method",
"matches",
"by",
"/",
"app",
"/",
"page",
"/",
"convention",
"using",
"its",
"pattern",
".",
"The",
"pattern",
"should",
"create",
"keyword",
"arguments",
"for",
"dmp_app",
"dmp_page",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/resolver.py#L183-L227 | train |
doconix/django-mako-plus | django_mako_plus/filters.py | alternate_syntax | def alternate_syntax(local, using, **kwargs):
'''
A Mako filter that renders a block of text using a different template engine
than Mako. The named template engine must be listed in settings.TEMPLATES.
The template context variables are available in the embedded template.
Specify kwargs to add additional variables created within the template.
This is a kludge that should be used sparingly. The `dmp_include` template tag
is often a better option.
The following examples assume you have installed the django_mustache template
engine in settings.py:
## Simple expression in Mustache syntax:
${ '{{ name }}' | template_syntax(local, 'django_mustache') }
## Embedded Mustache code block:
<%block filter="template_syntax(local, 'django_mustache')">
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
</%block>
Rendering Django or Jinja2 templates should be done with `django_syntax` and
`jinja2_syntax` because it doesn't require the using parameter.
'''
# get the request (the MakoTemplateAdapter above places this in the context)
request = local.context['request'] if isinstance(local.context, RequestContext) else None
# get the current Mako template object so we can attach the compiled string for later use
# Mako caches and automatically recreates this if the file changes
mako_template = local.template
if not hasattr(mako_template, '__compiled_template_syntax'):
mako_template.__compiled_template_syntax = {}
# create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter)
def wrap(template_st):
# get the template object, or create and cache it
try:
template = mako_template.__compiled_template_syntax[template_st]
except KeyError:
engine = engines[using]
template = engine.from_string(template_st)
# using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary)
mako_template.__compiled_template_syntax[template_st] = template
# create a copy the context and add any kwargs to it
dcontext = dict(local.context)
dcontext.update(kwargs)
# print a debug statement to the log
log.debug('rendering embedded expression or block using %s template engine', using)
# render the template with the context
return template.render(context=dcontext, request=request)
# return the embedded function
return wrap | python | def alternate_syntax(local, using, **kwargs):
'''
A Mako filter that renders a block of text using a different template engine
than Mako. The named template engine must be listed in settings.TEMPLATES.
The template context variables are available in the embedded template.
Specify kwargs to add additional variables created within the template.
This is a kludge that should be used sparingly. The `dmp_include` template tag
is often a better option.
The following examples assume you have installed the django_mustache template
engine in settings.py:
## Simple expression in Mustache syntax:
${ '{{ name }}' | template_syntax(local, 'django_mustache') }
## Embedded Mustache code block:
<%block filter="template_syntax(local, 'django_mustache')">
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
</%block>
Rendering Django or Jinja2 templates should be done with `django_syntax` and
`jinja2_syntax` because it doesn't require the using parameter.
'''
# get the request (the MakoTemplateAdapter above places this in the context)
request = local.context['request'] if isinstance(local.context, RequestContext) else None
# get the current Mako template object so we can attach the compiled string for later use
# Mako caches and automatically recreates this if the file changes
mako_template = local.template
if not hasattr(mako_template, '__compiled_template_syntax'):
mako_template.__compiled_template_syntax = {}
# create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter)
def wrap(template_st):
# get the template object, or create and cache it
try:
template = mako_template.__compiled_template_syntax[template_st]
except KeyError:
engine = engines[using]
template = engine.from_string(template_st)
# using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary)
mako_template.__compiled_template_syntax[template_st] = template
# create a copy the context and add any kwargs to it
dcontext = dict(local.context)
dcontext.update(kwargs)
# print a debug statement to the log
log.debug('rendering embedded expression or block using %s template engine', using)
# render the template with the context
return template.render(context=dcontext, request=request)
# return the embedded function
return wrap | [
"def",
"alternate_syntax",
"(",
"local",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"# get the request (the MakoTemplateAdapter above places this in the context)",
"request",
"=",
"local",
".",
"context",
"[",
"'request'",
"]",
"if",
"isinstance",
"(",
"local",
".",
"context",
",",
"RequestContext",
")",
"else",
"None",
"# get the current Mako template object so we can attach the compiled string for later use",
"# Mako caches and automatically recreates this if the file changes",
"mako_template",
"=",
"local",
".",
"template",
"if",
"not",
"hasattr",
"(",
"mako_template",
",",
"'__compiled_template_syntax'",
")",
":",
"mako_template",
".",
"__compiled_template_syntax",
"=",
"{",
"}",
"# create a closure so we can still get to context and using (Mako filters take exactly one parameter: the string to filter)",
"def",
"wrap",
"(",
"template_st",
")",
":",
"# get the template object, or create and cache it",
"try",
":",
"template",
"=",
"mako_template",
".",
"__compiled_template_syntax",
"[",
"template_st",
"]",
"except",
"KeyError",
":",
"engine",
"=",
"engines",
"[",
"using",
"]",
"template",
"=",
"engine",
".",
"from_string",
"(",
"template_st",
")",
"# using full string, even if long, as the key doesn't really affect performance of python's hash (see http://stackoverflow.com/questions/28150047/efficiency-of-long-str-keys-in-python-dictionary)",
"mako_template",
".",
"__compiled_template_syntax",
"[",
"template_st",
"]",
"=",
"template",
"# create a copy the context and add any kwargs to it",
"dcontext",
"=",
"dict",
"(",
"local",
".",
"context",
")",
"dcontext",
".",
"update",
"(",
"kwargs",
")",
"# print a debug statement to the log",
"log",
".",
"debug",
"(",
"'rendering embedded expression or block using %s template engine'",
",",
"using",
")",
"# render the template with the context",
"return",
"template",
".",
"render",
"(",
"context",
"=",
"dcontext",
",",
"request",
"=",
"request",
")",
"# return the embedded function",
"return",
"wrap"
] | A Mako filter that renders a block of text using a different template engine
than Mako. The named template engine must be listed in settings.TEMPLATES.
The template context variables are available in the embedded template.
Specify kwargs to add additional variables created within the template.
This is a kludge that should be used sparingly. The `dmp_include` template tag
is often a better option.
The following examples assume you have installed the django_mustache template
engine in settings.py:
## Simple expression in Mustache syntax:
${ '{{ name }}' | template_syntax(local, 'django_mustache') }
## Embedded Mustache code block:
<%block filter="template_syntax(local, 'django_mustache')">
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
</%block>
Rendering Django or Jinja2 templates should be done with `django_syntax` and
`jinja2_syntax` because it doesn't require the using parameter. | [
"A",
"Mako",
"filter",
"that",
"renders",
"a",
"block",
"of",
"text",
"using",
"a",
"different",
"template",
"engine",
"than",
"Mako",
".",
"The",
"named",
"template",
"engine",
"must",
"be",
"listed",
"in",
"settings",
".",
"TEMPLATES",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/filters.py#L64-L124 | train |
doconix/django-mako-plus | django_mako_plus/router/discover.py | get_view_function | def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Retrieves a view function from the cache, finding it if the first time.
Raises ViewDoesNotExist if not found. This is called by resolver.py.
'''
# first check the cache (without doing locks)
key = ( module_name, function_name )
try:
return CACHED_VIEW_FUNCTIONS[key]
except KeyError:
with rlock:
# try again now that we're locked
try:
return CACHED_VIEW_FUNCTIONS[key]
except KeyError:
# if we get here, we need to load the view function
func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator)
# cache in production mode
if not settings.DEBUG:
CACHED_VIEW_FUNCTIONS[key] = func
return func
# the code should never be able to get here
raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.") | python | def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Retrieves a view function from the cache, finding it if the first time.
Raises ViewDoesNotExist if not found. This is called by resolver.py.
'''
# first check the cache (without doing locks)
key = ( module_name, function_name )
try:
return CACHED_VIEW_FUNCTIONS[key]
except KeyError:
with rlock:
# try again now that we're locked
try:
return CACHED_VIEW_FUNCTIONS[key]
except KeyError:
# if we get here, we need to load the view function
func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator)
# cache in production mode
if not settings.DEBUG:
CACHED_VIEW_FUNCTIONS[key] = func
return func
# the code should never be able to get here
raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.") | [
"def",
"get_view_function",
"(",
"module_name",
",",
"function_name",
",",
"fallback_app",
"=",
"None",
",",
"fallback_template",
"=",
"None",
",",
"verify_decorator",
"=",
"True",
")",
":",
"# first check the cache (without doing locks)",
"key",
"=",
"(",
"module_name",
",",
"function_name",
")",
"try",
":",
"return",
"CACHED_VIEW_FUNCTIONS",
"[",
"key",
"]",
"except",
"KeyError",
":",
"with",
"rlock",
":",
"# try again now that we're locked",
"try",
":",
"return",
"CACHED_VIEW_FUNCTIONS",
"[",
"key",
"]",
"except",
"KeyError",
":",
"# if we get here, we need to load the view function",
"func",
"=",
"find_view_function",
"(",
"module_name",
",",
"function_name",
",",
"fallback_app",
",",
"fallback_template",
",",
"verify_decorator",
")",
"# cache in production mode",
"if",
"not",
"settings",
".",
"DEBUG",
":",
"CACHED_VIEW_FUNCTIONS",
"[",
"key",
"]",
"=",
"func",
"return",
"func",
"# the code should never be able to get here",
"raise",
"Exception",
"(",
"\"Django-Mako-Plus error: get_view_function() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.\"",
")"
] | Retrieves a view function from the cache, finding it if the first time.
Raises ViewDoesNotExist if not found. This is called by resolver.py. | [
"Retrieves",
"a",
"view",
"function",
"from",
"the",
"cache",
"finding",
"it",
"if",
"the",
"first",
"time",
".",
"Raises",
"ViewDoesNotExist",
"if",
"not",
"found",
".",
"This",
"is",
"called",
"by",
"resolver",
".",
"py",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L24-L47 | train |
doconix/django-mako-plus | django_mako_plus/router/discover.py | find_view_function | def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
'''
dmp = apps.get_app_config('django_mako_plus')
# I'm first calling find_spec first here beacuse I don't want import_module in
# a try/except -- there are lots of reasons that importing can fail, and I just want to
# know whether the file actually exists. find_spec raises AttributeError if not found.
try:
spec = find_spec(module_name)
except ValueError:
spec = None
if spec is None:
# no view module, so create a view function that directly renders the template
try:
return create_view_for_template(fallback_app, fallback_template)
except TemplateDoesNotExist as e:
raise ViewDoesNotExist('view module {} not found, and fallback template {} could not be loaded ({})'.format(module_name, fallback_template, e))
# load the module and function
try:
module = import_module(module_name)
func = getattr(module, function_name)
func.view_type = 'function'
except ImportError as e:
raise ViewDoesNotExist('module "{}" could not be imported: {}'.format(module_name, e))
except AttributeError as e:
raise ViewDoesNotExist('module "{}" found successfully, but "{}" was not found: {}'.format(module_name, function_name, e))
# if class-based view, call as_view() to get a view function to it
if inspect.isclass(func) and issubclass(func, View):
func = func.as_view()
func.view_type = 'class'
# if regular view function, check the decorator
elif verify_decorator and not view_function.is_decorated(func):
raise ViewDoesNotExist("view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.".format(module_name, function_name))
# attach a converter to the view function
if dmp.options['PARAMETER_CONVERTER'] is not None:
try:
converter = import_qualified(dmp.options['PARAMETER_CONVERTER'])(func)
setattr(func, CONVERTER_ATTRIBUTE_NAME, converter)
except ImportError as e:
raise ImproperlyConfigured('Cannot find PARAMETER_CONVERTER: {}'.format(str(e)))
# return the function/class
return func | python | def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
'''
dmp = apps.get_app_config('django_mako_plus')
# I'm first calling find_spec first here beacuse I don't want import_module in
# a try/except -- there are lots of reasons that importing can fail, and I just want to
# know whether the file actually exists. find_spec raises AttributeError if not found.
try:
spec = find_spec(module_name)
except ValueError:
spec = None
if spec is None:
# no view module, so create a view function that directly renders the template
try:
return create_view_for_template(fallback_app, fallback_template)
except TemplateDoesNotExist as e:
raise ViewDoesNotExist('view module {} not found, and fallback template {} could not be loaded ({})'.format(module_name, fallback_template, e))
# load the module and function
try:
module = import_module(module_name)
func = getattr(module, function_name)
func.view_type = 'function'
except ImportError as e:
raise ViewDoesNotExist('module "{}" could not be imported: {}'.format(module_name, e))
except AttributeError as e:
raise ViewDoesNotExist('module "{}" found successfully, but "{}" was not found: {}'.format(module_name, function_name, e))
# if class-based view, call as_view() to get a view function to it
if inspect.isclass(func) and issubclass(func, View):
func = func.as_view()
func.view_type = 'class'
# if regular view function, check the decorator
elif verify_decorator and not view_function.is_decorated(func):
raise ViewDoesNotExist("view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.".format(module_name, function_name))
# attach a converter to the view function
if dmp.options['PARAMETER_CONVERTER'] is not None:
try:
converter = import_qualified(dmp.options['PARAMETER_CONVERTER'])(func)
setattr(func, CONVERTER_ATTRIBUTE_NAME, converter)
except ImportError as e:
raise ImproperlyConfigured('Cannot find PARAMETER_CONVERTER: {}'.format(str(e)))
# return the function/class
return func | [
"def",
"find_view_function",
"(",
"module_name",
",",
"function_name",
",",
"fallback_app",
"=",
"None",
",",
"fallback_template",
"=",
"None",
",",
"verify_decorator",
"=",
"True",
")",
":",
"dmp",
"=",
"apps",
".",
"get_app_config",
"(",
"'django_mako_plus'",
")",
"# I'm first calling find_spec first here beacuse I don't want import_module in",
"# a try/except -- there are lots of reasons that importing can fail, and I just want to",
"# know whether the file actually exists. find_spec raises AttributeError if not found.",
"try",
":",
"spec",
"=",
"find_spec",
"(",
"module_name",
")",
"except",
"ValueError",
":",
"spec",
"=",
"None",
"if",
"spec",
"is",
"None",
":",
"# no view module, so create a view function that directly renders the template",
"try",
":",
"return",
"create_view_for_template",
"(",
"fallback_app",
",",
"fallback_template",
")",
"except",
"TemplateDoesNotExist",
"as",
"e",
":",
"raise",
"ViewDoesNotExist",
"(",
"'view module {} not found, and fallback template {} could not be loaded ({})'",
".",
"format",
"(",
"module_name",
",",
"fallback_template",
",",
"e",
")",
")",
"# load the module and function",
"try",
":",
"module",
"=",
"import_module",
"(",
"module_name",
")",
"func",
"=",
"getattr",
"(",
"module",
",",
"function_name",
")",
"func",
".",
"view_type",
"=",
"'function'",
"except",
"ImportError",
"as",
"e",
":",
"raise",
"ViewDoesNotExist",
"(",
"'module \"{}\" could not be imported: {}'",
".",
"format",
"(",
"module_name",
",",
"e",
")",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"ViewDoesNotExist",
"(",
"'module \"{}\" found successfully, but \"{}\" was not found: {}'",
".",
"format",
"(",
"module_name",
",",
"function_name",
",",
"e",
")",
")",
"# if class-based view, call as_view() to get a view function to it",
"if",
"inspect",
".",
"isclass",
"(",
"func",
")",
"and",
"issubclass",
"(",
"func",
",",
"View",
")",
":",
"func",
"=",
"func",
".",
"as_view",
"(",
")",
"func",
".",
"view_type",
"=",
"'class'",
"# if regular view function, check the decorator",
"elif",
"verify_decorator",
"and",
"not",
"view_function",
".",
"is_decorated",
"(",
"func",
")",
":",
"raise",
"ViewDoesNotExist",
"(",
"\"view {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.\"",
".",
"format",
"(",
"module_name",
",",
"function_name",
")",
")",
"# attach a converter to the view function",
"if",
"dmp",
".",
"options",
"[",
"'PARAMETER_CONVERTER'",
"]",
"is",
"not",
"None",
":",
"try",
":",
"converter",
"=",
"import_qualified",
"(",
"dmp",
".",
"options",
"[",
"'PARAMETER_CONVERTER'",
"]",
")",
"(",
"func",
")",
"setattr",
"(",
"func",
",",
"CONVERTER_ATTRIBUTE_NAME",
",",
"converter",
")",
"except",
"ImportError",
"as",
"e",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Cannot find PARAMETER_CONVERTER: {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"# return the function/class",
"return",
"func"
] | Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found. | [
"Finds",
"a",
"view",
"function",
"class",
"-",
"based",
"view",
"or",
"template",
"view",
".",
"Raises",
"ViewDoesNotExist",
"if",
"not",
"found",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L50-L99 | train |
doconix/django-mako-plus | django_mako_plus/router/discover.py | create_view_for_template | def create_view_for_template(app_name, template_name):
'''
Creates a view function for templates (used whe a view.py file doesn't exist but the .html does)
Raises TemplateDoesNotExist if the template doesn't exist.
'''
# ensure the template exists
apps.get_app_config('django_mako_plus').engine.get_template_loader(app_name).get_template(template_name)
# create the view function
def template_view(request, *args, **kwargs):
# not caching the template object (getting it each time) because Mako has its own cache
dmp = apps.get_app_config('django_mako_plus')
template = dmp.engine.get_template_loader(app_name).get_template(template_name)
return template.render_to_response(request=request, context=kwargs)
template_view.view_type = 'template'
return template_view | python | def create_view_for_template(app_name, template_name):
'''
Creates a view function for templates (used whe a view.py file doesn't exist but the .html does)
Raises TemplateDoesNotExist if the template doesn't exist.
'''
# ensure the template exists
apps.get_app_config('django_mako_plus').engine.get_template_loader(app_name).get_template(template_name)
# create the view function
def template_view(request, *args, **kwargs):
# not caching the template object (getting it each time) because Mako has its own cache
dmp = apps.get_app_config('django_mako_plus')
template = dmp.engine.get_template_loader(app_name).get_template(template_name)
return template.render_to_response(request=request, context=kwargs)
template_view.view_type = 'template'
return template_view | [
"def",
"create_view_for_template",
"(",
"app_name",
",",
"template_name",
")",
":",
"# ensure the template exists",
"apps",
".",
"get_app_config",
"(",
"'django_mako_plus'",
")",
".",
"engine",
".",
"get_template_loader",
"(",
"app_name",
")",
".",
"get_template",
"(",
"template_name",
")",
"# create the view function",
"def",
"template_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# not caching the template object (getting it each time) because Mako has its own cache",
"dmp",
"=",
"apps",
".",
"get_app_config",
"(",
"'django_mako_plus'",
")",
"template",
"=",
"dmp",
".",
"engine",
".",
"get_template_loader",
"(",
"app_name",
")",
".",
"get_template",
"(",
"template_name",
")",
"return",
"template",
".",
"render_to_response",
"(",
"request",
"=",
"request",
",",
"context",
"=",
"kwargs",
")",
"template_view",
".",
"view_type",
"=",
"'template'",
"return",
"template_view"
] | Creates a view function for templates (used whe a view.py file doesn't exist but the .html does)
Raises TemplateDoesNotExist if the template doesn't exist. | [
"Creates",
"a",
"view",
"function",
"for",
"templates",
"(",
"used",
"whe",
"a",
"view",
".",
"py",
"file",
"doesn",
"t",
"exist",
"but",
"the",
".",
"html",
"does",
")",
"Raises",
"TemplateDoesNotExist",
"if",
"the",
"template",
"doesn",
"t",
"exist",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/router/discover.py#L102-L116 | train |
doconix/django-mako-plus | django_mako_plus/provider/base.py | BaseProvider.iter_related | def iter_related(self):
'''
Generator function that iterates this object's related providers,
which includes this provider.
'''
for tpl in self.provider_run.templates:
yield tpl.providers[self.index] | python | def iter_related(self):
'''
Generator function that iterates this object's related providers,
which includes this provider.
'''
for tpl in self.provider_run.templates:
yield tpl.providers[self.index] | [
"def",
"iter_related",
"(",
"self",
")",
":",
"for",
"tpl",
"in",
"self",
".",
"provider_run",
".",
"templates",
":",
"yield",
"tpl",
".",
"providers",
"[",
"self",
".",
"index",
"]"
] | Generator function that iterates this object's related providers,
which includes this provider. | [
"Generator",
"function",
"that",
"iterates",
"this",
"object",
"s",
"related",
"providers",
"which",
"includes",
"this",
"provider",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/base.py#L94-L100 | train |
doconix/django-mako-plus | django_mako_plus/provider/base.py | BaseProvider.get_cache_item | def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('Caching disabled in DEBUG mode')
return getattr(self.template, self.options['template_cache_key']) | python | def get_cache_item(self):
'''Gets the cached item. Raises AttributeError if it hasn't been set.'''
if settings.DEBUG:
raise AttributeError('Caching disabled in DEBUG mode')
return getattr(self.template, self.options['template_cache_key']) | [
"def",
"get_cache_item",
"(",
"self",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"raise",
"AttributeError",
"(",
"'Caching disabled in DEBUG mode'",
")",
"return",
"getattr",
"(",
"self",
".",
"template",
",",
"self",
".",
"options",
"[",
"'template_cache_key'",
"]",
")"
] | Gets the cached item. Raises AttributeError if it hasn't been set. | [
"Gets",
"the",
"cached",
"item",
".",
"Raises",
"AttributeError",
"if",
"it",
"hasn",
"t",
"been",
"set",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/provider/base.py#L149-L153 | train |
doconix/django-mako-plus | django_mako_plus/util/datastruct.py | flatten | def flatten(*args):
'''Generator that recursively flattens embedded lists, tuples, etc.'''
for arg in args:
if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)):
yield from flatten(*arg)
else:
yield arg | python | def flatten(*args):
'''Generator that recursively flattens embedded lists, tuples, etc.'''
for arg in args:
if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)):
yield from flatten(*arg)
else:
yield arg | [
"def",
"flatten",
"(",
"*",
"args",
")",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"arg",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"yield",
"from",
"flatten",
"(",
"*",
"arg",
")",
"else",
":",
"yield",
"arg"
] | Generator that recursively flattens embedded lists, tuples, etc. | [
"Generator",
"that",
"recursively",
"flattens",
"embedded",
"lists",
"tuples",
"etc",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/datastruct.py#L18-L24 | train |
doconix/django-mako-plus | django_mako_plus/util/datastruct.py | crc32 | def crc32(filename):
'''
Calculates the CRC checksum for a file.
Using CRC32 because security isn't the issue and don't need perfect noncollisions.
We just need to know if a file has changed.
On my machine, crc32 was 20 times faster than any hashlib algorithm,
including blake and md5 algorithms.
'''
result = 0
with open(filename, 'rb') as fin:
while True:
chunk = fin.read(48)
if len(chunk) == 0:
break
result = zlib.crc32(chunk, result)
return result | python | def crc32(filename):
'''
Calculates the CRC checksum for a file.
Using CRC32 because security isn't the issue and don't need perfect noncollisions.
We just need to know if a file has changed.
On my machine, crc32 was 20 times faster than any hashlib algorithm,
including blake and md5 algorithms.
'''
result = 0
with open(filename, 'rb') as fin:
while True:
chunk = fin.read(48)
if len(chunk) == 0:
break
result = zlib.crc32(chunk, result)
return result | [
"def",
"crc32",
"(",
"filename",
")",
":",
"result",
"=",
"0",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fin",
":",
"while",
"True",
":",
"chunk",
"=",
"fin",
".",
"read",
"(",
"48",
")",
"if",
"len",
"(",
"chunk",
")",
"==",
"0",
":",
"break",
"result",
"=",
"zlib",
".",
"crc32",
"(",
"chunk",
",",
"result",
")",
"return",
"result"
] | Calculates the CRC checksum for a file.
Using CRC32 because security isn't the issue and don't need perfect noncollisions.
We just need to know if a file has changed.
On my machine, crc32 was 20 times faster than any hashlib algorithm,
including blake and md5 algorithms. | [
"Calculates",
"the",
"CRC",
"checksum",
"for",
"a",
"file",
".",
"Using",
"CRC32",
"because",
"security",
"isn",
"t",
"the",
"issue",
"and",
"don",
"t",
"need",
"perfect",
"noncollisions",
".",
"We",
"just",
"need",
"to",
"know",
"if",
"a",
"file",
"has",
"changed",
"."
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/util/datastruct.py#L28-L44 | train |
doconix/django-mako-plus | django_mako_plus/management/commands/dmp_makemessages.py | Command.compile_mako_files | def compile_mako_files(self, app_config):
'''Compiles the Mako templates within the apps of this system'''
# go through the files in the templates, scripts, and styles directories
for subdir_name in self.SEARCH_DIRS:
subdir = subdir_name.format(
app_path=app_config.path,
app_name=app_config.name,
)
def recurse_path(path):
self.message('searching for Mako templates in {}'.format(path), 1)
if os.path.exists(path):
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
_, ext = os.path.splitext(filename)
if filename.startswith('__'): # __dmpcache__, __pycache__
continue
elif os.path.isdir(filepath):
recurse_path(filepath)
elif ext.lower() in ( '.htm', '.html', '.mako' ):
# create the template object, which creates the compiled .py file
self.message('compiling {}'.format(filepath), 2)
try:
get_template_for_path(filepath)
except TemplateSyntaxError:
if not self.options.get('ignore_template_errors'):
raise
recurse_path(subdir) | python | def compile_mako_files(self, app_config):
'''Compiles the Mako templates within the apps of this system'''
# go through the files in the templates, scripts, and styles directories
for subdir_name in self.SEARCH_DIRS:
subdir = subdir_name.format(
app_path=app_config.path,
app_name=app_config.name,
)
def recurse_path(path):
self.message('searching for Mako templates in {}'.format(path), 1)
if os.path.exists(path):
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
_, ext = os.path.splitext(filename)
if filename.startswith('__'): # __dmpcache__, __pycache__
continue
elif os.path.isdir(filepath):
recurse_path(filepath)
elif ext.lower() in ( '.htm', '.html', '.mako' ):
# create the template object, which creates the compiled .py file
self.message('compiling {}'.format(filepath), 2)
try:
get_template_for_path(filepath)
except TemplateSyntaxError:
if not self.options.get('ignore_template_errors'):
raise
recurse_path(subdir) | [
"def",
"compile_mako_files",
"(",
"self",
",",
"app_config",
")",
":",
"# go through the files in the templates, scripts, and styles directories",
"for",
"subdir_name",
"in",
"self",
".",
"SEARCH_DIRS",
":",
"subdir",
"=",
"subdir_name",
".",
"format",
"(",
"app_path",
"=",
"app_config",
".",
"path",
",",
"app_name",
"=",
"app_config",
".",
"name",
",",
")",
"def",
"recurse_path",
"(",
"path",
")",
":",
"self",
".",
"message",
"(",
"'searching for Mako templates in {}'",
".",
"format",
"(",
"path",
")",
",",
"1",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"filename",
".",
"startswith",
"(",
"'__'",
")",
":",
"# __dmpcache__, __pycache__",
"continue",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"filepath",
")",
":",
"recurse_path",
"(",
"filepath",
")",
"elif",
"ext",
".",
"lower",
"(",
")",
"in",
"(",
"'.htm'",
",",
"'.html'",
",",
"'.mako'",
")",
":",
"# create the template object, which creates the compiled .py file",
"self",
".",
"message",
"(",
"'compiling {}'",
".",
"format",
"(",
"filepath",
")",
",",
"2",
")",
"try",
":",
"get_template_for_path",
"(",
"filepath",
")",
"except",
"TemplateSyntaxError",
":",
"if",
"not",
"self",
".",
"options",
".",
"get",
"(",
"'ignore_template_errors'",
")",
":",
"raise",
"recurse_path",
"(",
"subdir",
")"
] | Compiles the Mako templates within the apps of this system | [
"Compiles",
"the",
"Mako",
"templates",
"within",
"the",
"apps",
"of",
"this",
"system"
] | a90f9b4af19e5fa9f83452989cdcaed21569a181 | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/commands/dmp_makemessages.py#L70-L100 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.