partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | ZappaCLI.init | Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, which isn't pretty. | zappa/cli.py | def init(self, settings_file="zappa_settings.json"):
"""
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, whi... | def init(self, settings_file="zappa_settings.json"):
"""
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.
This should probably be broken up into few separate componants once it's stable.
Testing these inputs requires monkeypatching with mock, whi... | [
"Initialize",
"a",
"new",
"Zappa",
"project",
"by",
"creating",
"a",
"new",
"zappa_settings",
".",
"json",
"in",
"a",
"guided",
"process",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1550-L1797 | [
"def",
"init",
"(",
"self",
",",
"settings_file",
"=",
"\"zappa_settings.json\"",
")",
":",
"# Make sure we're in a venv.",
"self",
".",
"check_venv",
"(",
")",
"# Ensure that we don't already have a zappa_settings file.",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.certify | Register or update a domain certificate for this env. | zappa/cli.py | def certify(self, no_confirm=True, manual=False):
"""
Register or update a domain certificate for this env.
"""
if not self.domain:
raise ClickException("Can't certify a domain without " + click.style("domain", fg="red", bold=True) + " configured!")
if not no_confir... | def certify(self, no_confirm=True, manual=False):
"""
Register or update a domain certificate for this env.
"""
if not self.domain:
raise ClickException("Can't certify a domain without " + click.style("domain", fg="red", bold=True) + " configured!")
if not no_confir... | [
"Register",
"or",
"update",
"a",
"domain",
"certificate",
"for",
"this",
"env",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1799-L1919 | [
"def",
"certify",
"(",
"self",
",",
"no_confirm",
"=",
"True",
",",
"manual",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"domain",
":",
"raise",
"ClickException",
"(",
"\"Can't certify a domain without \"",
"+",
"click",
".",
"style",
"(",
"\"domain\"... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.shell | Spawn a debug shell. | zappa/cli.py | def shell(self):
"""
Spawn a debug shell.
"""
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!")
self.zappa.shell()
return | def shell(self):
"""
Spawn a debug shell.
"""
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!")
self.zappa.shell()
return | [
"Spawn",
"a",
"debug",
"shell",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1924-L1930 | [
"def",
"shell",
"(",
"self",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"NOTICE!\"",
",",
"fg",
"=",
"\"yellow\"",
",",
"bold",
"=",
"True",
")",
"+",
"\" This is a \"",
"+",
"click",
".",
"style",
"(",
"\"local\"",
",",
"fg",... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.callback | Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None | zappa/cli.py | def callback(self, position):
"""
Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None
"""
callbacks = self.stage_config.get('callbacks', {})
callback = callbacks.get(position)
if callback:
(mod_p... | def callback(self, position):
"""
Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None
"""
callbacks = self.stage_config.get('callbacks', {})
callback = callbacks.get(position)
if callback:
(mod_p... | [
"Allows",
"the",
"execution",
"of",
"custom",
"code",
"between",
"creation",
"of",
"the",
"zip",
"file",
"and",
"deployment",
"to",
"AWS",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1936-L1977 | [
"def",
"callback",
"(",
"self",
",",
"position",
")",
":",
"callbacks",
"=",
"self",
".",
"stage_config",
".",
"get",
"(",
"'callbacks'",
",",
"{",
"}",
")",
"callback",
"=",
"callbacks",
".",
"get",
"(",
"position",
")",
"if",
"callback",
":",
"(",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.check_for_update | Print a warning if there's a new Zappa version available. | zappa/cli.py | def check_for_update(self):
"""
Print a warning if there's a new Zappa version available.
"""
try:
version = pkg_resources.require("zappa")[0].version
updateable = check_new_version_available(version)
if updateable:
click.echo(click.sty... | def check_for_update(self):
"""
Print a warning if there's a new Zappa version available.
"""
try:
version = pkg_resources.require("zappa")[0].version
updateable = check_new_version_available(version)
if updateable:
click.echo(click.sty... | [
"Print",
"a",
"warning",
"if",
"there",
"s",
"a",
"new",
"Zappa",
"version",
"available",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1979-L1994 | [
"def",
"check_for_update",
"(",
"self",
")",
":",
"try",
":",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"\"zappa\"",
")",
"[",
"0",
"]",
".",
"version",
"updateable",
"=",
"check_new_version_available",
"(",
"version",
")",
"if",
"updateable",
":... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.load_settings | Load the local zappa_settings file.
An existing boto session can be supplied, though this is likely for testing purposes.
Returns the loaded Zappa object. | zappa/cli.py | def load_settings(self, settings_file=None, session=None):
"""
Load the local zappa_settings file.
An existing boto session can be supplied, though this is likely for testing purposes.
Returns the loaded Zappa object.
"""
# Ensure we're passed a valid settings file.
... | def load_settings(self, settings_file=None, session=None):
"""
Load the local zappa_settings file.
An existing boto session can be supplied, though this is likely for testing purposes.
Returns the loaded Zappa object.
"""
# Ensure we're passed a valid settings file.
... | [
"Load",
"the",
"local",
"zappa_settings",
"file",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1996-L2133 | [
"def",
"load_settings",
"(",
"self",
",",
"settings_file",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"# Ensure we're passed a valid settings file.",
"if",
"not",
"settings_file",
":",
"settings_file",
"=",
"self",
".",
"get_json_or_yaml_settings",
"(",
")"... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.get_json_or_yaml_settings | Return zappa_settings path as JSON or YAML (or TOML), as appropriate. | zappa/cli.py | def get_json_or_yaml_settings(self, settings_name="zappa_settings"):
"""
Return zappa_settings path as JSON or YAML (or TOML), as appropriate.
"""
zs_json = settings_name + ".json"
zs_yml = settings_name + ".yml"
zs_yaml = settings_name + ".yaml"
zs_toml = setting... | def get_json_or_yaml_settings(self, settings_name="zappa_settings"):
"""
Return zappa_settings path as JSON or YAML (or TOML), as appropriate.
"""
zs_json = settings_name + ".json"
zs_yml = settings_name + ".yml"
zs_yaml = settings_name + ".yaml"
zs_toml = setting... | [
"Return",
"zappa_settings",
"path",
"as",
"JSON",
"or",
"YAML",
"(",
"or",
"TOML",
")",
"as",
"appropriate",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2135-L2161 | [
"def",
"get_json_or_yaml_settings",
"(",
"self",
",",
"settings_name",
"=",
"\"zappa_settings\"",
")",
":",
"zs_json",
"=",
"settings_name",
"+",
"\".json\"",
"zs_yml",
"=",
"settings_name",
"+",
"\".yml\"",
"zs_yaml",
"=",
"settings_name",
"+",
"\".yaml\"",
"zs_tom... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.load_settings_file | Load our settings file. | zappa/cli.py | def load_settings_file(self, settings_file=None):
"""
Load our settings file.
"""
if not settings_file:
settings_file = self.get_json_or_yaml_settings()
if not os.path.isfile(settings_file):
raise ClickException("Please configure your zappa_settings file ... | def load_settings_file(self, settings_file=None):
"""
Load our settings file.
"""
if not settings_file:
settings_file = self.get_json_or_yaml_settings()
if not os.path.isfile(settings_file):
raise ClickException("Please configure your zappa_settings file ... | [
"Load",
"our",
"settings",
"file",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2163-L2191 | [
"def",
"load_settings_file",
"(",
"self",
",",
"settings_file",
"=",
"None",
")",
":",
"if",
"not",
"settings_file",
":",
"settings_file",
"=",
"self",
".",
"get_json_or_yaml_settings",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"settings_... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.create_package | Ensure that the package can be properly configured,
and then create it. | zappa/cli.py | def create_package(self, output=None):
"""
Ensure that the package can be properly configured,
and then create it.
"""
# Create the Lambda zip package (includes project and virtualenvironment)
# Also define the path the handler file so it can be copied to the zip
... | def create_package(self, output=None):
"""
Ensure that the package can be properly configured,
and then create it.
"""
# Create the Lambda zip package (includes project and virtualenvironment)
# Also define the path the handler file so it can be copied to the zip
... | [
"Ensure",
"that",
"the",
"package",
"can",
"be",
"properly",
"configured",
"and",
"then",
"create",
"it",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2193-L2441 | [
"def",
"create_package",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"# Create the Lambda zip package (includes project and virtualenvironment)",
"# Also define the path the handler file so it can be copied to the zip",
"# root for Lambda.",
"current_file",
"=",
"os",
".",
"... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.remove_local_zip | Remove our local zip file. | zappa/cli.py | def remove_local_zip(self):
"""
Remove our local zip file.
"""
if self.stage_config.get('delete_local_zip', True):
try:
if os.path.isfile(self.zip_path):
os.remove(self.zip_path)
if self.handler_path and os.path.isfile(self... | def remove_local_zip(self):
"""
Remove our local zip file.
"""
if self.stage_config.get('delete_local_zip', True):
try:
if os.path.isfile(self.zip_path):
os.remove(self.zip_path)
if self.handler_path and os.path.isfile(self... | [
"Remove",
"our",
"local",
"zip",
"file",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2443-L2455 | [
"def",
"remove_local_zip",
"(",
"self",
")",
":",
"if",
"self",
".",
"stage_config",
".",
"get",
"(",
"'delete_local_zip'",
",",
"True",
")",
":",
"try",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"zip_path",
")",
":",
"os",
".",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.remove_uploaded_zip | Remove the local and S3 zip file after uploading and updating. | zappa/cli.py | def remove_uploaded_zip(self):
"""
Remove the local and S3 zip file after uploading and updating.
"""
# Remove the uploaded zip from S3, because it is now registered..
if self.stage_config.get('delete_s3_zip', True):
self.zappa.remove_from_s3(self.zip_path, self.s3_b... | def remove_uploaded_zip(self):
"""
Remove the local and S3 zip file after uploading and updating.
"""
# Remove the uploaded zip from S3, because it is now registered..
if self.stage_config.get('delete_s3_zip', True):
self.zappa.remove_from_s3(self.zip_path, self.s3_b... | [
"Remove",
"the",
"local",
"and",
"S3",
"zip",
"file",
"after",
"uploading",
"and",
"updating",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2457-L2467 | [
"def",
"remove_uploaded_zip",
"(",
"self",
")",
":",
"# Remove the uploaded zip from S3, because it is now registered..",
"if",
"self",
".",
"stage_config",
".",
"get",
"(",
"'delete_s3_zip'",
",",
"True",
")",
":",
"self",
".",
"zappa",
".",
"remove_from_s3",
"(",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.on_exit | Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs. | zappa/cli.py | def on_exit(self):
"""
Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.
"""
if self.zip_path:
# Only try to remove uploaded zip if we're running a command that has loaded credentials
if s... | def on_exit(self):
"""
Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.
"""
if self.zip_path:
# Only try to remove uploaded zip if we're running a command that has loaded credentials
if s... | [
"Cleanup",
"after",
"the",
"command",
"finishes",
".",
"Always",
"called",
":",
"SystemExit",
"KeyboardInterrupt",
"and",
"any",
"other",
"Exception",
"that",
"occurs",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2469-L2479 | [
"def",
"on_exit",
"(",
"self",
")",
":",
"if",
"self",
".",
"zip_path",
":",
"# Only try to remove uploaded zip if we're running a command that has loaded credentials",
"if",
"self",
".",
"load_credentials",
":",
"self",
".",
"remove_uploaded_zip",
"(",
")",
"self",
"."... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.print_logs | Parse, filter and print logs to the console. | zappa/cli.py | def print_logs(self, logs, colorize=True, http=False, non_http=False, force_colorize=None):
"""
Parse, filter and print logs to the console.
"""
for log in logs:
timestamp = log['timestamp']
message = log['message']
if "START RequestId" in message:
... | def print_logs(self, logs, colorize=True, http=False, non_http=False, force_colorize=None):
"""
Parse, filter and print logs to the console.
"""
for log in logs:
timestamp = log['timestamp']
message = log['message']
if "START RequestId" in message:
... | [
"Parse",
"filter",
"and",
"print",
"logs",
"to",
"the",
"console",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2481-L2514 | [
"def",
"print_logs",
"(",
"self",
",",
"logs",
",",
"colorize",
"=",
"True",
",",
"http",
"=",
"False",
",",
"non_http",
"=",
"False",
",",
"force_colorize",
"=",
"None",
")",
":",
"for",
"log",
"in",
"logs",
":",
"timestamp",
"=",
"log",
"[",
"'time... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.is_http_log_entry | Determines if a log entry is an HTTP-formatted log string or not. | zappa/cli.py | def is_http_log_entry(self, string):
"""
Determines if a log entry is an HTTP-formatted log string or not.
"""
# Debug event filter
if 'Zappa Event' in string:
return False
# IP address filter
for token in string.replace('\t', ' ').split(' '):
... | def is_http_log_entry(self, string):
"""
Determines if a log entry is an HTTP-formatted log string or not.
"""
# Debug event filter
if 'Zappa Event' in string:
return False
# IP address filter
for token in string.replace('\t', ' ').split(' '):
... | [
"Determines",
"if",
"a",
"log",
"entry",
"is",
"an",
"HTTP",
"-",
"formatted",
"log",
"string",
"or",
"not",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2516-L2532 | [
"def",
"is_http_log_entry",
"(",
"self",
",",
"string",
")",
":",
"# Debug event filter",
"if",
"'Zappa Event'",
"in",
"string",
":",
"return",
"False",
"# IP address filter",
"for",
"token",
"in",
"string",
".",
"replace",
"(",
"'\\t'",
",",
"' '",
")",
".",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.colorize_log_entry | Apply various heuristics to return a colorized version of a string.
If these fail, simply return the string in plaintext. | zappa/cli.py | def colorize_log_entry(self, string):
"""
Apply various heuristics to return a colorized version of a string.
If these fail, simply return the string in plaintext.
"""
final_string = string
try:
# First, do stuff in square brackets
inside_squares... | def colorize_log_entry(self, string):
"""
Apply various heuristics to return a colorized version of a string.
If these fail, simply return the string in plaintext.
"""
final_string = string
try:
# First, do stuff in square brackets
inside_squares... | [
"Apply",
"various",
"heuristics",
"to",
"return",
"a",
"colorized",
"version",
"of",
"a",
"string",
".",
"If",
"these",
"fail",
"simply",
"return",
"the",
"string",
"in",
"plaintext",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2537-L2603 | [
"def",
"colorize_log_entry",
"(",
"self",
",",
"string",
")",
":",
"final_string",
"=",
"string",
"try",
":",
"# First, do stuff in square brackets",
"inside_squares",
"=",
"re",
".",
"findall",
"(",
"r'\\[([^]]*)\\]'",
",",
"string",
")",
"for",
"token",
"in",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.execute_prebuild_script | Parse and execute the prebuild_script from the zappa_settings. | zappa/cli.py | def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1)
try: # Prefer prebuild script in working directory
if pb_mod_path.count('.') >= 1: # Prebuild sc... | def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1)
try: # Prefer prebuild script in working directory
if pb_mod_path.count('.') >= 1: # Prebuild sc... | [
"Parse",
"and",
"execute",
"the",
"prebuild_script",
"from",
"the",
"zappa_settings",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2605-L2641 | [
"def",
"execute_prebuild_script",
"(",
"self",
")",
":",
"(",
"pb_mod_path",
",",
"pb_func",
")",
"=",
"self",
".",
"prebuild_script",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"# Prefer prebuild script in working directory",
"if",
"pb_mod_path",
"."... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.collision_warning | Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events. | zappa/cli.py | def collision_warning(self, item):
"""
Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events.
"""
namespace_collisions = [
"zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt.... | def collision_warning(self, item):
"""
Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events.
"""
namespace_collisions = [
"zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt.... | [
"Given",
"a",
"string",
"print",
"a",
"warning",
"if",
"this",
"could",
"collide",
"with",
"a",
"Zappa",
"core",
"package",
"module",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2643-L2661 | [
"def",
"collision_warning",
"(",
"self",
",",
"item",
")",
":",
"namespace_collisions",
"=",
"[",
"\"zappa.\"",
",",
"\"wsgi.\"",
",",
"\"middleware.\"",
",",
"\"handler.\"",
",",
"\"util.\"",
",",
"\"letsencrypt.\"",
",",
"\"cli.\"",
"]",
"for",
"namespace_collis... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.check_venv | Ensure we're inside a virtualenv. | zappa/cli.py | def check_venv(self):
""" Ensure we're inside a virtualenv. """
if self.zappa:
venv = self.zappa.get_current_venv()
else:
# Just for `init`, when we don't have settings yet.
venv = Zappa.get_current_venv()
if not venv:
raise ClickException(... | def check_venv(self):
""" Ensure we're inside a virtualenv. """
if self.zappa:
venv = self.zappa.get_current_venv()
else:
# Just for `init`, when we don't have settings yet.
venv = Zappa.get_current_venv()
if not venv:
raise ClickException(... | [
"Ensure",
"we",
"re",
"inside",
"a",
"virtualenv",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2679-L2689 | [
"def",
"check_venv",
"(",
"self",
")",
":",
"if",
"self",
".",
"zappa",
":",
"venv",
"=",
"self",
".",
"zappa",
".",
"get_current_venv",
"(",
")",
"else",
":",
"# Just for `init`, when we don't have settings yet.",
"venv",
"=",
"Zappa",
".",
"get_current_venv",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.silence | Route all stdout to null. | zappa/cli.py | def silence(self):
"""
Route all stdout to null.
"""
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w') | def silence(self):
"""
Route all stdout to null.
"""
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w') | [
"Route",
"all",
"stdout",
"to",
"null",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2691-L2697 | [
"def",
"silence",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"sys",
".",
"stderr",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | ZappaCLI.touch_endpoint | Test the deployed endpoint with a GET request. | zappa/cli.py | def touch_endpoint(self, endpoint_url):
"""
Test the deployed endpoint with a GET request.
"""
# Private APIGW endpoints most likely can't be reached by a deployer
# unless they're connected to the VPC by VPN. Instead of trying
# connect to the service, print a warning a... | def touch_endpoint(self, endpoint_url):
"""
Test the deployed endpoint with a GET request.
"""
# Private APIGW endpoints most likely can't be reached by a deployer
# unless they're connected to the VPC by VPN. Instead of trying
# connect to the service, print a warning a... | [
"Test",
"the",
"deployed",
"endpoint",
"with",
"a",
"GET",
"request",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2699-L2738 | [
"def",
"touch_endpoint",
"(",
"self",
",",
"endpoint_url",
")",
":",
"# Private APIGW endpoints most likely can't be reached by a deployer",
"# unless they're connected to the VPC by VPN. Instead of trying",
"# connect to the service, print a warning and let the user know",
"# to check it manu... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | all_casings | Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python | zappa/middleware.py | def all_casings(input_string):
"""
Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
"""
if not input_string:
yield ""
else:
first = input_string[:1]
if fi... | def all_casings(input_string):
"""
Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
"""
if not input_string:
yield ""
else:
first = input_string[:1]
if fi... | [
"Permute",
"all",
"casings",
"of",
"a",
"given",
"string",
"."
] | Miserlou/Zappa | python | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/middleware.py#L4-L21 | [
"def",
"all_casings",
"(",
"input_string",
")",
":",
"if",
"not",
"input_string",
":",
"yield",
"\"\"",
"else",
":",
"first",
"=",
"input_string",
"[",
":",
"1",
"]",
"if",
"first",
".",
"lower",
"(",
")",
"==",
"first",
".",
"upper",
"(",
")",
":",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 |
train | TaskDB.status_count | return a dict | pyspider/database/sqlite/taskdb.py | def status_count(self, project):
'''
return a dict
'''
result = dict()
if project not in self.projects:
self._list_project()
if project not in self.projects:
return result
tablename = self._tablename(project)
for status, count in se... | def status_count(self, project):
'''
return a dict
'''
result = dict()
if project not in self.projects:
self._list_project()
if project not in self.projects:
return result
tablename = self._tablename(project)
for status, count in se... | [
"return",
"a",
"dict"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/sqlite/taskdb.py#L85-L98 | [
"def",
"status_count",
"(",
"self",
",",
"project",
")",
":",
"result",
"=",
"dict",
"(",
")",
"if",
"project",
"not",
"in",
"self",
".",
"projects",
":",
"self",
".",
"_list_project",
"(",
")",
"if",
"project",
"not",
"in",
"self",
".",
"projects",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | get_encoding | Get encoding from request headers or page head. | pyspider/libs/response.py | def get_encoding(headers, content):
"""Get encoding from request headers or page head."""
encoding = None
content_type = headers.get('content-type')
if content_type:
_, params = cgi.parse_header(content_type)
if 'charset' in params:
encoding = params['charset'].strip("'\"")
... | def get_encoding(headers, content):
"""Get encoding from request headers or page head."""
encoding = None
content_type = headers.get('content-type')
if content_type:
_, params = cgi.parse_header(content_type)
if 'charset' in params:
encoding = params['charset'].strip("'\"")
... | [
"Get",
"encoding",
"from",
"request",
"headers",
"or",
"page",
"head",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L211-L234 | [
"def",
"get_encoding",
"(",
"headers",
",",
"content",
")",
":",
"encoding",
"=",
"None",
"content_type",
"=",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"content_type",
":",
"_",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"content_... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.encoding | encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available. | pyspider/libs/response.py | def encoding(self):
"""
encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available.
"""
if hasattr(self, '_encoding'):
return self._encoding
# content is unicode
if isinst... | def encoding(self):
"""
encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available.
"""
if hasattr(self, '_encoding'):
return self._encoding
# content is unicode
if isinst... | [
"encoding",
"of",
"Response",
".",
"content",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L61-L86 | [
"def",
"encoding",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_encoding'",
")",
":",
"return",
"self",
".",
"_encoding",
"# content is unicode",
"if",
"isinstance",
"(",
"self",
".",
"content",
",",
"six",
".",
"text_type",
")",
":",
"re... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.text | Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed. | pyspider/libs/response.py | def text(self):
"""
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed.
"""
if hasattr(self, '_text') and self._text:
return self._text
if not self.content:
return u'... | def text(self):
"""
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed.
"""
if hasattr(self, '_text') and self._text:
return self._text
if not self.content:
return u'... | [
"Content",
"of",
"the",
"response",
"in",
"unicode",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L98-L126 | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_text'",
")",
"and",
"self",
".",
"_text",
":",
"return",
"self",
".",
"_text",
"if",
"not",
"self",
".",
"content",
":",
"return",
"u''",
"if",
"isinstance",
"(",
"self",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.json | Returns the json-encoded content of the response, if any. | pyspider/libs/response.py | def json(self):
"""Returns the json-encoded content of the response, if any."""
if hasattr(self, '_json'):
return self._json
try:
self._json = json.loads(self.text or self.content)
except ValueError:
self._json = None
return self._json | def json(self):
"""Returns the json-encoded content of the response, if any."""
if hasattr(self, '_json'):
return self._json
try:
self._json = json.loads(self.text or self.content)
except ValueError:
self._json = None
return self._json | [
"Returns",
"the",
"json",
"-",
"encoded",
"content",
"of",
"the",
"response",
"if",
"any",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L129-L137 | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_json'",
")",
":",
"return",
"self",
".",
"_json",
"try",
":",
"self",
".",
"_json",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"text",
"or",
"self",
".",
"content",
")"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.doc | Returns a PyQuery object of the response's content | pyspider/libs/response.py | def doc(self):
"""Returns a PyQuery object of the response's content"""
if hasattr(self, '_doc'):
return self._doc
elements = self.etree
doc = self._doc = PyQuery(elements)
doc.make_links_absolute(utils.text(self.url))
return doc | def doc(self):
"""Returns a PyQuery object of the response's content"""
if hasattr(self, '_doc'):
return self._doc
elements = self.etree
doc = self._doc = PyQuery(elements)
doc.make_links_absolute(utils.text(self.url))
return doc | [
"Returns",
"a",
"PyQuery",
"object",
"of",
"the",
"response",
"s",
"content"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L140-L147 | [
"def",
"doc",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_doc'",
")",
":",
"return",
"self",
".",
"_doc",
"elements",
"=",
"self",
".",
"etree",
"doc",
"=",
"self",
".",
"_doc",
"=",
"PyQuery",
"(",
"elements",
")",
"doc",
".",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.etree | Returns a lxml object of the response's content that can be selected by xpath | pyspider/libs/response.py | def etree(self):
"""Returns a lxml object of the response's content that can be selected by xpath"""
if not hasattr(self, '_elements'):
try:
parser = lxml.html.HTMLParser(encoding=self.encoding)
self._elements = lxml.html.fromstring(self.content, parser=parser... | def etree(self):
"""Returns a lxml object of the response's content that can be selected by xpath"""
if not hasattr(self, '_elements'):
try:
parser = lxml.html.HTMLParser(encoding=self.encoding)
self._elements = lxml.html.fromstring(self.content, parser=parser... | [
"Returns",
"a",
"lxml",
"object",
"of",
"the",
"response",
"s",
"content",
"that",
"can",
"be",
"selected",
"by",
"xpath"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L150-L163 | [
"def",
"etree",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_elements'",
")",
":",
"try",
":",
"parser",
"=",
"lxml",
".",
"html",
".",
"HTMLParser",
"(",
"encoding",
"=",
"self",
".",
"encoding",
")",
"self",
".",
"_elements",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Response.raise_for_status | Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred. | pyspider/libs/response.py | def raise_for_status(self, allow_redirects=True):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""
if self.status_code == 304:
return
elif self.error:
if self.traceback:
six.reraise(Exception, Exception(self.error), Traceback.... | def raise_for_status(self, allow_redirects=True):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""
if self.status_code == 304:
return
elif self.error:
if self.traceback:
six.reraise(Exception, Exception(self.error), Traceback.... | [
"Raises",
"stored",
":",
"class",
":",
"HTTPError",
"or",
":",
"class",
":",
"URLError",
"if",
"one",
"occurred",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L165-L184 | [
"def",
"raise_for_status",
"(",
"self",
",",
"allow_redirects",
"=",
"True",
")",
":",
"if",
"self",
".",
"status_code",
"==",
"304",
":",
"return",
"elif",
"self",
".",
"error",
":",
"if",
"self",
".",
"traceback",
":",
"six",
".",
"reraise",
"(",
"Ex... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | not_send_status | Do not send process status package back to scheduler.
It's used by callbacks like on_message, on_result etc... | pyspider/libs/base_handler.py | def not_send_status(func):
"""
Do not send process status package back to scheduler.
It's used by callbacks like on_message, on_result etc...
"""
@functools.wraps(func)
def wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.... | def not_send_status(func):
"""
Do not send process status package back to scheduler.
It's used by callbacks like on_message, on_result etc...
"""
@functools.wraps(func)
def wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.... | [
"Do",
"not",
"send",
"process",
"status",
"package",
"back",
"to",
"scheduler",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L35-L46 | [
"def",
"not_send_status",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"response",
",",
"task",
")",
":",
"self",
".",
"_extinfo",
"[",
"'not_send_status'",
"]",
"=",
"True",
"function",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | config | A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config. | pyspider/libs/base_handler.py | def config(_config=None, **kwargs):
"""
A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config.
"""
if _config is None:
_config = {}
_config.update(kwargs)
def wrapper(func):
func._config = _config
re... | def config(_config=None, **kwargs):
"""
A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config.
"""
if _config is None:
_config = {}
_config.update(kwargs)
def wrapper(func):
func._config = _config
re... | [
"A",
"decorator",
"for",
"setting",
"the",
"default",
"kwargs",
"of",
"BaseHandler",
".",
"crawl",
".",
"Any",
"self",
".",
"crawl",
"with",
"this",
"callback",
"will",
"use",
"this",
"config",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L49-L61 | [
"def",
"config",
"(",
"_config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_config",
"is",
"None",
":",
"_config",
"=",
"{",
"}",
"_config",
".",
"update",
"(",
"kwargs",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"func",
".",
"_c... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | every | method will been called every minutes or seconds | pyspider/libs/base_handler.py | def every(minutes=NOTSET, seconds=NOTSET):
"""
method will been called every minutes or seconds
"""
def wrapper(func):
# mark the function with variable 'is_cronjob=True', the function would be
# collected into the list Handler._cron_jobs by meta class
func.is_cronjob = True
... | def every(minutes=NOTSET, seconds=NOTSET):
"""
method will been called every minutes or seconds
"""
def wrapper(func):
# mark the function with variable 'is_cronjob=True', the function would be
# collected into the list Handler._cron_jobs by meta class
func.is_cronjob = True
... | [
"method",
"will",
"been",
"called",
"every",
"minutes",
"or",
"seconds"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L68-L97 | [
"def",
"every",
"(",
"minutes",
"=",
"NOTSET",
",",
"seconds",
"=",
"NOTSET",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"# mark the function with variable 'is_cronjob=True', the function would be",
"# collected into the list Handler._cron_jobs by meta class",
"func",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | catch_error | Catch errors of rabbitmq then reconnect | pyspider/message_queue/rabbitmq.py | def catch_error(func):
"""Catch errors of rabbitmq then reconnect"""
import amqp
try:
import pika.exceptions
connect_exceptions = (
pika.exceptions.ConnectionClosed,
pika.exceptions.AMQPConnectionError,
)
except ImportError:
connect_exceptions = ()... | def catch_error(func):
"""Catch errors of rabbitmq then reconnect"""
import amqp
try:
import pika.exceptions
connect_exceptions = (
pika.exceptions.ConnectionClosed,
pika.exceptions.AMQPConnectionError,
)
except ImportError:
connect_exceptions = ()... | [
"Catch",
"errors",
"of",
"rabbitmq",
"then",
"reconnect"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/rabbitmq.py#L24-L49 | [
"def",
"catch_error",
"(",
"func",
")",
":",
"import",
"amqp",
"try",
":",
"import",
"pika",
".",
"exceptions",
"connect_exceptions",
"=",
"(",
"pika",
".",
"exceptions",
".",
"ConnectionClosed",
",",
"pika",
".",
"exceptions",
".",
"AMQPConnectionError",
",",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | PikaQueue.reconnect | Reconnect to rabbitmq server | pyspider/message_queue/rabbitmq.py | def reconnect(self):
"""Reconnect to rabbitmq server"""
import pika
import pika.exceptions
self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))
self.channel = self.connection.channel()
try:
self.channel.queue_declare(self.name)
... | def reconnect(self):
"""Reconnect to rabbitmq server"""
import pika
import pika.exceptions
self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))
self.channel = self.connection.channel()
try:
self.channel.queue_declare(self.name)
... | [
"Reconnect",
"to",
"rabbitmq",
"server"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/rabbitmq.py#L91-L102 | [
"def",
"reconnect",
"(",
"self",
")",
":",
"import",
"pika",
"import",
"pika",
".",
"exceptions",
"self",
".",
"connection",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"URLParameters",
"(",
"self",
".",
"amqp_url",
")",
")",
"self",
".",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | AmqpQueue.reconnect | Reconnect to rabbitmq server | pyspider/message_queue/rabbitmq.py | def reconnect(self):
"""Reconnect to rabbitmq server"""
parsed = urlparse.urlparse(self.amqp_url)
port = parsed.port or 5672
self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port),
userid=parsed.username or 'guest',
... | def reconnect(self):
"""Reconnect to rabbitmq server"""
parsed = urlparse.urlparse(self.amqp_url)
port = parsed.port or 5672
self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port),
userid=parsed.username or 'guest',
... | [
"Reconnect",
"to",
"rabbitmq",
"server"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/rabbitmq.py#L224-L237 | [
"def",
"reconnect",
"(",
"self",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"self",
".",
"amqp_url",
")",
"port",
"=",
"parsed",
".",
"port",
"or",
"5672",
"self",
".",
"connection",
"=",
"amqp",
".",
"Connection",
"(",
"host",
"=",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskQueue.put | Put a task into task queue
when use heap sort, if we put tasks(with the same priority and exetime=0) into queue,
the queue is not a strict FIFO queue, but more like a FILO stack.
It is very possible that when there are continuous big flow, the speed of select is
slower than req... | pyspider/scheduler/task_queue.py | def put(self, taskid, priority=0, exetime=0):
"""
Put a task into task queue
when use heap sort, if we put tasks(with the same priority and exetime=0) into queue,
the queue is not a strict FIFO queue, but more like a FILO stack.
It is very possible that when there are co... | def put(self, taskid, priority=0, exetime=0):
"""
Put a task into task queue
when use heap sort, if we put tasks(with the same priority and exetime=0) into queue,
the queue is not a strict FIFO queue, but more like a FILO stack.
It is very possible that when there are co... | [
"Put",
"a",
"task",
"into",
"task",
"queue",
"when",
"use",
"heap",
"sort",
"if",
"we",
"put",
"tasks",
"(",
"with",
"the",
"same",
"priority",
"and",
"exetime",
"=",
"0",
")",
"into",
"queue",
"the",
"queue",
"is",
"not",
"a",
"strict",
"FIFO",
"que... | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L190-L225 | [
"def",
"put",
"(",
"self",
",",
"taskid",
",",
"priority",
"=",
"0",
",",
"exetime",
"=",
"0",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"task",
"=",
"InQueueTask",
"(",
"taskid",
",",
"priority",
",",
"exetime",
")",
"self",
".",
"mut... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskQueue.get | Get a task from queue when bucket available | pyspider/scheduler/task_queue.py | def get(self):
'''Get a task from queue when bucket available'''
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
... | def get(self):
'''Get a task from queue when bucket available'''
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
... | [
"Get",
"a",
"task",
"from",
"queue",
"when",
"bucket",
"available"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L227-L242 | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"bucket",
".",
"get",
"(",
")",
"<",
"1",
":",
"return",
"None",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"try",
":",
"task",
"=",
"self... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskQueue.done | Mark task done | pyspider/scheduler/task_queue.py | def done(self, taskid):
'''Mark task done'''
if taskid in self.processing:
self.mutex.acquire()
if taskid in self.processing:
del self.processing[taskid]
self.mutex.release()
return True
return False | def done(self, taskid):
'''Mark task done'''
if taskid in self.processing:
self.mutex.acquire()
if taskid in self.processing:
del self.processing[taskid]
self.mutex.release()
return True
return False | [
"Mark",
"task",
"done"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L244-L252 | [
"def",
"done",
"(",
"self",
",",
"taskid",
")",
":",
"if",
"taskid",
"in",
"self",
".",
"processing",
":",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"if",
"taskid",
"in",
"self",
".",
"processing",
":",
"del",
"self",
".",
"processing",
"[",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskQueue.is_processing | return True if taskid is in processing | pyspider/scheduler/task_queue.py | def is_processing(self, taskid):
'''
return True if taskid is in processing
'''
return taskid in self.processing and self.processing[taskid].taskid | def is_processing(self, taskid):
'''
return True if taskid is in processing
'''
return taskid in self.processing and self.processing[taskid].taskid | [
"return",
"True",
"if",
"taskid",
"is",
"in",
"processing"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L272-L276 | [
"def",
"is_processing",
"(",
"self",
",",
"taskid",
")",
":",
"return",
"taskid",
"in",
"self",
".",
"processing",
"and",
"self",
".",
"processing",
"[",
"taskid",
"]",
".",
"taskid"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProcessorResult.logstr | handler the log records to formatted string | pyspider/processor/processor.py | def logstr(self):
"""handler the log records to formatted string"""
result = []
formater = LogFormatter(color=False)
for record in self.logs:
if isinstance(record, six.string_types):
result.append(pretty_unicode(record))
else:
if r... | def logstr(self):
"""handler the log records to formatted string"""
result = []
formater = LogFormatter(color=False)
for record in self.logs:
if isinstance(record, six.string_types):
result.append(pretty_unicode(record))
else:
if r... | [
"handler",
"the",
"log",
"records",
"to",
"formatted",
"string"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/processor.py#L44-L59 | [
"def",
"logstr",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"formater",
"=",
"LogFormatter",
"(",
"color",
"=",
"False",
")",
"for",
"record",
"in",
"self",
".",
"logs",
":",
"if",
"isinstance",
"(",
"record",
",",
"six",
".",
"string_types",
")... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Processor.on_task | Deal one task | pyspider/processor/processor.py | def on_task(self, task, response):
'''Deal one task'''
start_time = time.time()
response = rebuild_response(response)
try:
assert 'taskid' in task, 'need taskid in task'
project = task['project']
updatetime = task.get('project_updatetime', None)
... | def on_task(self, task, response):
'''Deal one task'''
start_time = time.time()
response = rebuild_response(response)
try:
assert 'taskid' in task, 'need taskid in task'
project = task['project']
updatetime = task.get('project_updatetime', None)
... | [
"Deal",
"one",
"task"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/processor.py#L102-L203 | [
"def",
"on_task",
"(",
"self",
",",
"task",
",",
"response",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
"rebuild_response",
"(",
"response",
")",
"try",
":",
"assert",
"'taskid'",
"in",
"task",
",",
"'need taskid in task'"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Processor.run | Run loop | pyspider/processor/processor.py | def run(self):
'''Run loop'''
logger.info("processor starting...")
while not self._quit:
try:
task, response = self.inqueue.get(timeout=1)
self.on_task(task, response)
self._exceptions = 0
except Queue.Empty as e:
... | def run(self):
'''Run loop'''
logger.info("processor starting...")
while not self._quit:
try:
task, response = self.inqueue.get(timeout=1)
self.on_task(task, response)
self._exceptions = 0
except Queue.Empty as e:
... | [
"Run",
"loop"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/processor.py#L209-L229 | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"processor starting...\"",
")",
"while",
"not",
"self",
".",
"_quit",
":",
"try",
":",
"task",
",",
"response",
"=",
"self",
".",
"inqueue",
".",
"get",
"(",
"timeout",
"=",
"1",
")",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | connect_message_queue | create connection to message queue
name:
name of message queue
rabbitmq:
amqp://username:password@host:5672/%2F
see https://www.rabbitmq.com/uri-spec.html
beanstalk:
beanstalk://host:11300/
redis:
redis://host:6379/db
redis://host1:port1,host2:port2,...,... | pyspider/message_queue/__init__.py | def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True):
"""
create connection to message queue
name:
name of message queue
rabbitmq:
amqp://username:password@host:5672/%2F
see https://www.rabbitmq.com/uri-spec.html
beanstalk:
beanstalk://host:11300/
... | def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True):
"""
create connection to message queue
name:
name of message queue
rabbitmq:
amqp://username:password@host:5672/%2F
see https://www.rabbitmq.com/uri-spec.html
beanstalk:
beanstalk://host:11300/
... | [
"create",
"connection",
"to",
"message",
"queue"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/__init__.py#L16-L78 | [
"def",
"connect_message_queue",
"(",
"name",
",",
"url",
"=",
"None",
",",
"maxsize",
"=",
"0",
",",
"lazy_limit",
"=",
"True",
")",
":",
"if",
"not",
"url",
":",
"from",
"pyspider",
".",
"libs",
".",
"multiprocessing_queue",
"import",
"Queue",
"return",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | hide_me | Hide stack traceback of given stack | pyspider/libs/utils.py | def hide_me(tb, g=globals()):
"""Hide stack traceback of given stack"""
base_tb = tb
try:
while tb and tb.tb_frame.f_globals is not g:
tb = tb.tb_next
while tb and tb.tb_frame.f_globals is g:
tb = tb.tb_next
except Exception as e:
logging.exception(e)
... | def hide_me(tb, g=globals()):
"""Hide stack traceback of given stack"""
base_tb = tb
try:
while tb and tb.tb_frame.f_globals is not g:
tb = tb.tb_next
while tb and tb.tb_frame.f_globals is g:
tb = tb.tb_next
except Exception as e:
logging.exception(e)
... | [
"Hide",
"stack",
"traceback",
"of",
"given",
"stack"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L38-L51 | [
"def",
"hide_me",
"(",
"tb",
",",
"g",
"=",
"globals",
"(",
")",
")",
":",
"base_tb",
"=",
"tb",
"try",
":",
"while",
"tb",
"and",
"tb",
".",
"tb_frame",
".",
"f_globals",
"is",
"not",
"g",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"while",
"tb",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | run_in_subprocess | Run function in subprocess, return a Process object | pyspider/libs/utils.py | def run_in_subprocess(func, *args, **kwargs):
"""Run function in subprocess, return a Process object"""
from multiprocessing import Process
thread = Process(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread | def run_in_subprocess(func, *args, **kwargs):
"""Run function in subprocess, return a Process object"""
from multiprocessing import Process
thread = Process(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread | [
"Run",
"function",
"in",
"subprocess",
"return",
"a",
"Process",
"object"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L63-L69 | [
"def",
"run_in_subprocess",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"multiprocessing",
"import",
"Process",
"thread",
"=",
"Process",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | format_date | Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July 10, 1980") with
``full_format=True``.
This method is primarily intended for dates in... | pyspider/libs/utils.py | def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False):
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July ... | def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False):
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July ... | [
"Formats",
"the",
"given",
"date",
"(",
"which",
"should",
"be",
"GMT",
")",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L72-L130 | [
"def",
"format_date",
"(",
"date",
",",
"gmt_offset",
"=",
"0",
",",
"relative",
"=",
"True",
",",
"shorter",
"=",
"False",
",",
"full_format",
"=",
"False",
")",
":",
"if",
"not",
"date",
":",
"return",
"'-'",
"if",
"isinstance",
"(",
"date",
",",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | utf8 | Make sure string is utf8 encoded bytes.
If parameter is a object, object.__str__ will been called before encode as bytes | pyspider/libs/utils.py | def utf8(string):
"""
Make sure string is utf8 encoded bytes.
If parameter is a object, object.__str__ will been called before encode as bytes
"""
if isinstance(string, six.text_type):
return string.encode('utf8')
elif isinstance(string, six.binary_type):
return string
else:... | def utf8(string):
"""
Make sure string is utf8 encoded bytes.
If parameter is a object, object.__str__ will been called before encode as bytes
"""
if isinstance(string, six.text_type):
return string.encode('utf8')
elif isinstance(string, six.binary_type):
return string
else:... | [
"Make",
"sure",
"string",
"is",
"utf8",
"encoded",
"bytes",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L213-L224 | [
"def",
"utf8",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | text | Make sure string is unicode type, decode with given encoding if it's not.
If parameter is a object, object.__str__ will been called | pyspider/libs/utils.py | def text(string, encoding='utf8'):
"""
Make sure string is unicode type, decode with given encoding if it's not.
If parameter is a object, object.__str__ will been called
"""
if isinstance(string, six.text_type):
return string
elif isinstance(string, six.binary_type):
return str... | def text(string, encoding='utf8'):
"""
Make sure string is unicode type, decode with given encoding if it's not.
If parameter is a object, object.__str__ will been called
"""
if isinstance(string, six.text_type):
return string
elif isinstance(string, six.binary_type):
return str... | [
"Make",
"sure",
"string",
"is",
"unicode",
"type",
"decode",
"with",
"given",
"encoding",
"if",
"it",
"s",
"not",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L227-L238 | [
"def",
"text",
"(",
"string",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"elif",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"retur... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | pretty_unicode | Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed. | pyspider/libs/utils.py | def pretty_unicode(string):
"""
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decode('Latin-1').... | def pretty_unicode(string):
"""
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decode('Latin-1').... | [
"Make",
"sure",
"string",
"is",
"unicode",
"try",
"to",
"decode",
"with",
"utf8",
"or",
"unicode",
"escaped",
"string",
"if",
"failed",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L241-L250 | [
"def",
"pretty_unicode",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"try",
":",
"return",
"string",
".",
"decode",
"(",
"\"utf8\"",
")",
"except",
"UnicodeDecodeError",
":",
"retu... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | unicode_string | Make sure string is unicode, try to default with utf8, or base64 if failed.
can been decode by `decode_unicode_string` | pyspider/libs/utils.py | def unicode_string(string):
"""
Make sure string is unicode, try to default with utf8, or base64 if failed.
can been decode by `decode_unicode_string`
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
... | def unicode_string(string):
"""
Make sure string is unicode, try to default with utf8, or base64 if failed.
can been decode by `decode_unicode_string`
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
... | [
"Make",
"sure",
"string",
"is",
"unicode",
"try",
"to",
"default",
"with",
"utf8",
"or",
"base64",
"if",
"failed",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L253-L264 | [
"def",
"unicode_string",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"try",
":",
"return",
"string",
".",
"decode",
"(",
"\"utf8\"",
")",
"except",
"UnicodeDecodeError",
":",
"retu... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | unicode_dict | Make sure keys and values of dict is unicode. | pyspider/libs/utils.py | def unicode_dict(_dict):
"""
Make sure keys and values of dict is unicode.
"""
r = {}
for k, v in iteritems(_dict):
r[unicode_obj(k)] = unicode_obj(v)
return r | def unicode_dict(_dict):
"""
Make sure keys and values of dict is unicode.
"""
r = {}
for k, v in iteritems(_dict):
r[unicode_obj(k)] = unicode_obj(v)
return r | [
"Make",
"sure",
"keys",
"and",
"values",
"of",
"dict",
"is",
"unicode",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L267-L274 | [
"def",
"unicode_dict",
"(",
"_dict",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"_dict",
")",
":",
"r",
"[",
"unicode_obj",
"(",
"k",
")",
"]",
"=",
"unicode_obj",
"(",
"v",
")",
"return",
"r"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | unicode_obj | Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64.
Can been decode by `decode_unicode_obj` | pyspider/libs/utils.py | def unicode_obj(obj):
"""
Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64.
Can been decode by `decode_unicode_obj`
"""
if isinstance(obj, dict):
return unicode_dict(obj)
elif isinstance(obj, (list, tuple)):
return unicode_list(obj)
elif i... | def unicode_obj(obj):
"""
Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64.
Can been decode by `decode_unicode_obj`
"""
if isinstance(obj, dict):
return unicode_dict(obj)
elif isinstance(obj, (list, tuple)):
return unicode_list(obj)
elif i... | [
"Make",
"sure",
"keys",
"and",
"values",
"of",
"dict",
"/",
"list",
"/",
"tuple",
"is",
"unicode",
".",
"bytes",
"will",
"encode",
"in",
"base64",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L284-L304 | [
"def",
"unicode_obj",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"unicode_dict",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"unicode_list",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | decode_unicode_string | Decode string encoded by `unicode_string` | pyspider/libs/utils.py | def decode_unicode_string(string):
"""
Decode string encoded by `unicode_string`
"""
if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'):
return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')])
return string | def decode_unicode_string(string):
"""
Decode string encoded by `unicode_string`
"""
if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'):
return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')])
return string | [
"Decode",
"string",
"encoded",
"by",
"unicode_string"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L307-L313 | [
"def",
"decode_unicode_string",
"(",
"string",
")",
":",
"if",
"string",
".",
"startswith",
"(",
"'[BASE64-DATA]'",
")",
"and",
"string",
".",
"endswith",
"(",
"'[/BASE64-DATA]'",
")",
":",
"return",
"base64",
".",
"b64decode",
"(",
"string",
"[",
"len",
"("... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | decode_unicode_obj | Decode unicoded dict/list/tuple encoded by `unicode_obj` | pyspider/libs/utils.py | def decode_unicode_obj(obj):
"""
Decode unicoded dict/list/tuple encoded by `unicode_obj`
"""
if isinstance(obj, dict):
r = {}
for k, v in iteritems(obj):
r[decode_unicode_string(k)] = decode_unicode_obj(v)
return r
elif isinstance(obj, six.string_types):
... | def decode_unicode_obj(obj):
"""
Decode unicoded dict/list/tuple encoded by `unicode_obj`
"""
if isinstance(obj, dict):
r = {}
for k, v in iteritems(obj):
r[decode_unicode_string(k)] = decode_unicode_obj(v)
return r
elif isinstance(obj, six.string_types):
... | [
"Decode",
"unicoded",
"dict",
"/",
"list",
"/",
"tuple",
"encoded",
"by",
"unicode_obj"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L316-L330 | [
"def",
"decode_unicode_obj",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"obj",
")",
":",
"r",
"[",
"decode_unicode_string",
"(",
"k",
")",
"]",
"=... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | load_object | Load object from module | pyspider/libs/utils.py | def load_object(name):
"""Load object from module"""
if "." not in name:
raise Exception('load object need module.object')
module_name, object_name = name.rsplit('.', 1)
if six.PY2:
module = __import__(module_name, globals(), locals(), [utf8(object_name)], -1)
else:
module ... | def load_object(name):
"""Load object from module"""
if "." not in name:
raise Exception('load object need module.object')
module_name, object_name = name.rsplit('.', 1)
if six.PY2:
module = __import__(module_name, globals(), locals(), [utf8(object_name)], -1)
else:
module ... | [
"Load",
"object",
"from",
"module"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L359-L370 | [
"def",
"load_object",
"(",
"name",
")",
":",
"if",
"\".\"",
"not",
"in",
"name",
":",
"raise",
"Exception",
"(",
"'load object need module.object'",
")",
"module_name",
",",
"object_name",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"if",
"six",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | get_python_console | Return a interactive python console instance with caller's stack | pyspider/libs/utils.py | def get_python_console(namespace=None):
"""
Return a interactive python console instance with caller's stack
"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who star... | def get_python_console(namespace=None):
"""
Return a interactive python console instance with caller's stack
"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who star... | [
"Return",
"a",
"interactive",
"python",
"console",
"instance",
"with",
"caller",
"s",
"stack"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L373-L415 | [
"def",
"get_python_console",
"(",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"caller",
"=",
"frame",
".",
"f_back",
"if",
"not",
"caller",
":",
"l... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | python_console | Start a interactive python console with caller's stack | pyspider/libs/utils.py | def python_console(namespace=None):
"""Start a interactive python console with caller's stack"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who start this console.")
... | def python_console(namespace=None):
"""Start a interactive python console with caller's stack"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who start this console.")
... | [
"Start",
"a",
"interactive",
"python",
"console",
"with",
"caller",
"s",
"stack"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L418-L431 | [
"def",
"python_console",
"(",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"caller",
"=",
"frame",
".",
"f_back",
"if",
"not",
"caller",
":",
"loggi... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | WSGIXMLRPCApplication.handler | XMLRPC service for windmill browser core to communicate with | pyspider/libs/wsgi_xmlrpc.py | def handler(self, environ, start_response):
"""XMLRPC service for windmill browser core to communicate with"""
if environ['REQUEST_METHOD'] == 'POST':
return self.handle_POST(environ, start_response)
else:
start_response("400 Bad request", [('Content-Type', 'text/plain')... | def handler(self, environ, start_response):
"""XMLRPC service for windmill browser core to communicate with"""
if environ['REQUEST_METHOD'] == 'POST':
return self.handle_POST(environ, start_response)
else:
start_response("400 Bad request", [('Content-Type', 'text/plain')... | [
"XMLRPC",
"service",
"for",
"windmill",
"browser",
"core",
"to",
"communicate",
"with"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/wsgi_xmlrpc.py#L48-L55 | [
"def",
"handler",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'POST'",
":",
"return",
"self",
".",
"handle_POST",
"(",
"environ",
",",
"start_response",
")",
"else",
":",
"start_response... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | WSGIXMLRPCApplication.handle_POST | Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. | pyspider/libs/wsgi_xmlrpc.py | def handle_POST(self, environ, start_response):
"""Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
Most code taken from SimpleXMLRPCServer with modifications for wsgi and my... | def handle_POST(self, environ, start_response):
"""Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
Most code taken from SimpleXMLRPCServer with modifications for wsgi and my... | [
"Handles",
"the",
"HTTP",
"POST",
"request",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/wsgi_xmlrpc.py#L57-L92 | [
"def",
"handle_POST",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"try",
":",
"# Get arguments by reading body of request.",
"# We read this in chunks to avoid straining",
"# socket.read(); around the 10 or 15Mb mark, some platforms",
"# begin to have problems (bug #7... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | connect_database | create database object by url
mysql:
mysql+type://user:passwd@host:port/database
sqlite:
# relative path
sqlite+type:///path/to/database.db
# absolute path
sqlite+type:////path/to/database.db
# memory database
sqlite+type://
mongodb:
mongodb+t... | pyspider/database/__init__.py | def connect_database(url):
"""
create database object by url
mysql:
mysql+type://user:passwd@host:port/database
sqlite:
# relative path
sqlite+type:///path/to/database.db
# absolute path
sqlite+type:////path/to/database.db
# memory database
sqlite... | def connect_database(url):
"""
create database object by url
mysql:
mysql+type://user:passwd@host:port/database
sqlite:
# relative path
sqlite+type:///path/to/database.db
# absolute path
sqlite+type:////path/to/database.db
# memory database
sqlite... | [
"create",
"database",
"object",
"by",
"url"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/__init__.py#L11-L46 | [
"def",
"connect_database",
"(",
"url",
")",
":",
"db",
"=",
"_connect_database",
"(",
"url",
")",
"db",
".",
"copy",
"=",
"lambda",
":",
"_connect_database",
"(",
"url",
")",
"return",
"db"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._update_projects | Check project update | pyspider/scheduler/scheduler.py | def _update_projects(self):
'''Check project update'''
now = time.time()
if (
not self._force_update_project
and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now
):
return
for project in self.projectdb.check_update(self._l... | def _update_projects(self):
'''Check project update'''
now = time.time()
if (
not self._force_update_project
and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now
):
return
for project in self.projectdb.check_update(self._l... | [
"Check",
"project",
"update"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L206-L218 | [
"def",
"_update_projects",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"(",
"not",
"self",
".",
"_force_update_project",
"and",
"self",
".",
"_last_update_project",
"+",
"self",
".",
"UPDATE_PROJECT_INTERVAL",
">",
"now",
")",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._update_project | update one project | pyspider/scheduler/scheduler.py | def _update_project(self, project):
'''update one project'''
if project['name'] not in self.projects:
self.projects[project['name']] = Project(self, project)
else:
self.projects[project['name']].update(project)
project = self.projects[project['name']]
if... | def _update_project(self, project):
'''update one project'''
if project['name'] not in self.projects:
self.projects[project['name']] = Project(self, project)
else:
self.projects[project['name']].update(project)
project = self.projects[project['name']]
if... | [
"update",
"one",
"project"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L222-L259 | [
"def",
"_update_project",
"(",
"self",
",",
"project",
")",
":",
"if",
"project",
"[",
"'name'",
"]",
"not",
"in",
"self",
".",
"projects",
":",
"self",
".",
"projects",
"[",
"project",
"[",
"'name'",
"]",
"]",
"=",
"Project",
"(",
"self",
",",
"proj... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._load_tasks | load tasks from database | pyspider/scheduler/scheduler.py | def _load_tasks(self, project):
'''load tasks from database'''
task_queue = project.task_queue
for task in self.taskdb.load_tasks(
self.taskdb.ACTIVE, project.name, self.scheduler_task_fields
):
taskid = task['taskid']
_schedule = task.get('schedu... | def _load_tasks(self, project):
'''load tasks from database'''
task_queue = project.task_queue
for task in self.taskdb.load_tasks(
self.taskdb.ACTIVE, project.name, self.scheduler_task_fields
):
taskid = task['taskid']
_schedule = task.get('schedu... | [
"load",
"tasks",
"from",
"database"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L263-L280 | [
"def",
"_load_tasks",
"(",
"self",
",",
"project",
")",
":",
"task_queue",
"=",
"project",
".",
"task_queue",
"for",
"task",
"in",
"self",
".",
"taskdb",
".",
"load_tasks",
"(",
"self",
".",
"taskdb",
".",
"ACTIVE",
",",
"project",
".",
"name",
",",
"s... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.task_verify | return False if any of 'taskid', 'project', 'url' is not in task dict
or project in not in task_queue | pyspider/scheduler/scheduler.py | def task_verify(self, task):
'''
return False if any of 'taskid', 'project', 'url' is not in task dict
or project in not in task_queue
'''
for each in ('taskid', 'project', 'url', ):
if each not in task or not task[each]:
logger.error('... | def task_verify(self, task):
'''
return False if any of 'taskid', 'project', 'url' is not in task dict
or project in not in task_queue
'''
for each in ('taskid', 'project', 'url', ):
if each not in task or not task[each]:
logger.error('... | [
"return",
"False",
"if",
"any",
"of",
"taskid",
"project",
"url",
"is",
"not",
"in",
"task",
"dict",
"or",
"project",
"in",
"not",
"in",
"task_queue"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L297-L315 | [
"def",
"task_verify",
"(",
"self",
",",
"task",
")",
":",
"for",
"each",
"in",
"(",
"'taskid'",
",",
"'project'",
",",
"'url'",
",",
")",
":",
"if",
"each",
"not",
"in",
"task",
"or",
"not",
"task",
"[",
"each",
"]",
":",
"logger",
".",
"error",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.put_task | put task to task queue | pyspider/scheduler/scheduler.py | def put_task(self, task):
'''put task to task queue'''
_schedule = task.get('schedule', self.default_schedule)
self.projects[task['project']].task_queue.put(
task['taskid'],
priority=_schedule.get('priority', self.default_schedule['priority']),
exetime=_schedu... | def put_task(self, task):
'''put task to task queue'''
_schedule = task.get('schedule', self.default_schedule)
self.projects[task['project']].task_queue.put(
task['taskid'],
priority=_schedule.get('priority', self.default_schedule['priority']),
exetime=_schedu... | [
"put",
"task",
"to",
"task",
"queue"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L325-L332 | [
"def",
"put_task",
"(",
"self",
",",
"task",
")",
":",
"_schedule",
"=",
"task",
".",
"get",
"(",
"'schedule'",
",",
"self",
".",
"default_schedule",
")",
"self",
".",
"projects",
"[",
"task",
"[",
"'project'",
"]",
"]",
".",
"task_queue",
".",
"put",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.send_task | dispatch task to fetcher
out queue may have size limit to prevent block, a send_buffer is used | pyspider/scheduler/scheduler.py | def send_task(self, task, force=True):
'''
dispatch task to fetcher
out queue may have size limit to prevent block, a send_buffer is used
'''
try:
self.out_queue.put_nowait(task)
except Queue.Full:
if force:
self._send_buffer.appen... | def send_task(self, task, force=True):
'''
dispatch task to fetcher
out queue may have size limit to prevent block, a send_buffer is used
'''
try:
self.out_queue.put_nowait(task)
except Queue.Full:
if force:
self._send_buffer.appen... | [
"dispatch",
"task",
"to",
"fetcher"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L334-L346 | [
"def",
"send_task",
"(",
"self",
",",
"task",
",",
"force",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"out_queue",
".",
"put_nowait",
"(",
"task",
")",
"except",
"Queue",
".",
"Full",
":",
"if",
"force",
":",
"self",
".",
"_send_buffer",
".",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._check_task_done | Check status queue | pyspider/scheduler/scheduler.py | def _check_task_done(self):
'''Check status queue'''
cnt = 0
try:
while True:
task = self.status_queue.get_nowait()
# check _on_get_info result here
if task.get('taskid') == '_on_get_info' and 'project' in task and 'track' in task:
... | def _check_task_done(self):
'''Check status queue'''
cnt = 0
try:
while True:
task = self.status_queue.get_nowait()
# check _on_get_info result here
if task.get('taskid') == '_on_get_info' and 'project' in task and 'track' in task:
... | [
"Check",
"status",
"queue"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L348-L370 | [
"def",
"_check_task_done",
"(",
"self",
")",
":",
"cnt",
"=",
"0",
"try",
":",
"while",
"True",
":",
"task",
"=",
"self",
".",
"status_queue",
".",
"get_nowait",
"(",
")",
"# check _on_get_info result here",
"if",
"task",
".",
"get",
"(",
"'taskid'",
")",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._check_request | Check new task queue | pyspider/scheduler/scheduler.py | def _check_request(self):
'''Check new task queue'''
# check _postpone_request first
todo = []
for task in self._postpone_request:
if task['project'] not in self.projects:
continue
if self.projects[task['project']].task_queue.is_processing(task['ta... | def _check_request(self):
'''Check new task queue'''
# check _postpone_request first
todo = []
for task in self._postpone_request:
if task['project'] not in self.projects:
continue
if self.projects[task['project']].task_queue.is_processing(task['ta... | [
"Check",
"new",
"task",
"queue"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L374-L417 | [
"def",
"_check_request",
"(",
"self",
")",
":",
"# check _postpone_request first",
"todo",
"=",
"[",
"]",
"for",
"task",
"in",
"self",
".",
"_postpone_request",
":",
"if",
"task",
"[",
"'project'",
"]",
"not",
"in",
"self",
".",
"projects",
":",
"continue",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._check_cronjob | Check projects cronjob tick, return True when a new tick is sended | pyspider/scheduler/scheduler.py | def _check_cronjob(self):
"""Check projects cronjob tick, return True when a new tick is sended"""
now = time.time()
self._last_tick = int(self._last_tick)
if now - self._last_tick < 1:
return False
self._last_tick += 1
for project in itervalues(self.projects)... | def _check_cronjob(self):
"""Check projects cronjob tick, return True when a new tick is sended"""
now = time.time()
self._last_tick = int(self._last_tick)
if now - self._last_tick < 1:
return False
self._last_tick += 1
for project in itervalues(self.projects)... | [
"Check",
"projects",
"cronjob",
"tick",
"return",
"True",
"when",
"a",
"new",
"tick",
"is",
"sended"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L419-L449 | [
"def",
"_check_cronjob",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_last_tick",
"=",
"int",
"(",
"self",
".",
"_last_tick",
")",
"if",
"now",
"-",
"self",
".",
"_last_tick",
"<",
"1",
":",
"return",
"False",
"s... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._check_select | Select task to fetch & process | pyspider/scheduler/scheduler.py | def _check_select(self):
'''Select task to fetch & process'''
while self._send_buffer:
_task = self._send_buffer.pop()
try:
# use force=False here to prevent automatic send_buffer append and get exception
self.send_task(_task, False)
ex... | def _check_select(self):
'''Select task to fetch & process'''
while self._send_buffer:
_task = self._send_buffer.pop()
try:
# use force=False here to prevent automatic send_buffer append and get exception
self.send_task(_task, False)
ex... | [
"Select",
"task",
"to",
"fetch",
"&",
"process"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L463-L566 | [
"def",
"_check_select",
"(",
"self",
")",
":",
"while",
"self",
".",
"_send_buffer",
":",
"_task",
"=",
"self",
".",
"_send_buffer",
".",
"pop",
"(",
")",
"try",
":",
"# use force=False here to prevent automatic send_buffer append and get exception",
"self",
".",
"s... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._dump_cnt | Dump counters to file | pyspider/scheduler/scheduler.py | def _dump_cnt(self):
'''Dump counters to file'''
self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all')) | def _dump_cnt(self):
'''Dump counters to file'''
self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all')) | [
"Dump",
"counters",
"to",
"file"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L616-L620 | [
"def",
"_dump_cnt",
"(",
"self",
")",
":",
"self",
".",
"_cnt",
"[",
"'1h'",
"]",
".",
"dump",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"'scheduler.1h'",
")",
")",
"self",
".",
"_cnt",
"[",
"'1d'",
"]",
".",
"dump"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._try_dump_cnt | Dump counters every 60 seconds | pyspider/scheduler/scheduler.py | def _try_dump_cnt(self):
'''Dump counters every 60 seconds'''
now = time.time()
if now - self._last_dump_cnt > 60:
self._last_dump_cnt = now
self._dump_cnt()
self._print_counter_log() | def _try_dump_cnt(self):
'''Dump counters every 60 seconds'''
now = time.time()
if now - self._last_dump_cnt > 60:
self._last_dump_cnt = now
self._dump_cnt()
self._print_counter_log() | [
"Dump",
"counters",
"every",
"60",
"seconds"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L622-L628 | [
"def",
"_try_dump_cnt",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"_last_dump_cnt",
">",
"60",
":",
"self",
".",
"_last_dump_cnt",
"=",
"now",
"self",
".",
"_dump_cnt",
"(",
")",
"self",
".",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler._check_delete | Check project delete | pyspider/scheduler/scheduler.py | def _check_delete(self):
'''Check project delete'''
now = time.time()
for project in list(itervalues(self.projects)):
if project.db_status != 'STOP':
continue
if now - project.updatetime < self.DELETE_TIME:
continue
if 'delete' ... | def _check_delete(self):
'''Check project delete'''
now = time.time()
for project in list(itervalues(self.projects)):
if project.db_status != 'STOP':
continue
if now - project.updatetime < self.DELETE_TIME:
continue
if 'delete' ... | [
"Check",
"project",
"delete"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L630-L648 | [
"def",
"_check_delete",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"project",
"in",
"list",
"(",
"itervalues",
"(",
"self",
".",
"projects",
")",
")",
":",
"if",
"project",
".",
"db_status",
"!=",
"'STOP'",
":",
"continu... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.quit | Set quit signal | pyspider/scheduler/scheduler.py | def quit(self):
'''Set quit signal'''
self._quit = True
# stop xmlrpc server
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop) | def quit(self):
'''Set quit signal'''
self._quit = True
# stop xmlrpc server
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop) | [
"Set",
"quit",
"signal"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L653-L659 | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_quit",
"=",
"True",
"# stop xmlrpc server",
"if",
"hasattr",
"(",
"self",
",",
"'xmlrpc_server'",
")",
":",
"self",
".",
"xmlrpc_ioloop",
".",
"add_callback",
"(",
"self",
".",
"xmlrpc_server",
".",
"sto... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.run_once | comsume queues and feed tasks to fetcher, once | pyspider/scheduler/scheduler.py | def run_once(self):
'''comsume queues and feed tasks to fetcher, once'''
self._update_projects()
self._check_task_done()
self._check_request()
while self._check_cronjob():
pass
self._check_select()
self._check_delete()
self._try_dump_cnt() | def run_once(self):
'''comsume queues and feed tasks to fetcher, once'''
self._update_projects()
self._check_task_done()
self._check_request()
while self._check_cronjob():
pass
self._check_select()
self._check_delete()
self._try_dump_cnt() | [
"comsume",
"queues",
"and",
"feed",
"tasks",
"to",
"fetcher",
"once"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L661-L671 | [
"def",
"run_once",
"(",
"self",
")",
":",
"self",
".",
"_update_projects",
"(",
")",
"self",
".",
"_check_task_done",
"(",
")",
"self",
".",
"_check_request",
"(",
")",
"while",
"self",
".",
"_check_cronjob",
"(",
")",
":",
"pass",
"self",
".",
"_check_s... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.run | Start scheduler loop | pyspider/scheduler/scheduler.py | def run(self):
'''Start scheduler loop'''
logger.info("scheduler starting...")
while not self._quit:
try:
time.sleep(self.LOOP_INTERVAL)
self.run_once()
self._exceptions = 0
except KeyboardInterrupt:
break
... | def run(self):
'''Start scheduler loop'''
logger.info("scheduler starting...")
while not self._quit:
try:
time.sleep(self.LOOP_INTERVAL)
self.run_once()
self._exceptions = 0
except KeyboardInterrupt:
break
... | [
"Start",
"scheduler",
"loop"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L673-L692 | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"scheduler starting...\"",
")",
"while",
"not",
"self",
".",
"_quit",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"LOOP_INTERVAL",
")",
"self",
".",
"run_once",
"(",
")",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.xmlrpc_run | Start xmlrpc interface | pyspider/scheduler/scheduler.py | def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False):
'''Start xmlrpc interface'''
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
application = WSGIXMLRPCApplication()
application.register_function(self.quit, '_quit')
application.register_function(... | def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False):
'''Start xmlrpc interface'''
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
application = WSGIXMLRPCApplication()
application.register_function(self.quit, '_quit')
application.register_function(... | [
"Start",
"xmlrpc",
"interface"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L705-L811 | [
"def",
"xmlrpc_run",
"(",
"self",
",",
"port",
"=",
"23333",
",",
"bind",
"=",
"'127.0.0.1'",
",",
"logRequests",
"=",
"False",
")",
":",
"from",
"pyspider",
".",
"libs",
".",
"wsgi_xmlrpc",
"import",
"WSGIXMLRPCApplication",
"application",
"=",
"WSGIXMLRPCApp... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_new_request | Called when a new request is arrived | pyspider/scheduler/scheduler.py | def on_new_request(self, task):
'''Called when a new request is arrived'''
task['status'] = self.taskdb.ACTIVE
self.insert_task(task)
self.put_task(task)
project = task['project']
self._cnt['5m'].event((project, 'pending'), +1)
self._cnt['1h'].event((project, 'pe... | def on_new_request(self, task):
'''Called when a new request is arrived'''
task['status'] = self.taskdb.ACTIVE
self.insert_task(task)
self.put_task(task)
project = task['project']
self._cnt['5m'].event((project, 'pending'), +1)
self._cnt['1h'].event((project, 'pe... | [
"Called",
"when",
"a",
"new",
"request",
"is",
"arrived"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L825-L837 | [
"def",
"on_new_request",
"(",
"self",
",",
"task",
")",
":",
"task",
"[",
"'status'",
"]",
"=",
"self",
".",
"taskdb",
".",
"ACTIVE",
"self",
".",
"insert_task",
"(",
"task",
")",
"self",
".",
"put_task",
"(",
"task",
")",
"project",
"=",
"task",
"["... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_old_request | Called when a crawled task is arrived | pyspider/scheduler/scheduler.py | def on_old_request(self, task, old_task):
'''Called when a crawled task is arrived'''
now = time.time()
_schedule = task.get('schedule', self.default_schedule)
old_schedule = old_task.get('schedule', {})
if _schedule.get('force_update') and self.projects[task['project']].task_q... | def on_old_request(self, task, old_task):
'''Called when a crawled task is arrived'''
now = time.time()
_schedule = task.get('schedule', self.default_schedule)
old_schedule = old_task.get('schedule', {})
if _schedule.get('force_update') and self.projects[task['project']].task_q... | [
"Called",
"when",
"a",
"crawled",
"task",
"is",
"arrived"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L839-L887 | [
"def",
"on_old_request",
"(",
"self",
",",
"task",
",",
"old_task",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"_schedule",
"=",
"task",
".",
"get",
"(",
"'schedule'",
",",
"self",
".",
"default_schedule",
")",
"old_schedule",
"=",
"old_task",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_task_status | Called when a status pack is arrived | pyspider/scheduler/scheduler.py | def on_task_status(self, task):
'''Called when a status pack is arrived'''
try:
procesok = task['track']['process']['ok']
if not self.projects[task['project']].task_queue.done(task['taskid']):
logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', ta... | def on_task_status(self, task):
'''Called when a status pack is arrived'''
try:
procesok = task['track']['process']['ok']
if not self.projects[task['project']].task_queue.done(task['taskid']):
logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', ta... | [
"Called",
"when",
"a",
"status",
"pack",
"is",
"arrived"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L889-L912 | [
"def",
"on_task_status",
"(",
"self",
",",
"task",
")",
":",
"try",
":",
"procesok",
"=",
"task",
"[",
"'track'",
"]",
"[",
"'process'",
"]",
"[",
"'ok'",
"]",
"if",
"not",
"self",
".",
"projects",
"[",
"task",
"[",
"'project'",
"]",
"]",
".",
"tas... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_task_done | Called when a task is done and success, called by `on_task_status` | pyspider/scheduler/scheduler.py | def on_task_done(self, task):
'''Called when a task is done and success, called by `on_task_status`'''
task['status'] = self.taskdb.SUCCESS
task['lastcrawltime'] = time.time()
if 'schedule' in task:
if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
... | def on_task_done(self, task):
'''Called when a task is done and success, called by `on_task_status`'''
task['status'] = self.taskdb.SUCCESS
task['lastcrawltime'] = time.time()
if 'schedule' in task:
if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
... | [
"Called",
"when",
"a",
"task",
"is",
"done",
"and",
"success",
"called",
"by",
"on_task_status"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L914-L935 | [
"def",
"on_task_done",
"(",
"self",
",",
"task",
")",
":",
"task",
"[",
"'status'",
"]",
"=",
"self",
".",
"taskdb",
".",
"SUCCESS",
"task",
"[",
"'lastcrawltime'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"if",
"'schedule'",
"in",
"task",
":",
"if",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_task_failed | Called when a task is failed, called by `on_task_status` | pyspider/scheduler/scheduler.py | def on_task_failed(self, task):
'''Called when a task is failed, called by `on_task_status`'''
if 'schedule' not in task:
old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule'])
if old_task is None:
logging.error('unknown status pack... | def on_task_failed(self, task):
'''Called when a task is failed, called by `on_task_status`'''
if 'schedule' not in task:
old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule'])
if old_task is None:
logging.error('unknown status pack... | [
"Called",
"when",
"a",
"task",
"is",
"failed",
"called",
"by",
"on_task_status"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L937-L988 | [
"def",
"on_task_failed",
"(",
"self",
",",
"task",
")",
":",
"if",
"'schedule'",
"not",
"in",
"task",
":",
"old_task",
"=",
"self",
".",
"taskdb",
".",
"get_task",
"(",
"task",
"[",
"'project'",
"]",
",",
"task",
"[",
"'taskid'",
"]",
",",
"fields",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Scheduler.on_select_task | Called when a task is selected to fetch & process | pyspider/scheduler/scheduler.py | def on_select_task(self, task):
'''Called when a task is selected to fetch & process'''
# inject informations about project
logger.info('select %(project)s:%(taskid)s %(url)s', task)
project_info = self.projects.get(task['project'])
assert project_info, 'no such project'
... | def on_select_task(self, task):
'''Called when a task is selected to fetch & process'''
# inject informations about project
logger.info('select %(project)s:%(taskid)s %(url)s', task)
project_info = self.projects.get(task['project'])
assert project_info, 'no such project'
... | [
"Called",
"when",
"a",
"task",
"is",
"selected",
"to",
"fetch",
"&",
"process"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L990-L1008 | [
"def",
"on_select_task",
"(",
"self",
",",
"task",
")",
":",
"# inject informations about project",
"logger",
".",
"info",
"(",
"'select %(project)s:%(taskid)s %(url)s'",
",",
"task",
")",
"project_info",
"=",
"self",
".",
"projects",
".",
"get",
"(",
"task",
"[",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | OneScheduler._check_select | interactive mode of select tasks | pyspider/scheduler/scheduler.py | def _check_select(self):
"""
interactive mode of select tasks
"""
if not self.interactive:
return super(OneScheduler, self)._check_select()
# waiting for running tasks
if self.running_task > 0:
return
is_crawled = []
def run(proj... | def _check_select(self):
"""
interactive mode of select tasks
"""
if not self.interactive:
return super(OneScheduler, self)._check_select()
# waiting for running tasks
if self.running_task > 0:
return
is_crawled = []
def run(proj... | [
"interactive",
"mode",
"of",
"select",
"tasks"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1022-L1104 | [
"def",
"_check_select",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"interactive",
":",
"return",
"super",
"(",
"OneScheduler",
",",
"self",
")",
".",
"_check_select",
"(",
")",
"# waiting for running tasks",
"if",
"self",
".",
"running_task",
">",
"0",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | OneScheduler.on_task_status | Ignore not processing error in interactive mode | pyspider/scheduler/scheduler.py | def on_task_status(self, task):
"""Ignore not processing error in interactive mode"""
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status... | def on_task_status(self, task):
"""Ignore not processing error in interactive mode"""
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status... | [
"Ignore",
"not",
"processing",
"error",
"in",
"interactive",
"mode"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1112-L1134 | [
"def",
"on_task_status",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"interactive",
":",
"super",
"(",
"OneScheduler",
",",
"self",
")",
".",
"on_task_status",
"(",
"task",
")",
"try",
":",
"procesok",
"=",
"task",
"[",
"'track'",
"]"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager.build_module | Build project script as module | pyspider/processor/project_module.py | def build_module(project, env=None):
'''Build project script as module'''
from pyspider.libs import base_handler
assert 'name' in project, 'need name of project'
assert 'script' in project, 'need script of project'
if env is None:
env = {}
# fix for old non-p... | def build_module(project, env=None):
'''Build project script as module'''
from pyspider.libs import base_handler
assert 'name' in project, 'need name of project'
assert 'script' in project, 'need script of project'
if env is None:
env = {}
# fix for old non-p... | [
"Build",
"project",
"script",
"as",
"module"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L32-L87 | [
"def",
"build_module",
"(",
"project",
",",
"env",
"=",
"None",
")",
":",
"from",
"pyspider",
".",
"libs",
"import",
"base_handler",
"assert",
"'name'",
"in",
"project",
",",
"'need name of project'",
"assert",
"'script'",
"in",
"project",
",",
"'need script of ... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager._need_update | Check if project_name need update | pyspider/processor/project_module.py | def _need_update(self, project_name, updatetime=None, md5sum=None):
'''Check if project_name need update'''
if project_name not in self.projects:
return True
elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'):
return True
elif updatetime a... | def _need_update(self, project_name, updatetime=None, md5sum=None):
'''Check if project_name need update'''
if project_name not in self.projects:
return True
elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'):
return True
elif updatetime a... | [
"Check",
"if",
"project_name",
"need",
"update"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L96-L106 | [
"def",
"_need_update",
"(",
"self",
",",
"project_name",
",",
"updatetime",
"=",
"None",
",",
"md5sum",
"=",
"None",
")",
":",
"if",
"project_name",
"not",
"in",
"self",
".",
"projects",
":",
"return",
"True",
"elif",
"md5sum",
"and",
"md5sum",
"!=",
"se... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager._check_projects | Check projects by last update time | pyspider/processor/project_module.py | def _check_projects(self):
'''Check projects by last update time'''
for project in self.projectdb.check_update(self.last_check_projects,
['name', 'updatetime']):
if project['name'] not in self.projects:
continue
i... | def _check_projects(self):
'''Check projects by last update time'''
for project in self.projectdb.check_update(self.last_check_projects,
['name', 'updatetime']):
if project['name'] not in self.projects:
continue
i... | [
"Check",
"projects",
"by",
"last",
"update",
"time"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L108-L116 | [
"def",
"_check_projects",
"(",
"self",
")",
":",
"for",
"project",
"in",
"self",
".",
"projectdb",
".",
"check_update",
"(",
"self",
".",
"last_check_projects",
",",
"[",
"'name'",
",",
"'updatetime'",
"]",
")",
":",
"if",
"project",
"[",
"'name'",
"]",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager._update_project | Update one project from database | pyspider/processor/project_module.py | def _update_project(self, project_name):
'''Update one project from database'''
project = self.projectdb.get(project_name)
if not project:
return None
return self._load_project(project) | def _update_project(self, project_name):
'''Update one project from database'''
project = self.projectdb.get(project_name)
if not project:
return None
return self._load_project(project) | [
"Update",
"one",
"project",
"from",
"database"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L118-L123 | [
"def",
"_update_project",
"(",
"self",
",",
"project_name",
")",
":",
"project",
"=",
"self",
".",
"projectdb",
".",
"get",
"(",
"project_name",
")",
"if",
"not",
"project",
":",
"return",
"None",
"return",
"self",
".",
"_load_project",
"(",
"project",
")"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager._load_project | Load project into self.projects from project info dict | pyspider/processor/project_module.py | def _load_project(self, project):
'''Load project into self.projects from project info dict'''
try:
project['md5sum'] = utils.md5string(project['script'])
ret = self.build_module(project, self.env)
self.projects[project['name']] = ret
except Exception as e:
... | def _load_project(self, project):
'''Load project into self.projects from project info dict'''
try:
project['md5sum'] = utils.md5string(project['script'])
ret = self.build_module(project, self.env)
self.projects[project['name']] = ret
except Exception as e:
... | [
"Load",
"project",
"into",
"self",
".",
"projects",
"from",
"project",
"info",
"dict"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L125-L146 | [
"def",
"_load_project",
"(",
"self",
",",
"project",
")",
":",
"try",
":",
"project",
"[",
"'md5sum'",
"]",
"=",
"utils",
".",
"md5string",
"(",
"project",
"[",
"'script'",
"]",
")",
"ret",
"=",
"self",
".",
"build_module",
"(",
"project",
",",
"self",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | ProjectManager.get | get project data object, return None if not exists | pyspider/processor/project_module.py | def get(self, project_name, updatetime=None, md5sum=None):
'''get project data object, return None if not exists'''
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects()
if self._need_update(project_name, updatetime, md5sum):
sel... | def get(self, project_name, updatetime=None, md5sum=None):
'''get project data object, return None if not exists'''
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects()
if self._need_update(project_name, updatetime, md5sum):
sel... | [
"get",
"project",
"data",
"object",
"return",
"None",
"if",
"not",
"exists"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L148-L154 | [
"def",
"get",
"(",
"self",
",",
"project_name",
",",
"updatetime",
"=",
"None",
",",
"md5sum",
"=",
"None",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_check_projects",
">",
"self",
".",
"CHECK_PROJECTS_INTERVAL",
":",
"self",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | MockResponse.get_all | make cookie python 3 version use this instead of getheaders | pyspider/fetcher/cookie_utils.py | def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = []
return self._headers.get_list(name) or default | def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = []
return self._headers.get_list(name) or default | [
"make",
"cookie",
"python",
"3",
"version",
"use",
"this",
"instead",
"of",
"getheaders"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/cookie_utils.py#L23-L27 | [
"def",
"get_all",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"[",
"]",
"return",
"self",
".",
"_headers",
".",
"get_list",
"(",
"name",
")",
"or",
"default"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskDB.status_count | return a dict | pyspider/database/redis/taskdb.py | def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, status))
ret = pipe.execute()
result = {}
for status, count in enumerate(r... | def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, status))
ret = pipe.execute()
result = {}
for status, count in enumerate(r... | [
"return",
"a",
"dict"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/redis/taskdb.py#L118-L131 | [
"def",
"status_count",
"(",
"self",
",",
"project",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
".",
"pipeline",
"(",
"transaction",
"=",
"False",
")",
"for",
"status",
"in",
"range",
"(",
"1",
",",
"5",
")",
":",
"pipe",
".",
"scard",
"(",
"self"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | SharedCounter.increment | Increment the counter by n (default = 1) | pyspider/libs/multiprocessing_queue.py | def increment(self, n=1):
""" Increment the counter by n (default = 1) """
with self.count.get_lock():
self.count.value += n | def increment(self, n=1):
""" Increment the counter by n (default = 1) """
with self.count.get_lock():
self.count.value += n | [
"Increment",
"the",
"counter",
"by",
"n",
"(",
"default",
"=",
"1",
")"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/multiprocessing_queue.py#L25-L28 | [
"def",
"increment",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"with",
"self",
".",
"count",
".",
"get_lock",
"(",
")",
":",
"self",
".",
"count",
".",
"value",
"+=",
"n"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | TaskDB.refresh | Explicitly refresh one or more index, making all operations
performed since the last refresh available for search. | pyspider/database/elasticsearch/taskdb.py | def refresh(self):
"""
Explicitly refresh one or more index, making all operations
performed since the last refresh available for search.
"""
self._changed = False
self.es.indices.refresh(index=self.index) | def refresh(self):
"""
Explicitly refresh one or more index, making all operations
performed since the last refresh available for search.
"""
self._changed = False
self.es.indices.refresh(index=self.index) | [
"Explicitly",
"refresh",
"one",
"or",
"more",
"index",
"making",
"all",
"operations",
"performed",
"since",
"the",
"last",
"refresh",
"available",
"for",
"search",
"."
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/elasticsearch/taskdb.py#L119-L125 | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"_changed",
"=",
"False",
"self",
".",
"es",
".",
"indices",
".",
"refresh",
"(",
"index",
"=",
"self",
".",
"index",
")"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Fetcher.send_result | Send fetch result to processor | pyspider/fetcher/tornado_fetcher.py | def send_result(self, type, task, result):
'''Send fetch result to processor'''
if self.outqueue:
try:
self.outqueue.put((task, result))
except Exception as e:
logger.exception(e) | def send_result(self, type, task, result):
'''Send fetch result to processor'''
if self.outqueue:
try:
self.outqueue.put((task, result))
except Exception as e:
logger.exception(e) | [
"Send",
"fetch",
"result",
"to",
"processor"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L108-L114 | [
"def",
"send_result",
"(",
"self",
",",
"type",
",",
"task",
",",
"result",
")",
":",
"if",
"self",
".",
"outqueue",
":",
"try",
":",
"self",
".",
"outqueue",
".",
"put",
"(",
"(",
"task",
",",
"result",
")",
")",
"except",
"Exception",
"as",
"e",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Fetcher.async_fetch | Do one fetch | pyspider/fetcher/tornado_fetcher.py | def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
... | def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
... | [
"Do",
"one",
"fetch"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L123-L153 | [
"def",
"async_fetch",
"(",
"self",
",",
"task",
",",
"callback",
"=",
"None",
")",
":",
"url",
"=",
"task",
".",
"get",
"(",
"'url'",
",",
"'data:,'",
")",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"self",
".",
"send_result",
"type",
"=",... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Fetcher.sync_fetch | Synchronization fetch, usually used in xmlrpc thread | pyspider/fetcher/tornado_fetcher.py | def sync_fetch(self, task):
'''Synchronization fetch, usually used in xmlrpc thread'''
if not self._running:
return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))
wait_result = threading.Condition()
_result = {}
def callback(ty... | def sync_fetch(self, task):
'''Synchronization fetch, usually used in xmlrpc thread'''
if not self._running:
return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))
wait_result = threading.Condition()
_result = {}
def callback(ty... | [
"Synchronization",
"fetch",
"usually",
"used",
"in",
"xmlrpc",
"thread"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L155-L176 | [
"def",
"sync_fetch",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"_running",
":",
"return",
"self",
".",
"ioloop",
".",
"run_sync",
"(",
"functools",
".",
"partial",
"(",
"self",
".",
"async_fetch",
",",
"task",
",",
"lambda",
"t",
... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Fetcher.data_fetch | A fake fetcher for dataurl | pyspider/fetcher/tornado_fetcher.py | def data_fetch(self, url, task):
'''A fake fetcher for dataurl'''
self.on_fetch('data', task)
result = {}
result['orig_url'] = url
result['content'] = dataurl.decode(url)
result['headers'] = {}
result['status_code'] = 200
result['url'] = url
result... | def data_fetch(self, url, task):
'''A fake fetcher for dataurl'''
self.on_fetch('data', task)
result = {}
result['orig_url'] = url
result['content'] = dataurl.decode(url)
result['headers'] = {}
result['status_code'] = 200
result['url'] = url
result... | [
"A",
"fake",
"fetcher",
"for",
"dataurl"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L178-L200 | [
"def",
"data_fetch",
"(",
"self",
",",
"url",
",",
"task",
")",
":",
"self",
".",
"on_fetch",
"(",
"'data'",
",",
"task",
")",
"result",
"=",
"{",
"}",
"result",
"[",
"'orig_url'",
"]",
"=",
"url",
"result",
"[",
"'content'",
"]",
"=",
"dataurl",
"... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
train | Fetcher.http_fetch | HTTP fetcher | pyspider/fetcher/tornado_fetcher.py | def http_fetch(self, url, task):
'''HTTP fetcher'''
start_time = time.time()
self.on_fetch('http', task)
handle_error = lambda x: self.handle_error('http', url, task, start_time, x)
# setup request parameters
fetch = self.pack_tornado_request_parameters(url, task)
... | def http_fetch(self, url, task):
'''HTTP fetcher'''
start_time = time.time()
self.on_fetch('http', task)
handle_error = lambda x: self.handle_error('http', url, task, start_time, x)
# setup request parameters
fetch = self.pack_tornado_request_parameters(url, task)
... | [
"HTTP",
"fetcher"
] | binux/pyspider | python | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L327-L428 | [
"def",
"http_fetch",
"(",
"self",
",",
"url",
",",
"task",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"on_fetch",
"(",
"'http'",
",",
"task",
")",
"handle_error",
"=",
"lambda",
"x",
":",
"self",
".",
"handle_error",
"("... | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.