sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if fields:
url += '?' + urlencode(fields)
return self.urlopen(method, url, **urlopen_kw) | Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc. | entailment |
def make_str(value):
"""Converts a value into a valid string."""
if isinstance(value, bytes):
try:
return value.decode(sys.getfilesystemencoding())
except UnicodeError:
return value.decode('utf-8', 'replace')
return text_type(value) | Converts a value into a valid string. | entailment |
def echo(message=None, file=None, nl=True, err=False, color=None):
"""Prints a message plus a newline to the given file or stdout. On
first sight, this looks like the print function, but it has improved
support for handling Unicode and binary data that does not fail no
matter how badly configured the system is.
Primarily it means that you can print binary data as well as Unicode
data on both 2.x and 3.x to the given file in the most appropriate way
possible. This is a very carefree function as in that it will try its
best to not fail.
In addition to that, if `colorama`_ is installed, the echo function will
also support clever handling of ANSI codes. Essentially it will then
do the following:
- add transparent handling of ANSI color codes on Windows.
- hide ANSI codes automatically if the destination file is not a
terminal.
.. _colorama: http://pypi.python.org/pypi/colorama
.. versionchanged:: 2.0
Starting with version 2.0 of Click, the echo function will work
with colorama if it's installed.
.. versionadded:: 3.0
The `err` parameter was added.
.. versionchanged:: 4.0
Added the `color` flag.
:param message: the message to print
:param file: the file to write to (defaults to ``stdout``)
:param err: if set to true the file defaults to ``stderr`` instead of
``stdout``. This is faster and easier than calling
:func:`get_text_stderr` yourself.
:param nl: if set to `True` (the default) a newline is printed afterwards.
:param color: controls if the terminal supports ANSI colors or not. The
default is autodetection.
"""
if file is None:
if err:
file = _default_text_stderr()
else:
file = _default_text_stdout()
# Convert non bytes/text into the native string type.
if message is not None and not isinstance(message, echo_native_types):
message = text_type(message)
# If there is a message, and we're in Python 3, and the value looks
# like bytes, we manually need to find the binary stream and write the
# message in there. This is done separately so that most stream
# types will work as you would expect. Eg: you can write to StringIO
# for other cases.
if message and not PY2 and is_bytes(message):
binary_file = _find_binary_writer(file)
if binary_file is not None:
file.flush()
binary_file.write(message)
if nl:
binary_file.write(b'\n')
binary_file.flush()
return
# ANSI-style support. If there is no message or we are dealing with
# bytes nothing is happening. If we are connected to a file we want
# to strip colors. If we are on windows we either wrap the stream
# to strip the color or we use the colorama support to translate the
# ansi codes to API calls.
if message and not is_bytes(message):
if should_strip_ansi(file, color):
message = strip_ansi(message)
elif WIN:
if auto_wrap_for_ansi is not None:
file = auto_wrap_for_ansi(file)
elif not color:
message = strip_ansi(message)
if message:
file.write(message)
if nl:
file.write('\n')
file.flush() | Prints a message plus a newline to the given file or stdout. On
first sight, this looks like the print function, but it has improved
support for handling Unicode and binary data that does not fail no
matter how badly configured the system is.
Primarily it means that you can print binary data as well as Unicode
data on both 2.x and 3.x to the given file in the most appropriate way
possible. This is a very carefree function as in that it will try its
best to not fail.
In addition to that, if `colorama`_ is installed, the echo function will
also support clever handling of ANSI codes. Essentially it will then
do the following:
- add transparent handling of ANSI color codes on Windows.
- hide ANSI codes automatically if the destination file is not a
terminal.
.. _colorama: http://pypi.python.org/pypi/colorama
.. versionchanged:: 2.0
Starting with version 2.0 of Click, the echo function will work
with colorama if it's installed.
.. versionadded:: 3.0
The `err` parameter was added.
.. versionchanged:: 4.0
Added the `color` flag.
:param message: the message to print
:param file: the file to write to (defaults to ``stdout``)
:param err: if set to true the file defaults to ``stderr`` instead of
``stdout``. This is faster and easier than calling
:func:`get_text_stderr` yourself.
:param nl: if set to `True` (the default) a newline is printed afterwards.
:param color: controls if the terminal supports ANSI colors or not. The
default is autodetection. | entailment |
def parent():
"""Determine subshell matching the currently running shell
The shell is determined by either a pre-defined BE_SHELL
environment variable, or, if none is found, via psutil
which looks at the parent process directly through
system-level calls.
For example, is `be` is run from cmd.exe, then the full
path to cmd.exe is returned, and the same goes for bash.exe
and bash (without suffix) for Unix environments.
The point is to return an appropriate subshell for the
running shell, as opposed to the currently running OS.
"""
if self._parent:
return self._parent
if "BE_SHELL" in os.environ:
self._parent = os.environ["BE_SHELL"]
else:
# If a shell is not provided, rely on `psutil`
# to look at the calling process name.
try:
import psutil
except ImportError:
raise ImportError(
"No shell provided, see documentation for "
"BE_SHELL for more information.\n"
"https://github.com/mottosso/be/wiki"
"/environment#read-environment-variables")
parent = psutil.Process(os.getpid()).parent()
# `pip install` creates an additional executable
# that tricks the above mechanism to think of it
# as the parent shell. See #34 for more.
if parent.name() in ("be", "be.exe"):
parent = parent.parent()
self._parent = str(parent.exe())
return self._parent | Determine subshell matching the currently running shell
The shell is determined by either a pre-defined BE_SHELL
environment variable, or, if none is found, via psutil
which looks at the parent process directly through
system-level calls.
For example, is `be` is run from cmd.exe, then the full
path to cmd.exe is returned, and the same goes for bash.exe
and bash (without suffix) for Unix environments.
The point is to return an appropriate subshell for the
running shell, as opposed to the currently running OS. | entailment |
def platform():
"""Return platform for the current shell, e.g. windows or unix"""
executable = parent()
basename = os.path.basename(executable)
basename, _ = os.path.splitext(basename)
if basename in ("bash", "sh"):
return "unix"
if basename in ("cmd", "powershell"):
return "windows"
raise SystemError("Unsupported shell: %s" % basename) | Return platform for the current shell, e.g. windows or unix | entailment |
def cmd(parent):
"""Determine subshell command for subprocess.call
Arguments:
parent (str): Absolute path to parent shell executable
"""
shell_name = os.path.basename(parent).rsplit(".", 1)[0]
dirname = os.path.dirname(__file__)
# Support for Bash
if shell_name in ("bash", "sh"):
shell = os.path.join(dirname, "_shell.sh").replace("\\", "/")
cmd = [parent.replace("\\", "/"), shell]
# Support for Cmd
elif shell_name in ("cmd",):
shell = os.path.join(dirname, "_shell.bat").replace("\\", "/")
cmd = [parent, "/K", shell]
# Support for Powershell
elif shell_name in ("powershell",):
raise SystemError("Powershell not yet supported")
# Unsupported
else:
raise SystemError("Unsupported shell: %s" % shell_name)
return cmd | Determine subshell command for subprocess.call
Arguments:
parent (str): Absolute path to parent shell executable | entailment |
def context(root, project=""):
"""Produce the be environment
The environment is an exact replica of the active
environment of the current process, with a few
additional variables, all of which are listed below.
"""
environment = os.environ.copy()
environment.update({
"BE_PROJECT": project,
"BE_PROJECTROOT": (
os.path.join(root, project).replace("\\", "/")
if project else ""),
"BE_PROJECTSROOT": root,
"BE_ALIASDIR": "",
"BE_CWD": root,
"BE_CD": "",
"BE_ROOT": "",
"BE_TOPICS": "",
"BE_DEVELOPMENTDIR": "",
"BE_ACTIVE": "1",
"BE_USER": "",
"BE_SCRIPT": "",
"BE_PYTHON": "",
"BE_ENTER": "",
"BE_TEMPDIR": "",
"BE_PRESETSDIR": "",
"BE_GITHUB_API_TOKEN": "",
"BE_ENVIRONMENT": "",
"BE_BINDING": "",
"BE_TABCOMPLETION": ""
})
return environment | Produce the be environment
The environment is an exact replica of the active
environment of the current process, with a few
additional variables, all of which are listed below. | entailment |
def random_name():
"""Return a random name
Example:
>> random_name()
dizzy_badge
>> random_name()
evasive_cactus
"""
adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)]
noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)]
return "%s_%s" % (adj, noun) | Return a random name
Example:
>> random_name()
dizzy_badge
>> random_name()
evasive_cactus | entailment |
def isproject(path):
"""Return whether or not `path` is a project
Arguments:
path (str): Absolute path
"""
try:
if os.path.basename(path)[0] in (".", "_"):
return False
if not os.path.isdir(path):
return False
if not any(fname in os.listdir(path)
for fname in ("templates.yaml",
"inventory.yaml")):
return False
except:
return False
return True | Return whether or not `path` is a project
Arguments:
path (str): Absolute path | entailment |
def echo(text, silent=False, newline=True):
"""Print to the console
Arguments:
text (str): Text to print to the console
silen (bool, optional): Whether or not to produce any output
newline (bool, optional): Whether or not to append a newline.
"""
if silent:
return
print(text) if newline else sys.stdout.write(text) | Print to the console
Arguments:
text (str): Text to print to the console
silen (bool, optional): Whether or not to produce any output
newline (bool, optional): Whether or not to append a newline. | entailment |
def list_projects(root, backend=os.listdir):
"""List projects at `root`
Arguments:
root (str): Absolute path to the `be` root directory,
typically the current working directory.
"""
projects = list()
for project in sorted(backend(root)):
abspath = os.path.join(root, project)
if not isproject(abspath):
continue
projects.append(project)
return projects | List projects at `root`
Arguments:
root (str): Absolute path to the `be` root directory,
typically the current working directory. | entailment |
def list_inventory(inventory):
"""List a projects inventory
Given a project, simply list the contents of `inventory.yaml`
Arguments:
root (str): Absolute path to the `be` root directory,
typically the current working directory.
inventory (dict): inventory.yaml
"""
inverted = invert_inventory(inventory)
items = list()
for item in sorted(inverted, key=lambda a: (inverted[a], a)):
items.append((item, inverted[item]))
return items | List a projects inventory
Given a project, simply list the contents of `inventory.yaml`
Arguments:
root (str): Absolute path to the `be` root directory,
typically the current working directory.
inventory (dict): inventory.yaml | entailment |
def list_template(root, topics, templates, inventory, be, absolute=False):
"""List contents for resolved template
Resolve a template as far as possible via the given `topics`.
For example, if a template supports 5 arguments, but only
3 are given, resolve the template until its 4th argument
and list the contents thereafter.
In some cases, an additional path is present following an
argument, e.g. {3}/assets. The `/assets` portion is referred
to as the "tail" and is appended also.
Arguments:
topics (tuple): Current topics
templates (dict): templates.yaml
inventory (dict): inventory.yaml
be (dict): be.yaml
"""
project = topics[0]
# Get item
try:
key = be.get("templates", {}).get("key") or "{1}"
item = item_from_topics(key, topics)
binding = binding_from_item(inventory, item)
except KeyError:
return []
except IndexError as exc:
raise IndexError("At least %s topics are required" % str(exc))
fields = replacement_fields_from_context(
context(root, project))
binding = binding_from_item(inventory, item)
pattern = pattern_from_template(templates, binding)
# 2 arguments, {1}/{2}/{3} -> {1}/{2}
# 2 arguments, {1}/{2}/assets/{3} -> {1}/{2}/assets
index_end = pattern.index(str(len(topics)-1)) + 2
trimmed_pattern = pattern[:index_end]
# If there aren't any more positional arguments, we're done
print trimmed_pattern
if not re.findall("{[\d]+}", pattern[index_end:]):
return []
# Append trail
# e.g. {1}/{2}/assets
# ^^^^^^^
try:
index_trail = pattern[index_end:].index("{")
trail = pattern[index_end:index_end + index_trail - 1]
trimmed_pattern += trail
except ValueError:
pass
try:
path = trimmed_pattern.format(*topics, **fields)
except IndexError:
raise IndexError("Template for \"%s\" has unordered "
"positional arguments: \"%s\"" % (item, pattern))
if not os.path.isdir(path):
return []
items = list()
for dirname in os.listdir(path):
abspath = os.path.join(path, dirname).replace("\\", "/")
if not os.path.isdir(abspath):
continue
if absolute:
items.append(abspath)
else:
items.append(dirname)
return items | List contents for resolved template
Resolve a template as far as possible via the given `topics`.
For example, if a template supports 5 arguments, but only
3 are given, resolve the template until its 4th argument
and list the contents thereafter.
In some cases, an additional path is present following an
argument, e.g. {3}/assets. The `/assets` portion is referred
to as the "tail" and is appended also.
Arguments:
topics (tuple): Current topics
templates (dict): templates.yaml
inventory (dict): inventory.yaml
be (dict): be.yaml | entailment |
def invert_inventory(inventory):
"""Return {item: binding} from {binding: item}
Protect against items with additional metadata
and items whose type is a number
Returns:
Dictionary of inverted inventory
"""
inverted = dict()
for binding, items in inventory.iteritems():
for item in items:
if isinstance(item, dict):
item = item.keys()[0]
item = str(item) # Key may be number
if item in inverted:
echo("Warning: Duplicate item found, "
"for \"%s: %s\"" % (binding, item))
continue
inverted[item] = binding
return inverted | Return {item: binding} from {binding: item}
Protect against items with additional metadata
and items whose type is a number
Returns:
Dictionary of inverted inventory | entailment |
def pos_development_directory(templates,
inventory,
context,
topics,
user,
item):
"""Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
user (str): Current `be` user
item (str): Item from template-binding address
"""
replacement_fields = replacement_fields_from_context(context)
binding = binding_from_item(inventory, item)
pattern = pattern_from_template(templates, binding)
positional_arguments = find_positional_arguments(pattern)
highest_argument = find_highest_position(positional_arguments)
highest_available = len(topics) - 1
if highest_available < highest_argument:
echo("Template for \"%s\" requires at least %i arguments" % (
item, highest_argument + 1))
sys.exit(USER_ERROR)
try:
return pattern.format(*topics, **replacement_fields).replace("\\", "/")
except KeyError as exc:
echo("TEMPLATE ERROR: %s is not an available key\n" % exc)
echo("Available tokens:")
for key in replacement_fields:
echo("\n- %s" % key)
sys.exit(TEMPLATE_ERROR) | Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
user (str): Current `be` user
item (str): Item from template-binding address | entailment |
def fixed_development_directory(templates, inventory, topics, user):
"""Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
user (str): Current `be` user
"""
echo("Fixed syntax has been deprecated, see positional syntax")
project, item, task = topics[0].split("/")
template = binding_from_item(inventory, item)
pattern = pattern_from_template(templates, template)
if find_positional_arguments(pattern):
echo("\"%s\" uses a positional syntax" % project)
echo("Try this:")
echo(" be in %s" % " ".join([project, item, task]))
sys.exit(USER_ERROR)
keys = {
"cwd": os.getcwd(),
"project": project,
"item": item.replace("\\", "/"),
"user": user,
"task": task,
"type": task, # deprecated
}
try:
return pattern.format(**keys).replace("\\", "/")
except KeyError as exc:
echo("TEMPLATE ERROR: %s is not an available key\n" % exc)
echo("Available keys")
for key in keys:
echo("\n- %s" % key)
sys.exit(1) | Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
user (str): Current `be` user | entailment |
def replacement_fields_from_context(context):
"""Convert context replacement fields
Example:
BE_KEY=value -> {"key": "value}
Arguments:
context (dict): The current context
"""
return dict((k[3:].lower(), context[k])
for k in context if k.startswith("BE_")) | Convert context replacement fields
Example:
BE_KEY=value -> {"key": "value}
Arguments:
context (dict): The current context | entailment |
def item_from_topics(key, topics):
"""Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for the key
"""
if re.match("{\d+}", key):
pos = int(key.strip("{}"))
try:
binding = topics[pos]
except IndexError:
raise IndexError(pos + 1)
else:
echo("be.yaml template key not recognised")
sys.exit(PROJECT_ERROR)
return binding | Get binding from `topics` via `key`
Example:
{0} == hello --> be in hello world
{1} == world --> be in hello world
Returns:
Single topic matching the key
Raises:
IndexError (int): With number of required
arguments for the key | entailment |
def pattern_from_template(templates, name):
"""Return pattern for name
Arguments:
templates (dict): Current templates
name (str): Name of name
"""
if name not in templates:
echo("No template named \"%s\"" % name)
sys.exit(1)
return templates[name] | Return pattern for name
Arguments:
templates (dict): Current templates
name (str): Name of name | entailment |
def binding_from_item(inventory, item):
"""Return binding for `item`
Example:
asset:
- myasset
The binding is "asset"
Arguments:
project: Name of project
item (str): Name of item
"""
if item in self.bindings:
return self.bindings[item]
bindings = invert_inventory(inventory)
try:
self.bindings[item] = bindings[item]
return bindings[item]
except KeyError as exc:
exc.bindings = bindings
raise exc | Return binding for `item`
Example:
asset:
- myasset
The binding is "asset"
Arguments:
project: Name of project
item (str): Name of item | entailment |
def parse_environment(fields, context, topics):
"""Resolve the be.yaml environment key
Features:
- Lists, e.g. ["/path1", "/path2"]
- Environment variable references, via $
- Replacement field references, e.g. {key}
- Topic references, e.g. {1}
"""
def _resolve_environment_lists(context):
"""Concatenate environment lists"""
for key, value in context.copy().iteritems():
if isinstance(value, list):
context[key] = os.pathsep.join(value)
return context
def _resolve_environment_references(fields, context):
"""Resolve $ occurences by expansion
Given a dictionary {"PATH": "$PATH;somevalue;{0}"}
Return {"PATH": "value_of_PATH;somevalue;myproject"},
given that the first topic - {0} - is "myproject"
Arguments:
fields (dict): Environment from be.yaml
context (dict): Source context
"""
def repl(match):
key = pattern[match.start():match.end()].strip("$")
return context.get(key)
pat = re.compile("\$\w+", re.IGNORECASE)
for key, pattern in fields.copy().iteritems():
fields[key] = pat.sub(repl, pattern) \
.strip(os.pathsep) # Remove superflous separators
return fields
def _resolve_environment_fields(fields, context, topics):
"""Resolve {} occurences
Supports both positional and BE_-prefixed variables.
Example:
BE_MYKEY -> "{mykey}" from `BE_MYKEY`
{1} -> "{mytask}" from `be in myproject mytask`
Returns:
Dictionary of resolved fields
"""
source_dict = replacement_fields_from_context(context)
source_dict.update(dict((str(topics.index(topic)), topic)
for topic in topics))
def repl(match):
key = pattern[match.start():match.end()].strip("{}")
try:
return source_dict[key]
except KeyError:
echo("PROJECT ERROR: Unavailable reference \"%s\" "
"in be.yaml" % key)
sys.exit(PROJECT_ERROR)
for key, pattern in fields.copy().iteritems():
fields[key] = re.sub("{[\d\w]+}", repl, pattern)
return fields
fields = _resolve_environment_lists(fields)
fields = _resolve_environment_references(fields, context)
fields = _resolve_environment_fields(fields, context, topics)
return fields | Resolve the be.yaml environment key
Features:
- Lists, e.g. ["/path1", "/path2"]
- Environment variable references, via $
- Replacement field references, e.g. {key}
- Topic references, e.g. {1} | entailment |
def parse_redirect(redirect, topics, context):
"""Resolve the be.yaml redirect key
Arguments:
redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE}
topics (tuple): Topics from which to sample, e.g. (project, item, task)
context (dict): Context from which to sample
"""
for map_source, map_dest in redirect.items():
if re.match("{\d+}", map_source):
topics_index = int(map_source.strip("{}"))
topics_value = topics[topics_index]
context[map_dest] = topics_value
continue
context[map_dest] = context[map_source] | Resolve the be.yaml redirect key
Arguments:
redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE}
topics (tuple): Topics from which to sample, e.g. (project, item, task)
context (dict): Context from which to sample | entailment |
def slice(index, template):
"""Slice a template based on it's positional argument
Arguments:
index (int): Position at which to slice
template (str): Template to slice
Example:
>>> slice(0, "{cwd}/{0}/assets/{1}/{2}")
'{cwd}/{0}'
>>> slice(1, "{cwd}/{0}/assets/{1}/{2}")
'{cwd}/{0}/assets/{1}'
"""
try:
return re.match("^.*{[%i]}" % index, template).group()
except AttributeError:
raise ValueError("Index %i not found in template: %s"
% (index, template)) | Slice a template based on it's positional argument
Arguments:
index (int): Position at which to slice
template (str): Template to slice
Example:
>>> slice(0, "{cwd}/{0}/assets/{1}/{2}")
'{cwd}/{0}'
>>> slice(1, "{cwd}/{0}/assets/{1}/{2}")
'{cwd}/{0}/assets/{1}' | entailment |
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
"""
if not proxy in self.proxy_manager:
proxy_headers = self.proxy_headers(proxy)
self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return self.proxy_manager[proxy] | Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager | entailment |
def cert_verify(self, conn, url, verify, cert):
"""Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Whether we should actually verify the certificate.
:param cert: The SSL certificate to verify.
"""
if url.lower().startswith('https') and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = DEFAULT_CA_BUNDLE_PATH
if not cert_loc:
raise Exception("Could not find a suitable SSL CA certificate bundle.")
conn.cert_reqs = 'CERT_REQUIRED'
conn.ca_certs = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert | Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Whether we should actually verify the certificate.
:param cert: The SSL certificate to verify. | entailment |
def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
"""
proxies = proxies or {}
proxy = proxies.get(urlparse(url.lower()).scheme)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn | Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request. | entailment |
def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes to proxy URLs.
"""
proxies = proxies or {}
scheme = urlparse(request.url).scheme
proxy = proxies.get(scheme)
if proxy and scheme != 'https':
url = urldefragauth(request.url)
else:
url = request.path_url
return url | Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes to proxy URLs. | entailment |
def proxy_headers(self, proxy):
"""Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
:param kwargs: Optional additional keyword arguments.
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
return headers | Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
:param kwargs: Optional additional keyword arguments. | entailment |
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
"""
session = sessions.Session()
response = session.request(method=method, url=url, **kwargs)
# By explicitly closing the session, we avoid leaving sockets open which
# can trigger a ResourceWarning in some cases, and look like a memory leak
# in others.
session.close()
return response | Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]> | entailment |
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if sock is False: # Platform-specific: AppEngine
return False
if sock is None: # Connection already closed (such as by httplib).
return True
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except socket.error:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True | Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us. | entailment |
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
expires = time.time() + morsel['max-age']
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = time.mktime(
time.strptime(morsel['expires'], time_template)) - time.timezone
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
) | Convert a Morsel object into a Cookie containing the one k/v pair. | entailment |
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements."""
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (path is None
or cookie.path == path):
dictionary[cookie.name] = cookie.value
return dictionary | Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements. | entailment |
def feed(self, aBuf, aCharLen):
"""feed a character with known length"""
if aCharLen == 2:
# we only care about 2-bytes character in our distribution analysis
order = self.get_order(aBuf)
else:
order = -1
if order >= 0:
self._mTotalChars += 1
# order is valid
if order < self._mTableSize:
if 512 > self._mCharToFreqOrder[order]:
self._mFreqChars += 1 | feed a character with known length | entailment |
def get_confidence(self):
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD:
return SURE_NO
if self._mTotalChars != self._mFreqChars:
r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars)
* self._mTypicalDistributionRatio))
if r < SURE_YES:
return r
# normalize confidence (we don't want to be 100% sure)
return SURE_YES | return confidence based on existing data | entailment |
def add_stderr_logger(level=logging.DEBUG):
"""
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
"""
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another package.
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(handler)
logger.setLevel(level)
logger.debug('Added a stderr logging handler to logger: %s' % __name__)
return handler | Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it. | entailment |
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
# Maps the length of a digest to a possible hash function producing
# this digest.
hashfunc_map = {
16: md5,
20: sha1,
32: sha256,
}
fingerprint = fingerprint.replace(':', '').lower()
digest_length, odd = divmod(len(fingerprint), 2)
if odd or digest_length not in hashfunc_map:
raise SSLError('Fingerprint is of invalid length.')
# We need encode() here for py32; works on py2 and p33.
fingerprint_bytes = unhexlify(fingerprint.encode())
hashfunc = hashfunc_map[digest_length]
cert_digest = hashfunc(cert).digest()
if not cert_digest == fingerprint_bytes:
raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
.format(hexlify(fingerprint_bytes),
hexlify(cert_digest))) | Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons. | entailment |
def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,
options=None, ciphers=None):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do::
from urllib3.util import ssl_
context = ssl_.create_urllib3_context()
context.options &= ~ssl_.OP_NO_SSLv3
You can do the same to enable compression (substituting ``COMPRESSION``
for ``SSLv3`` in the last line above).
:param ssl_version:
The desired protocol version to use. This will default to
PROTOCOL_SSLv23 which will negotiate the highest protocol that both
the server and your installation of OpenSSL support.
:param cert_reqs:
Whether to require the certificate verification. This defaults to
``ssl.CERT_REQUIRED``.
:param options:
Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
:param ciphers:
Which cipher suites to allow the server to select.
:returns:
Constructed SSLContext object with specified options
:rtype: SSLContext
"""
context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
if options is None:
options = 0
# SSLv2 is easily broken and is considered harmful and dangerous
options |= OP_NO_SSLv2
# SSLv3 has several problems and is now dangerous
options |= OP_NO_SSLv3
# Disable compression to prevent CRIME attacks for OpenSSL 1.0+
# (issue #309)
options |= OP_NO_COMPRESSION
context.options |= options
if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6
context.set_ciphers(ciphers or _DEFAULT_CIPHERS)
context.verify_mode = cert_reqs
if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
# We do our own verification, including fingerprints and alternative
# hostnames. So disable it here
context.check_hostname = False
return context | All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do::
from urllib3.util import ssl_
context = ssl_.create_urllib3_context()
context.options &= ~ssl_.OP_NO_SSLv3
You can do the same to enable compression (substituting ``COMPRESSION``
for ``SSLv3`` in the last line above).
:param ssl_version:
The desired protocol version to use. This will default to
PROTOCOL_SSLv23 which will negotiate the highest protocol that both
the server and your installation of OpenSSL support.
:param cert_reqs:
Whether to require the certificate verification. This defaults to
``ssl.CERT_REQUIRED``.
:param options:
Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
:param ciphers:
Which cipher suites to allow the server to select.
:returns:
Constructed SSLContext object with specified options
:rtype: SSLContext | entailment |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None):
"""
All arguments except for server_hostname and ssl_context have the same
meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support. This is not
supported on Python 2.6 as the ssl module does not support it.
"""
context = ssl_context
if context is None:
context = create_urllib3_context(ssl_version, cert_reqs,
ciphers=ciphers)
if ca_certs:
try:
context.load_verify_locations(ca_certs)
except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2
raise SSLError(e)
# Py33 raises FileNotFoundError which subclasses OSError
# These are not equivalent unless we check the errno attribute
except OSError as e: # Platform-specific: Python 3.3 and beyond
if e.errno == errno.ENOENT:
raise SSLError(e)
raise
if certfile:
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock) | All arguments except for server_hostname and ssl_context have the same
meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object. If none is provided, one will
be created using :func:`create_urllib3_context`.
:param ciphers:
A string of ciphers we wish the client to support. This is not
supported on Python 2.6 as the ssl module does not support it. | entailment |
def connection_from_url(url, **kw):
"""
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must include the scheme. Port is optional.
:param \**kw:
Passes additional parameters to the constructor of the appropriate
:class:`.ConnectionPool`. Useful for specifying things like
timeout, maxsize, headers, etc.
Example::
>>> conn = connection_from_url('http://google.com/')
>>> r = conn.request('GET', '/')
"""
scheme, host, port = get_host(url)
if scheme == 'https':
return HTTPSConnectionPool(host, port=port, **kw)
else:
return HTTPConnectionPool(host, port=port, **kw) | Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must include the scheme. Port is optional.
:param \**kw:
Passes additional parameters to the constructor of the appropriate
:class:`.ConnectionPool`. Useful for specifying things like
timeout, maxsize, headers, etc.
Example::
>>> conn = connection_from_url('http://google.com/')
>>> r = conn.request('GET', '/') | entailment |
def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connections are discarded frequently,
then maxsize should be increased.
If the pool is closed, then the connection will be closed and discarded.
"""
try:
self.pool.put(conn, block=False)
return # Everything is dandy, done.
except AttributeError:
# self.pool is None.
pass
except Full:
# This should never happen if self.block == True
log.warning(
"Connection pool is full, discarding connection: %s" %
self.host)
# Connection never got put back into the pool, close it.
if conn:
conn.close() | Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connections are discarded frequently,
then maxsize should be increased.
If the pool is closed, then the connection will be closed and discarded. | entailment |
def _make_request(self, conn, method, url, timeout=_Default,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls httplib.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
conn.request(method, url, **httplib_request_kw)
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, 'sock', None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try: # Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
httplib_response = conn.getresponse()
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
httplib_response.status,
httplib_response.length))
return httplib_response | Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts. | entailment |
def urlopen(self, method, url, body=None, headers=None, retries=None,
redirect=True, assert_same_host=True, timeout=_Default,
pool_timeout=None, release_conn=None, **response_kw):
"""
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethods`, such as :meth:`request`.
.. note::
`release_conn` will only behave as expected if
`preload_content=False` because we want to make
`preload_content=False` the default behaviour someday soon without
breaking backwards compatibility.
:param method:
HTTP request method (such as GET, POST, PUT, etc.)
:param body:
Data to send in the request body (useful for creating
POST requests, see HTTPConnectionPool.post_url for
more convenience).
:param headers:
Dictionary of custom headers to send, such as User-Agent,
If-None-Match, etc. If None, pool headers are used. If provided,
these headers completely replace any pool-specific headers.
:param retries:
Configure the number of retries to allow before raising a
:class:`~urllib3.exceptions.MaxRetryError` exception.
Pass ``None`` to retry until you receive a response. Pass a
:class:`~urllib3.util.retry.Retry` object for fine-grained control
over different types of retries.
Pass an integer number to retry connection errors that many times,
but no other types of errors. Pass zero to never retry.
If ``False``, then retries are disabled and any exception is raised
immediately. Also, instead of raising a MaxRetryError on redirects,
the redirect response will be returned.
:type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
:param redirect:
If True, automatically handle redirects (status codes 301, 302,
303, 307, 308). Each redirect counts as a retry. Disabling retries
will disable redirect, too.
:param assert_same_host:
If ``True``, will make sure that the host of the pool requests is
consistent else will raise HostChangedError. When False, you can
use the pool on an HTTP proxy and request foreign hosts.
:param timeout:
If specified, overrides the default timeout for this one
request. It may be a float (in seconds) or an instance of
:class:`urllib3.util.Timeout`.
:param pool_timeout:
If set and the pool is set to block=True, then this method will
block for ``pool_timeout`` seconds and raise EmptyPoolError if no
connection is available within the time period.
:param release_conn:
If False, then the urlopen call will not release the connection
back into the pool once a response is received (but will release if
you read the entire contents of the response such as when
`preload_content=True`). This is useful if you're not preloading
the response's content immediately. You will need to call
``r.release_conn()`` on the response ``r`` to return the connection
back into the pool. If None, it takes the value of
``response_kw.get('preload_content', True)``.
:param \**response_kw:
Additional parameters are passed to
:meth:`urllib3.response.HTTPResponse.from_httplib`
"""
if headers is None:
headers = self.headers
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
if release_conn is None:
release_conn = response_kw.get('preload_content', True)
# Check host
if assert_same_host and not self.is_same_host(url):
raise HostChangedError(self, url, retries)
conn = None
# Merge the proxy headers. Only do this in HTTP. We have to copy the
# headers dict so we can safely change it without those changes being
# reflected in anyone else's copy.
if self.scheme == 'http':
headers = headers.copy()
headers.update(self.proxy_headers)
# Must keep the exception bound to a separate variable or else Python 3
# complains about UnboundLocalError.
err = None
try:
# Request a connection from the queue.
timeout_obj = self._get_timeout(timeout)
conn = self._get_conn(timeout=pool_timeout)
conn.timeout = timeout_obj.connect_timeout
is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
if is_new_proxy_conn:
self._prepare_proxy(conn)
# Make the request on the httplib connection object.
httplib_response = self._make_request(conn, method, url,
timeout=timeout_obj,
body=body, headers=headers)
# If we're going to release the connection in ``finally:``, then
# the request doesn't need to know about the connection. Otherwise
# it will also try to release it and we'll have a double-release
# mess.
response_conn = not release_conn and conn
# Import httplib's response into our own wrapper object
response = HTTPResponse.from_httplib(httplib_response,
pool=self,
connection=response_conn,
**response_kw)
# else:
# The connection will be put back into the pool when
# ``response.release_conn()`` is called (implicitly by
# ``response.read()``)
except Empty:
# Timed out by queue.
raise EmptyPoolError(self, "No pool connections are available.")
except (BaseSSLError, CertificateError) as e:
# Close the connection. If a connection is reused on which there
# was a Certificate error, the next request will certainly raise
# another Certificate error.
if conn:
conn.close()
conn = None
raise SSLError(e)
except SSLError:
# Treat SSLError separately from BaseSSLError to preserve
# traceback.
if conn:
conn.close()
conn = None
raise
except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:
if conn:
# Discard the connection for these exceptions. It will be
# be replaced during the next _get_conn() call.
conn.close()
conn = None
if isinstance(e, SocketError) and self.proxy:
e = ProxyError('Cannot connect to proxy.', e)
elif isinstance(e, (SocketError, HTTPException)):
e = ProtocolError('Connection aborted.', e)
retries = retries.increment(method, url, error=e, _pool=self,
_stacktrace=sys.exc_info()[2])
retries.sleep()
# Keep track of the error for the retry warning.
err = e
finally:
if release_conn:
# Put the connection back to be reused. If the connection is
# expired then it will be None, which will get replaced with a
# fresh connection during _get_conn.
self._put_conn(conn)
if not conn:
# Try again
log.warning("Retrying (%r) after connection "
"broken by '%r': %s" % (retries, err, url))
return self.urlopen(method, url, body, headers, retries,
redirect, assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
# Handle redirect?
redirect_location = redirect and response.get_redirect_location()
if redirect_location:
if response.status == 303:
method = 'GET'
try:
retries = retries.increment(method, url, response=response, _pool=self)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
log.info("Redirecting %s -> %s" % (url, redirect_location))
return self.urlopen(method, redirect_location, body, headers,
retries=retries, redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
# Check if we should retry the HTTP response.
if retries.is_forced_retry(method, status_code=response.status):
retries = retries.increment(method, url, response=response, _pool=self)
retries.sleep()
log.info("Forced retry: %s" % url)
return self.urlopen(method, url, body, headers,
retries=retries, redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
return response | Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethods`, such as :meth:`request`.
.. note::
`release_conn` will only behave as expected if
`preload_content=False` because we want to make
`preload_content=False` the default behaviour someday soon without
breaking backwards compatibility.
:param method:
HTTP request method (such as GET, POST, PUT, etc.)
:param body:
Data to send in the request body (useful for creating
POST requests, see HTTPConnectionPool.post_url for
more convenience).
:param headers:
Dictionary of custom headers to send, such as User-Agent,
If-None-Match, etc. If None, pool headers are used. If provided,
these headers completely replace any pool-specific headers.
:param retries:
Configure the number of retries to allow before raising a
:class:`~urllib3.exceptions.MaxRetryError` exception.
Pass ``None`` to retry until you receive a response. Pass a
:class:`~urllib3.util.retry.Retry` object for fine-grained control
over different types of retries.
Pass an integer number to retry connection errors that many times,
but no other types of errors. Pass zero to never retry.
If ``False``, then retries are disabled and any exception is raised
immediately. Also, instead of raising a MaxRetryError on redirects,
the redirect response will be returned.
:type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
:param redirect:
If True, automatically handle redirects (status codes 301, 302,
303, 307, 308). Each redirect counts as a retry. Disabling retries
will disable redirect, too.
:param assert_same_host:
If ``True``, will make sure that the host of the pool requests is
consistent else will raise HostChangedError. When False, you can
use the pool on an HTTP proxy and request foreign hosts.
:param timeout:
If specified, overrides the default timeout for this one
request. It may be a float (in seconds) or an instance of
:class:`urllib3.util.Timeout`.
:param pool_timeout:
If set and the pool is set to block=True, then this method will
block for ``pool_timeout`` seconds and raise EmptyPoolError if no
connection is available within the time period.
:param release_conn:
If False, then the urlopen call will not release the connection
back into the pool once a response is received (but will release if
you read the entire contents of the response such as when
`preload_content=True`). This is useful if you're not preloading
the response's content immediately. You will need to call
``r.release_conn()`` on the response ``r`` to return the connection
back into the pool. If None, it takes the value of
``response_kw.get('preload_content', True)``.
:param \**response_kw:
Additional parameters are passed to
:meth:`urllib3.response.HTTPResponse.from_httplib` | entailment |
def _new_conn(self):
"""
Return a fresh :class:`httplib.HTTPSConnection`.
"""
self.num_connections += 1
log.info("Starting new HTTPS connection (%d): %s"
% (self.num_connections, self.host))
if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
# Platform-specific: Python without ssl
raise SSLError("Can't connect to HTTPS URL because the SSL "
"module is not available.")
actual_host = self.host
actual_port = self.port
if self.proxy is not None:
actual_host = self.proxy.host
actual_port = self.proxy.port
conn = self.ConnectionCls(host=actual_host, port=actual_port,
timeout=self.timeout.connect_timeout,
strict=self.strict, **self.conn_kw)
return self._prepare_conn(conn) | Return a fresh :class:`httplib.HTTPSConnection`. | entailment |
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
conn.connect()
if not conn.is_verified:
warnings.warn((
'Unverified HTTPS request is being made. '
'Adding certificate verification is strongly advised. See: '
'https://urllib3.readthedocs.org/en/latest/security.html'),
InsecureRequestWarning) | Called right before a request is made, after the socket is created. | entailment |
def description_of(lines, name='stdin'):
"""
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
"""
u = UniversalDetector()
for line in lines:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '{0}: {1} with confidence {2}'.format(name, result['encoding'],
result['confidence'])
else:
return '{0}: no result'.format(name) | Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str | entailment |
def main(argv=None):
'''
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
'''
# Get command line arguments
parser = argparse.ArgumentParser(
description="Takes one or more file paths and reports their detected \
encodings",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
conflict_handler='resolve')
parser.add_argument('input',
help='File whose encoding we would like to determine.',
type=argparse.FileType('rb'), nargs='*',
default=[sys.stdin])
parser.add_argument('--version', action='version',
version='%(prog)s {0}'.format(__version__))
args = parser.parse_args(argv)
for f in args.input:
if f.isatty():
print("You are running chardetect interactively. Press " +
"CTRL-D twice at the start of a blank line to signal the " +
"end of your input. If you want help, run chardetect " +
"--help\n", file=sys.stderr)
print(description_of(f, f.name)) | Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str | entailment |
def get_terminal_size():
"""Returns the current size of the terminal as tuple in the form
``(width, height)`` in columns and rows.
"""
# If shutil has get_terminal_size() (Python 3.3 and later) use that
if sys.version_info >= (3, 3):
import shutil
shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)
if shutil_get_terminal_size:
sz = shutil_get_terminal_size()
return sz.columns, sz.lines
if get_winterm_size is not None:
return get_winterm_size()
def ioctl_gwinsz(fd):
try:
import fcntl
import termios
cr = struct.unpack(
'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except Exception:
return
return cr
cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
cr = ioctl_gwinsz(fd)
finally:
os.close(fd)
except Exception:
pass
if not cr or not cr[0] or not cr[1]:
cr = (os.environ.get('LINES', 25),
os.environ.get('COLUMNS', DEFAULT_COLUMNS))
return int(cr[1]), int(cr[0]) | Returns the current size of the terminal as tuple in the form
``(width, height)`` in columns and rows. | entailment |
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
blink=None, reverse=None, reset=True):
"""Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the string a reset code is issued. This can be prevented by
passing ``reset=False``.
Examples::
click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
Supported color names:
* ``black`` (might be a gray)
* ``red``
* ``green``
* ``yellow`` (might be an orange)
* ``blue``
* ``magenta``
* ``cyan``
* ``white`` (might be light gray)
* ``reset`` (reset the color code only)
.. versionadded:: 2.0
:param text: the string to style with ansi codes.
:param fg: if provided this will become the foreground color.
:param bg: if provided this will become the background color.
:param bold: if provided this will enable or disable bold mode.
:param dim: if provided this will enable or disable dim mode. This is
badly supported.
:param underline: if provided this will enable or disable underline.
:param blink: if provided this will enable or disable blinking.
:param reverse: if provided this will enable or disable inverse
rendering (foreground becomes background and the
other way round).
:param reset: by default a reset-all code is added at the end of the
string which means that styles do not carry over. This
can be disabled to compose styles.
"""
bits = []
if fg:
try:
bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))
except ValueError:
raise TypeError('Unknown color %r' % fg)
if bg:
try:
bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))
except ValueError:
raise TypeError('Unknown color %r' % bg)
if bold is not None:
bits.append('\033[%dm' % (1 if bold else 22))
if dim is not None:
bits.append('\033[%dm' % (2 if dim else 22))
if underline is not None:
bits.append('\033[%dm' % (4 if underline else 24))
if blink is not None:
bits.append('\033[%dm' % (5 if blink else 25))
if reverse is not None:
bits.append('\033[%dm' % (7 if reverse else 27))
bits.append(text)
if reset:
bits.append(_ansi_reset_all)
return ''.join(bits) | Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the string a reset code is issued. This can be prevented by
passing ``reset=False``.
Examples::
click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
Supported color names:
* ``black`` (might be a gray)
* ``red``
* ``green``
* ``yellow`` (might be an orange)
* ``blue``
* ``magenta``
* ``cyan``
* ``white`` (might be light gray)
* ``reset`` (reset the color code only)
.. versionadded:: 2.0
:param text: the string to style with ansi codes.
:param fg: if provided this will become the foreground color.
:param bg: if provided this will become the background color.
:param bold: if provided this will enable or disable bold mode.
:param dim: if provided this will enable or disable dim mode. This is
badly supported.
:param underline: if provided this will enable or disable underline.
:param blink: if provided this will enable or disable blinking.
:param reverse: if provided this will enable or disable inverse
rendering (foreground becomes background and the
other way round).
:param reset: by default a reset-all code is added at the end of the
string which means that styles do not carry over. This
can be disabled to compose styles. | entailment |
def secho(text, file=None, nl=True, err=False, color=None, **styles):
"""This function combines :func:`echo` and :func:`style` into one
call. As such the following two calls are the same::
click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions
depending on which one they go with.
.. versionadded:: 2.0
"""
return echo(style(text, **styles), file=file, nl=nl, err=err, color=color) | This function combines :func:`echo` and :func:`style` into one
call. As such the following two calls are the same::
click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions
depending on which one they go with.
.. versionadded:: 2.0 | entailment |
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""
Determines appropriate setting for a given request, taking into account the
explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class`
"""
if session_setting is None:
return request_setting
if request_setting is None:
return session_setting
# Bypass if not a dictionary (e.g. verify)
if not (
isinstance(session_setting, Mapping) and
isinstance(request_setting, Mapping)
):
return request_setting
merged_setting = dict_class(to_key_val_list(session_setting))
merged_setting.update(to_key_val_list(request_setting))
# Remove keys that are set to None.
for (k, v) in request_setting.items():
if v is None:
del merged_setting[k]
merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None)
return merged_setting | Determines appropriate setting for a given request, taking into account the
explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class` | entailment |
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None):
"""Receives a Response. Returns a generator of Responses."""
i = 0
hist = [] # keep track of history
while resp.is_redirect:
prepared_request = req.copy()
if i > 0:
# Update history and keep track of redirects.
hist.append(resp)
new_hist = list(hist)
resp.history = new_hist
try:
resp.content # Consume socket so it can be released
except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
resp.raw.read(decode_content=False)
if i >= self.max_redirects:
raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)
# Release the connection back into the pool.
resp.close()
url = resp.headers['location']
method = req.method
# Handle redirection without scheme (see: RFC 1808 Section 4)
if url.startswith('//'):
parsed_rurl = urlparse(resp.url)
url = '%s:%s' % (parsed_rurl.scheme, url)
# The scheme should be lower case...
parsed = urlparse(url)
url = parsed.geturl()
# Facilitate relative 'location' headers, as allowed by RFC 7231.
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
# Compliant with RFC3986, we percent encode the url.
if not parsed.netloc:
url = urljoin(resp.url, requote_uri(url))
else:
url = requote_uri(url)
prepared_request.url = to_native_string(url)
# Cache the url, unless it redirects to itself.
if resp.is_permanent_redirect and req.url != prepared_request.url:
self.redirect_cache[req.url] = prepared_request.url
# http://tools.ietf.org/html/rfc7231#section-6.4.4
if (resp.status_code == codes.see_other and
method != 'HEAD'):
method = 'GET'
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if resp.status_code == codes.found and method != 'HEAD':
method = 'GET'
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if resp.status_code == codes.moved and method == 'POST':
method = 'GET'
prepared_request.method = method
# https://github.com/kennethreitz/requests/issues/1084
if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
if 'Content-Length' in prepared_request.headers:
del prepared_request.headers['Content-Length']
prepared_request.body = None
headers = prepared_request.headers
try:
del headers['Cookie']
except KeyError:
pass
# Extract any cookies sent on the response to the cookiejar
# in the new request. Because we've mutated our copied prepared
# request, use the old one that we haven't yet touched.
extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
prepared_request._cookies.update(self.cookies)
prepared_request.prepare_cookies(prepared_request._cookies)
# Rebuild auth and proxy information.
proxies = self.rebuild_proxies(prepared_request, proxies)
self.rebuild_auth(prepared_request, resp)
# Override the original request.
req = prepared_request
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
)
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
i += 1
yield resp | Receives a Response. Returns a generator of Responses. | entailment |
def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefault('cert', self.cert)
kwargs.setdefault('proxies', self.proxies)
# It's possible that users might accidentally send a Request object.
# Guard against that specific failure case.
if not isinstance(request, PreparedRequest):
raise ValueError('You can only send PreparedRequests.')
checked_urls = set()
while request.url in self.redirect_cache:
checked_urls.add(request.url)
new_url = self.redirect_cache.get(request.url)
if new_url in checked_urls:
break
request.url = new_url
# Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop('allow_redirects', True)
stream = kwargs.get('stream')
timeout = kwargs.get('timeout')
verify = kwargs.get('verify')
cert = kwargs.get('cert')
proxies = kwargs.get('proxies')
hooks = request.hooks
# Get the appropriate adapter to use
adapter = self.get_adapter(url=request.url)
# Start time (approximately) of the request
start = datetime.utcnow()
# Send the request
r = adapter.send(request, **kwargs)
# Total elapsed time of the request (approximately)
r.elapsed = datetime.utcnow() - start
# Response manipulation hooks
r = dispatch_hook('response', hooks, r, **kwargs)
# Persist cookies
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self.cookies, request, r.raw)
# Redirect resolving generator.
gen = self.resolve_redirects(r, request,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies)
# Resolve redirects if allowed.
history = [resp for resp in gen] if allow_redirects else []
# Shuffle things around if there's history.
if history:
# Insert the first (original) request at the start
history.insert(0, r)
# Get the last request made
r = history.pop()
r.history = history
if not stream:
r.content
return r | Send a given PreparedRequest. | entailment |
def stream(self, amt=2**16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
while not is_fp_closed(self._fp):
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data | A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header. | entailment |
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper() | Prepares the given HTTP method. | entailment |
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
if headers:
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
else:
self.headers = CaseInsensitiveDict() | Prepares the given HTTP headers. | entailment |
def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
def generate():
try:
# Special case for urllib3.
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except AttributeError:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks | Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response. | entailment |
def json(self, **kwargs):
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
if not self.encoding and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return json.loads(self.content.decode(encoding), **kwargs)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
return json.loads(self.text, **kwargs) | Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes. | entailment |
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600:
http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
if http_error_msg:
raise HTTPError(http_error_msg, response=self) | Raises stored :class:`HTTPError`, if one occurred. | entailment |
def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.
"""
pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs) | Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization. | entailment |
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
if not host:
raise LocationValueError("No host specified.")
scheme = scheme or 'http'
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
with self.pools.lock:
# If the scheme, host, or port doesn't match existing open
# connections, open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
pool = self._new_pool(scheme, host, port)
self.pools[pool_key] = pool
return pool | Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. | entailment |
def genty_repeat(count):
"""
To use in conjunction with a TestClass wrapped with @genty.
Runs the wrapped test 'count' times:
@genty_repeat(count)
def test_some_function(self)
...
Can also wrap a test already decorated with @genty_dataset
@genty_repeat(3)
@genty_dataset(True, False)
def test_some__other_function(self, bool_value):
...
This will run 6 tests in total, 3 each of the True and False cases.
:param count:
The number of times to run the test.
:type count:
`int`
"""
if count < 0:
raise ValueError(
"Really? Can't have {0} iterations. Please pick a value >= 0."
.format(count)
)
def wrap(test_method):
test_method.genty_repeat_count = count
return test_method
return wrap | To use in conjunction with a TestClass wrapped with @genty.
Runs the wrapped test 'count' times:
@genty_repeat(count)
def test_some_function(self)
...
Can also wrap a test already decorated with @genty_dataset
@genty_repeat(3)
@genty_dataset(True, False)
def test_some__other_function(self, bool_value):
...
This will run 6 tests in total, 3 each of the True and False cases.
:param count:
The number of times to run the test.
:type count:
`int` | entailment |
def command(name=None):
"""A decorator to register a subcommand with the global `Subcommands` instance.
"""
def decorator(f):
_commands.append((name, f))
return f
return decorator | A decorator to register a subcommand with the global `Subcommands` instance. | entailment |
def main(program=None,
version=None,
doc_template=None,
commands=None,
argv=None,
exit_at_end=True):
"""Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
doc_template: The top-level docstring template for your program. If
`None`, a standard default version is applied.
commands: A `Subcommands` instance.
argv: The command-line arguments to parse. If `None`, this defaults to
`sys.argv[1:]`
exit_at_end: Whether to call `sys.exit()` at the end of the function.
There are two ways to use this function. First, you can pass `program`,
`version`, and `doc_template`, in which case `docopt_subcommands` will use
these arguments along with the subcommands registered with `command()` to
define you program.
The second way to use this function is to pass in a `Subcommands` objects
via the `commands` argument. In this case the `program`, `version`, and
`doc_template` arguments are ignored, and the `Subcommands` instance takes
precedence.
In both cases the `argv` argument can be used to specify the arguments to
be parsed.
"""
if commands is None:
if program is None:
raise ValueError(
'`program` required if subcommand object not provided')
if version is None:
raise ValueError(
'`version` required if subcommand object not provided')
commands = Subcommands(program,
version,
doc_template=doc_template)
for name, handler in _commands:
commands.add_command(handler, name)
if argv is None:
argv = sys.argv[1:]
result = commands(argv)
if exit_at_end:
sys.exit(result)
else:
return result | Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
doc_template: The top-level docstring template for your program. If
`None`, a standard default version is applied.
commands: A `Subcommands` instance.
argv: The command-line arguments to parse. If `None`, this defaults to
`sys.argv[1:]`
exit_at_end: Whether to call `sys.exit()` at the end of the function.
There are two ways to use this function. First, you can pass `program`,
`version`, and `doc_template`, in which case `docopt_subcommands` will use
these arguments along with the subcommands registered with `command()` to
define you program.
The second way to use this function is to pass in a `Subcommands` objects
via the `commands` argument. In this case the `program`, `version`, and
`doc_template` arguments are ignored, and the `Subcommands` instance takes
precedence.
In both cases the `argv` argument can be used to specify the arguments to
be parsed. | entailment |
def process_response(self, request, response, spider):
"""Overridden process_response would "pipe" response.body through BeautifulSoup."""
return response.replace(body=str(BeautifulSoup(response.body, self.parser))) | Overridden process_response would "pipe" response.body through BeautifulSoup. | entailment |
def genty(target_cls):
"""
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class`
"""
tests = _expand_tests(target_cls)
tests_with_datasets = _expand_datasets(tests)
tests_with_datasets_and_repeats = _expand_repeats(tests_with_datasets)
_add_new_test_methods(target_cls, tests_with_datasets_and_repeats)
return target_cls | This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class` | entailment |
def _expand_datasets(test_functions):
"""
Generator producing test_methods, with an optional dataset.
:param test_functions:
Iterator over tuples of test name and test unbound function.
:type test_functions:
`iterator` of `tuple` of (`unicode`, `function`)
:return:
Generator yielding a tuple of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset name : String representation of the given dataset
- dataset : Tuple representing the args for a test
- param factory : Function that returns params for the test method
:rtype:
`generator` of `tuple` of (
`unicode`,
`function`,
`unicode` or None,
`tuple` or None,
`function` or None,
)
"""
for name, func in test_functions:
dataset_tuples = chain(
[(None, getattr(func, 'genty_datasets', {}))],
getattr(func, 'genty_dataproviders', []),
)
no_datasets = True
for dataprovider, datasets in dataset_tuples:
for dataset_name, dataset in six.iteritems(datasets):
no_datasets = False
yield name, func, dataset_name, dataset, dataprovider
if no_datasets:
# yield the original test method, unaltered
yield name, func, None, None, None | Generator producing test_methods, with an optional dataset.
:param test_functions:
Iterator over tuples of test name and test unbound function.
:type test_functions:
`iterator` of `tuple` of (`unicode`, `function`)
:return:
Generator yielding a tuple of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset name : String representation of the given dataset
- dataset : Tuple representing the args for a test
- param factory : Function that returns params for the test method
:rtype:
`generator` of `tuple` of (
`unicode`,
`function`,
`unicode` or None,
`tuple` or None,
`function` or None,
) | entailment |
def _expand_repeats(test_functions):
"""
Generator producing test_methods, with any repeat count unrolled.
:param test_functions:
Sequence of tuples of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset name : String representation of the given dataset
- dataset : Tuple representing the args for a test
- param factory : Function that returns params for the test method
:type test_functions:
`iterator` of `tuple` of
(`unicode`, `function`, `unicode` or None, `tuple` or None, `function`)
:return:
Generator yielding a tuple of
(method_name, unbound function, dataset, name dataset, repeat_suffix)
:rtype:
`generator` of `tuple` of (`unicode`, `function`,
`unicode` or None, `tuple` or None, `function`, `unicode`)
"""
for name, func, dataset_name, dataset, dataprovider in test_functions:
repeat_count = getattr(func, 'genty_repeat_count', 0)
if repeat_count:
for i in range(1, repeat_count + 1):
repeat_suffix = _build_repeat_suffix(i, repeat_count)
yield (
name,
func,
dataset_name,
dataset,
dataprovider,
repeat_suffix,
)
else:
yield name, func, dataset_name, dataset, dataprovider, None | Generator producing test_methods, with any repeat count unrolled.
:param test_functions:
Sequence of tuples of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset name : String representation of the given dataset
- dataset : Tuple representing the args for a test
- param factory : Function that returns params for the test method
:type test_functions:
`iterator` of `tuple` of
(`unicode`, `function`, `unicode` or None, `tuple` or None, `function`)
:return:
Generator yielding a tuple of
(method_name, unbound function, dataset, name dataset, repeat_suffix)
:rtype:
`generator` of `tuple` of (`unicode`, `function`,
`unicode` or None, `tuple` or None, `function`, `unicode`) | entailment |
def _is_referenced_in_argv(method_name):
"""
Various test runners allow one to run a specific test like so:
python -m unittest -v <test_module>.<test_name>
Return True is the given method name is so referenced.
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:return:
Is the given method referenced by the command line.
:rtype:
`bool`
"""
expr = '.*[:.]{0}$'.format(method_name)
regex = re.compile(expr)
return any(regex.match(arg) for arg in sys.argv) | Various test runners allow one to run a specific test like so:
python -m unittest -v <test_module>.<test_name>
Return True is the given method name is so referenced.
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:return:
Is the given method referenced by the command line.
:rtype:
`bool` | entailment |
def _build_repeat_suffix(iteration, count):
"""
Return the suffix string to identify iteration X out of Y.
For example, with a count of 100, this will build strings like
"iteration_053" or "iteration_008".
:param iteration:
Current iteration.
:type iteration:
`int`
:param count:
Total number of iterations.
:type count:
`int`
:return:
Repeat suffix.
:rtype:
`unicode`
"""
format_width = int(math.ceil(math.log(count + 1, 10)))
new_suffix = 'iteration_{0:0{width}d}'.format(
iteration,
width=format_width
)
return new_suffix | Return the suffix string to identify iteration X out of Y.
For example, with a count of 100, this will build strings like
"iteration_053" or "iteration_008".
:param iteration:
Current iteration.
:type iteration:
`int`
:param count:
Total number of iterations.
:type count:
`int`
:return:
Repeat suffix.
:rtype:
`unicode` | entailment |
def _build_final_method_name(
method_name,
dataset_name,
dataprovider_name,
repeat_suffix,
):
"""
Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hello')"
Example: a test called 'test_other_stuff' with dataset of (9) and repeats
Return: "test_other_stuff(9) iteration_<X>"
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param dataset_name:
Base name of the data set.
:type dataset_name:
`unicode` or None
:param dataprovider_name:
If there's a dataprovider involved, then this is its name.
:type dataprovider_name:
`unicode` or None
:param repeat_suffix:
Suffix to append to the name of the generated method.
:type repeat_suffix:
`unicode` or None
:return:
The fully composed name of the generated test method.
:rtype:
`unicode`
"""
# For tests using a dataprovider, append "_<dataprovider_name>" to
# the test method name
suffix = ''
if dataprovider_name:
suffix = '_{0}'.format(dataprovider_name)
if not dataset_name and not repeat_suffix:
return '{0}{1}'.format(method_name, suffix)
if dataset_name:
# Nosetest multi-processing code parses the full test name
# to discern package/module names. Thus any periods in the test-name
# causes that code to fail. So replace any periods with the unicode
# middle-dot character. Yes, this change is applied independent
# of the test runner being used... and that's fine since there is
# no real contract as to how the fabricated tests are named.
dataset_name = dataset_name.replace('.', REPLACE_FOR_PERIOD_CHAR)
# Place data_set info inside parens, as if it were a function call
suffix = '{0}({1})'.format(suffix, dataset_name or "")
if repeat_suffix:
suffix = '{0} {1}'.format(suffix, repeat_suffix)
test_method_name_for_dataset = "{0}{1}".format(
method_name,
suffix,
)
return test_method_name_for_dataset | Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hello')"
Example: a test called 'test_other_stuff' with dataset of (9) and repeats
Return: "test_other_stuff(9) iteration_<X>"
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param dataset_name:
Base name of the data set.
:type dataset_name:
`unicode` or None
:param dataprovider_name:
If there's a dataprovider involved, then this is its name.
:type dataprovider_name:
`unicode` or None
:param repeat_suffix:
Suffix to append to the name of the generated method.
:type repeat_suffix:
`unicode` or None
:return:
The fully composed name of the generated test method.
:rtype:
`unicode` | entailment |
def _build_dataset_method(method, dataset):
"""
Return a fabricated method that marshals the dataset into parameters
for given 'method'
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of the dataset.
:type dataset:
`tuple` or :class:`GentyArgs`
:return:
Return an unbound function that will become a test method
:rtype:
`function`
"""
if isinstance(dataset, GentyArgs):
test_method = lambda my_self: method(
my_self,
*dataset.args,
**dataset.kwargs
)
else:
test_method = lambda my_self: method(
my_self,
*dataset
)
return test_method | Return a fabricated method that marshals the dataset into parameters
for given 'method'
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of the dataset.
:type dataset:
`tuple` or :class:`GentyArgs`
:return:
Return an unbound function that will become a test method
:rtype:
`function` | entailment |
def _build_dataprovider_method(method, dataset, dataprovider):
"""
Return a fabricated method that calls the dataprovider with the given
dataset, and marshals the return value from that into params to the
underlying test 'method'.
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of the dataset.
:type dataset:
`tuple` or :class:`GentyArgs`
:param dataprovider:
The unbound function that's responsible for generating the actual
params that will be passed to the test function.
:type dataprovider:
`callable`
:return:
Return an unbound function that will become a test method
:rtype:
`function`
"""
if isinstance(dataset, GentyArgs):
final_args = dataset.args
final_kwargs = dataset.kwargs
else:
final_args = dataset
final_kwargs = {}
def test_method_wrapper(my_self):
args = dataprovider(
my_self,
*final_args,
**final_kwargs
)
kwargs = {}
if isinstance(args, GentyArgs):
kwargs = args.kwargs
args = args.args
elif not isinstance(args, (tuple, list)):
args = (args, )
return method(my_self, *args, **kwargs)
return test_method_wrapper | Return a fabricated method that calls the dataprovider with the given
dataset, and marshals the return value from that into params to the
underlying test 'method'.
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of the dataset.
:type dataset:
`tuple` or :class:`GentyArgs`
:param dataprovider:
The unbound function that's responsible for generating the actual
params that will be passed to the test function.
:type dataprovider:
`callable`
:return:
Return an unbound function that will become a test method
:rtype:
`function` | entailment |
def _add_method_to_class(
target_cls,
method_name,
func,
dataset_name,
dataset,
dataprovider,
repeat_suffix,
):
"""
Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
`class`
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param func:
The underlying test function to call.
:type func:
`callable`
:param dataset_name:
Base name of the data set.
:type dataset_name:
`unicode` or None
:param dataset:
Tuple containing the args of the dataset.
:type dataset:
`tuple` or None
:param repeat_suffix:
Suffix to append to the name of the generated method.
:type repeat_suffix:
`unicode` or None
:param dataprovider:
The unbound function that's responsible for generating the actual
params that will be passed to the test function. Can be None.
:type dataprovider:
`callable`
"""
# pylint: disable=too-many-arguments
test_method_name_for_dataset = _build_final_method_name(
method_name,
dataset_name,
dataprovider.__name__ if dataprovider else None,
repeat_suffix,
)
test_method_for_dataset = _build_test_method(func, dataset, dataprovider)
test_method_for_dataset = functools.update_wrapper(
test_method_for_dataset,
func,
)
test_method_name_for_dataset = encode_non_ascii_string(
test_method_name_for_dataset,
)
test_method_for_dataset.__name__ = test_method_name_for_dataset
test_method_for_dataset.genty_generated_test = True
# Add the method to the class under the proper name
setattr(target_cls, test_method_name_for_dataset, test_method_for_dataset) | Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
`class`
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param func:
The underlying test function to call.
:type func:
`callable`
:param dataset_name:
Base name of the data set.
:type dataset_name:
`unicode` or None
:param dataset:
Tuple containing the args of the dataset.
:type dataset:
`tuple` or None
:param repeat_suffix:
Suffix to append to the name of the generated method.
:type repeat_suffix:
`unicode` or None
:param dataprovider:
The unbound function that's responsible for generating the actual
params that will be passed to the test function. Can be None.
:type dataprovider:
`callable` | entailment |
def close(self):
"""Close any open window.
Note that this only works with non-blocking methods.
"""
if self._process:
# Be nice first.
self._process.send_signal(signal.SIGINT)
# If it doesn't close itself promptly, be brutal.
# Python 3.2+ added the timeout option to wait() and the
# corresponding TimeoutExpired exception. If they exist, use them.
if hasattr(subprocess, 'TimeoutExpired'):
try:
self._process.wait(timeout=1)
except subprocess.TimeoutExpired:
self._process.send_signal(signal.SIGKILL)
# Otherwise, roll our own polling loop.
else:
# Give it 1s, checking every 10ms.
count = 0
while count < 100:
if self._process.poll() is not None:
break
time.sleep(0.01)
# Still hasn't quit.
if self._process.poll() is None:
self._process.send_signal(signal.SIGKILL)
# Clean up.
self._process = None | Close any open window.
Note that this only works with non-blocking methods. | entailment |
def _run_blocking(self, args, input=None):
"""Internal API: run a blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: string
Value to feed to the stdin of the process.
Returns
-------
(returncode, stdout)
The exit code (integer) and stdout value (string) from the process.
"""
# Close any existing dialog.
if self._process:
self.close()
# Make sure we grab stdout as text (not bytes).
kwargs = {}
kwargs['stdout'] = subprocess.PIPE
kwargs['universal_newlines'] = True
# Use the run() method if available (Python 3.5+).
if hasattr(subprocess, 'run'):
result = subprocess.run(args, input=input, **kwargs)
return result.returncode, result.stdout
# Have to do our own. If we need to feed stdin, we must open a pipe.
if input is not None:
kwargs['stdin'] = subprocess.PIPE
# Start the process.
with Popen(args, **kwargs) as proc:
# Talk to it (no timeout). This will wait until termination.
stdout, stderr = proc.communicate(input)
# Find out the return code.
returncode = proc.poll()
# Done.
return returncode, stdout | Internal API: run a blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: string
Value to feed to the stdin of the process.
Returns
-------
(returncode, stdout)
The exit code (integer) and stdout value (string) from the process. | entailment |
def _run_nonblocking(self, args, input=None):
"""Internal API: run a non-blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: string
Value to feed to the stdin of the process.
"""
# Close any existing dialog.
if self._process:
self.close()
# Start the new one.
self._process = subprocess.Popen(args, stdout=subprocess.PIPE) | Internal API: run a non-blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: string
Value to feed to the stdin of the process. | entailment |
def error(self, message, rofi_args=None, **kwargs):
"""Show an error window.
This method blocks until the user presses a key.
Fullscreen mode is not supported for error windows, and if specified
will be ignored.
Parameters
----------
message: string
Error message to show.
"""
rofi_args = rofi_args or []
# Generate arguments list.
args = ['rofi', '-e', message]
args.extend(self._common_args(allow_fullscreen=False, **kwargs))
args.extend(rofi_args)
# Close any existing window and show the error.
self._run_blocking(args) | Show an error window.
This method blocks until the user presses a key.
Fullscreen mode is not supported for error windows, and if specified
will be ignored.
Parameters
----------
message: string
Error message to show. | entailment |
def status(self, message, rofi_args=None, **kwargs):
"""Show a status message.
This method is non-blocking, and intended to give a status update to
the user while something is happening in the background.
To close the window, either call the close() method or use any of the
display methods to replace it with a different window.
Fullscreen mode is not supported for status messages and if specified
will be ignored.
Parameters
----------
message: string
Progress message to show.
"""
rofi_args = rofi_args or []
# Generate arguments list.
args = ['rofi', '-e', message]
args.extend(self._common_args(allow_fullscreen=False, **kwargs))
args.extend(rofi_args)
# Update the status.
self._run_nonblocking(args) | Show a status message.
This method is non-blocking, and intended to give a status update to
the user while something is happening in the background.
To close the window, either call the close() method or use any of the
display methods to replace it with a different window.
Fullscreen mode is not supported for status messages and if specified
will be ignored.
Parameters
----------
message: string
Progress message to show. | entailment |
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs):
"""Show a list of options and return user selection.
This method blocks until the user makes their choice.
Parameters
----------
prompt: string
The prompt telling the user what they are selecting.
options: list of strings
The options they can choose from. Any newline characters are
replaced with spaces.
message: string, optional
Message to show between the prompt and the options. This can
contain Pango markup, and any text content should be escaped.
select: integer, optional
Set which option is initially selected.
keyN: tuple (string, string); optional
Custom key bindings where N is one or greater. The first entry in
the tuple should be a string defining the key, e.g., "Alt+x" or
"Delete". Note that letter keys should be lowercase ie.e., Alt+a
not Alt+A.
The second entry should be a short string stating the action the
key will take. This is displayed to the user at the top of the
dialog. If None or an empty string, it is not displayed (but the
binding is still set).
By default, key1 through key9 are set to ("Alt+1", None) through
("Alt+9", None) respectively.
Returns
-------
tuple (index, key)
The index of the option the user selected, or -1 if they cancelled
the dialog.
Key indicates which key was pressed, with 0 being 'OK' (generally
Enter), -1 being 'Cancel' (generally escape), and N being custom
key N.
"""
rofi_args = rofi_args or []
# Replace newlines and turn the options into a single string.
optionstr = '\n'.join(option.replace('\n', ' ') for option in options)
# Set up arguments.
args = ['rofi', '-dmenu', '-p', prompt, '-format', 'i']
if select is not None:
args.extend(['-selected-row', str(select)])
# Key bindings to display.
display_bindings = []
# Configure the key bindings.
user_keys = set()
for k, v in kwargs.items():
# See if the keyword name matches the needed format.
if not k.startswith('key'):
continue
try:
keynum = int(k[3:])
except ValueError:
continue
# Add it to the set.
key, action = v
user_keys.add(keynum)
args.extend(['-kb-custom-{0:s}'.format(k[3:]), key])
if action:
display_bindings.append("<b>{0:s}</b>: {1:s}".format(key, action))
# And the global exit bindings.
exit_keys = set()
next_key = 10
for key in self.exit_hotkeys:
while next_key in user_keys:
next_key += 1
exit_keys.add(next_key)
args.extend(['-kb-custom-{0:d}'.format(next_key), key])
next_key += 1
# Add any displayed key bindings to the message.
message = message or ""
if display_bindings:
message += "\n" + " ".join(display_bindings)
message = message.strip()
# If we have a message, add it to the arguments.
if message:
args.extend(['-mesg', message])
# Add in common arguments.
args.extend(self._common_args(**kwargs))
args.extend(rofi_args)
# Run the dialog.
returncode, stdout = self._run_blocking(args, input=optionstr)
# Figure out which option was selected.
stdout = stdout.strip()
index = int(stdout) if stdout else -1
# And map the return code to a key.
if returncode == 0:
key = 0
elif returncode == 1:
key = -1
elif returncode > 9:
key = returncode - 9
if key in exit_keys:
raise SystemExit()
else:
self.exit_with_error("Unexpected rofi returncode {0:d}.".format(results.returncode))
# And return.
return index, key | Show a list of options and return user selection.
This method blocks until the user makes their choice.
Parameters
----------
prompt: string
The prompt telling the user what they are selecting.
options: list of strings
The options they can choose from. Any newline characters are
replaced with spaces.
message: string, optional
Message to show between the prompt and the options. This can
contain Pango markup, and any text content should be escaped.
select: integer, optional
Set which option is initially selected.
keyN: tuple (string, string); optional
Custom key bindings where N is one or greater. The first entry in
the tuple should be a string defining the key, e.g., "Alt+x" or
"Delete". Note that letter keys should be lowercase ie.e., Alt+a
not Alt+A.
The second entry should be a short string stating the action the
key will take. This is displayed to the user at the top of the
dialog. If None or an empty string, it is not displayed (but the
binding is still set).
By default, key1 through key9 are set to ("Alt+1", None) through
("Alt+9", None) respectively.
Returns
-------
tuple (index, key)
The index of the option the user selected, or -1 if they cancelled
the dialog.
Key indicates which key was pressed, with 0 being 'OK' (generally
Enter), -1 being 'Cancel' (generally escape), and N being custom
key N. | entailment |
def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs):
"""A generic entry box.
Parameters
----------
prompt: string
Text prompt for the entry.
validator: function, optional
A function to validate and convert the value entered by the user.
It should take one parameter, the string that the user entered, and
return a tuple (value, error). The value should be the users entry
converted to the appropriate Python type, or None if the entry was
invalid. The error message should be a string telling the user what
was wrong, or None if the entry was valid. The prompt will be
re-displayed to the user (along with the error message) until they
enter a valid value. If no validator is given, the text that the
user entered is returned as-is.
message: string
Optional message to display under the entry.
Returns
-------
The value returned by the validator, or None if the dialog was
cancelled.
Examples
--------
Enforce a minimum entry length:
>>> r = Rofi()
>>> validator = lambda s: (s, None) if len(s) > 6 else (None, "Too short")
>>> r.generic_entry('Enter a 7-character or longer string: ', validator)
"""
error = ""
rofi_args = rofi_args or []
# Keep going until we get something valid.
while True:
args = ['rofi', '-dmenu', '-p', prompt, '-format', 's']
# Add any error to the given message.
msg = message or ""
if error:
msg = '<span color="#FF0000" font_weight="bold">{0:s}</span>\n{1:s}'.format(error, msg)
msg = msg.rstrip('\n')
# If there is actually a message to show.
if msg:
args.extend(['-mesg', msg])
# Add in common arguments.
args.extend(self._common_args(**kwargs))
args.extend(rofi_args)
# Run it.
returncode, stdout = self._run_blocking(args, input="")
# Was the dialog cancelled?
if returncode == 1:
return None
# Get rid of the trailing newline and check its validity.
text = stdout.rstrip('\n')
if validator:
value, error = validator(text)
if not error:
return value
else:
return text | A generic entry box.
Parameters
----------
prompt: string
Text prompt for the entry.
validator: function, optional
A function to validate and convert the value entered by the user.
It should take one parameter, the string that the user entered, and
return a tuple (value, error). The value should be the users entry
converted to the appropriate Python type, or None if the entry was
invalid. The error message should be a string telling the user what
was wrong, or None if the entry was valid. The prompt will be
re-displayed to the user (along with the error message) until they
enter a valid value. If no validator is given, the text that the
user entered is returned as-is.
message: string
Optional message to display under the entry.
Returns
-------
The value returned by the validator, or None if the dialog was
cancelled.
Examples
--------
Enforce a minimum entry length:
>>> r = Rofi()
>>> validator = lambda s: (s, None) if len(s) > 6 else (None, "Too short")
>>> r.generic_entry('Enter a 7-character or longer string: ', validator) | entailment |
def text_entry(self, prompt, message=None, allow_blank=False, strip=True,
rofi_args=None, **kwargs):
"""Prompt the user to enter a piece of text.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
allow_blank: Boolean
Whether to allow blank entries.
strip: Boolean
Whether to strip leading and trailing whitespace from the entered
value.
Returns
-------
string, or None if the dialog was cancelled.
"""
def text_validator(text):
if strip:
text = text.strip()
if not allow_blank:
if not text:
return None, "A value is required."
return text, None
return self.generic_entry(prompt, text_validator, message, rofi_args, **kwargs) | Prompt the user to enter a piece of text.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
allow_blank: Boolean
Whether to allow blank entries.
strip: Boolean
Whether to strip leading and trailing whitespace from the entered
value.
Returns
-------
string, or None if the dialog was cancelled. | entailment |
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: integer, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
integer, or None if the dialog is cancelled.
"""
# Sanity check.
if (min is not None) and (max is not None) and not (max > min):
raise ValueError("Maximum limit has to be more than the minimum limit.")
def integer_validator(text):
error = None
# Attempt to convert to integer.
try:
value = int(text)
except ValueError:
return None, "Please enter an integer value."
# Check its within limits.
if (min is not None) and (value < min):
return None, "The minimum allowable value is {0:d}.".format(min)
if (max is not None) and (value > max):
return None, "The maximum allowable value is {0:d}.".format(max)
return value, None
return self.generic_entry(prompt, integer_validator, message, rofi_args, **kwargs) | Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: integer, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
integer, or None if the dialog is cancelled. | entailment |
def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter a floating point number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: float, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
float, or None if the dialog is cancelled.
"""
# Sanity check.
if (min is not None) and (max is not None) and not (max > min):
raise ValueError("Maximum limit has to be more than the minimum limit.")
def float_validator(text):
error = None
# Attempt to convert to float.
try:
value = float(text)
except ValueError:
return None, "Please enter a floating point value."
# Check its within limits.
if (min is not None) and (value < min):
return None, "The minimum allowable value is {0}.".format(min)
if (max is not None) and (value > max):
return None, "The maximum allowable value is {0}.".format(max)
return value, None
return self.generic_entry(prompt, float_validator, message, rofi_args, **kwargs) | Prompt the user to enter a floating point number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: float, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
float, or None if the dialog is cancelled. | entailment |
def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter a decimal number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: Decimal, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
Decimal, or None if the dialog is cancelled.
"""
# Sanity check.
if (min is not None) and (max is not None) and not (max > min):
raise ValueError("Maximum limit has to be more than the minimum limit.")
def decimal_validator(text):
error = None
# Attempt to convert to decimal.
try:
value = Decimal(text)
except InvalidOperation:
return None, "Please enter a decimal value."
# Check its within limits.
if (min is not None) and (value < min):
return None, "The minimum allowable value is {0}.".format(min)
if (max is not None) and (value > max):
return None, "The maximum allowable value is {0}.".format(max)
return value, None
return self.generic_entry(prompt, decimal_validator, message, rofi_args, **kwargs) | Prompt the user to enter a decimal number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
min, max: Decimal, optional
Minimum and maximum values to allow. If None, no limit is imposed.
Returns
-------
Decimal, or None if the dialog is cancelled. | entailment |
def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'],
show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a date.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter dates in. These should be
format strings as accepted by the datetime.datetime.strptime()
function from the standard library. They are tried in order, and
the first that returns a date object without error is selected.
Note that the '%x' in the default list is the current locale's date
representation.
show_example: Boolean
If True, today's date in the first format given is appended to the
message.
Returns
-------
datetime.date, or None if the dialog is cancelled.
"""
def date_validator(text):
# Try them in order.
for format in formats:
try:
dt = datetime.strptime(text, format)
except ValueError:
continue
else:
# This one worked; good enough for us.
return (dt.date(), None)
# None of the formats worked.
return (None, 'Please enter a valid date.')
# Add an example to the message?
if show_example:
message = message or ""
message += "Today's date in the correct format: " + datetime.now().strftime(formats[0])
return self.generic_entry(prompt, date_validator, message, rofi_args, **kwargs) | Prompt the user to enter a date.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter dates in. These should be
format strings as accepted by the datetime.datetime.strptime()
function from the standard library. They are tried in order, and
the first that returns a date object without error is selected.
Note that the '%x' in the default list is the current locale's date
representation.
show_example: Boolean
If True, today's date in the first format given is appended to the
message.
Returns
-------
datetime.date, or None if the dialog is cancelled. | entailment |
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M',
'%I.%M'], show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter times in. These should be
format strings as accepted by the datetime.datetime.strptime()
function from the standard library. They are tried in order, and
the first that returns a time object without error is selected.
Note that the '%X' in the default list is the current locale's time
representation.
show_example: Boolean
If True, the current time in the first format given is appended to
the message.
Returns
-------
datetime.time, or None if the dialog is cancelled.
"""
def time_validator(text):
# Try them in order.
for format in formats:
try:
dt = datetime.strptime(text, format)
except ValueError:
continue
else:
# This one worked; good enough for us.
return (dt.time(), None)
# None of the formats worked.
return (None, 'Please enter a valid time.')
# Add an example to the message?
if show_example:
message = message or ""
message += "Current time in the correct format: " + datetime.now().strftime(formats[0])
return self.generic_entry(prompt, time_validator, message, rofi_args=None, **kwargs) | Prompt the user to enter a time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter times in. These should be
format strings as accepted by the datetime.datetime.strptime()
function from the standard library. They are tried in order, and
the first that returns a time object without error is selected.
Note that the '%X' in the default list is the current locale's time
representation.
show_example: Boolean
If True, the current time in the first format given is appended to
the message.
Returns
-------
datetime.time, or None if the dialog is cancelled. | entailment |
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False,
rofi_args=None, **kwargs):
"""Prompt the user to enter a date and time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter the date and time in. These
should be format strings as accepted by the
datetime.datetime.strptime() function from the standard library.
They are tried in order, and the first that returns a datetime
object without error is selected. Note that the '%x %X' in the
default list is the current locale's date and time representation.
show_example: Boolean
If True, the current date and time in the first format given is appended to
the message.
Returns
-------
datetime.datetime, or None if the dialog is cancelled.
"""
def datetime_validator(text):
# Try them in order.
for format in formats:
try:
dt = datetime.strptime(text, format)
except ValueError:
continue
else:
# This one worked; good enough for us.
return (dt, None)
# None of the formats worked.
return (None, 'Please enter a valid date and time.')
# Add an example to the message?
if show_example:
message = message or ""
message += "Current date and time in the correct format: " + datetime.now().strftime(formats[0])
return self.generic_entry(prompt, datetime_validator, message, rofi_args, **kwargs) | Prompt the user to enter a date and time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the entry line.
formats: list of strings, optional
The formats that the user can enter the date and time in. These
should be format strings as accepted by the
datetime.datetime.strptime() function from the standard library.
They are tried in order, and the first that returns a datetime
object without error is selected. Note that the '%x %X' in the
default list is the current locale's date and time representation.
show_example: Boolean
If True, the current date and time in the first format given is appended to
the message.
Returns
-------
datetime.datetime, or None if the dialog is cancelled. | entailment |
def exit_with_error(self, error, **kwargs):
"""Report an error and exit.
This raises a SystemExit exception to ask the interpreter to quit.
Parameters
----------
error: string
The error to report before quitting.
"""
self.error(error, **kwargs)
raise SystemExit(error) | Report an error and exit.
This raises a SystemExit exception to ask the interpreter to quit.
Parameters
----------
error: string
The error to report before quitting. | entailment |
def format_kwarg(key, value):
"""
Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call.
"""
translator = repr if isinstance(value, six.string_types) else six.text_type
arg_value = translator(value)
return '{0}={1}'.format(key, arg_value) | Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call. | entailment |
def format_arg(value):
"""
:param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode`
"""
translator = repr if isinstance(value, six.string_types) else six.text_type
return translator(value) | :param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode` | entailment |
def encode_non_ascii_string(string):
"""
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str
"""
encoded_string = string.encode('utf-8', 'replace')
if six.PY3:
encoded_string = encoded_string.decode()
return encoded_string | :param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str | entailment |
def genty_dataprovider(builder_function):
"""Decorator defining that this test gets parameters from the given
build_function.
:param builder_function:
A callable that returns parameters that will be passed to the method
decorated by this decorator.
If the builder_function returns a tuple or list, then that will be
passed as *args to the decorated method.
If the builder_function returns a :class:`GentyArgs`, then that will
be used to pass *args and **kwargs to the decorated method.
Any other return value will be treated as a single parameter, and
passed as such to the decorated method.
:type builder_function:
`callable`
"""
datasets = getattr(builder_function, 'genty_datasets', {None: ()})
def wrap(test_method):
# Save the data providers in the test method. This data will be
# consumed by the @genty decorator.
if not hasattr(test_method, 'genty_dataproviders'):
test_method.genty_dataproviders = []
test_method.genty_dataproviders.append(
(builder_function, datasets),
)
return test_method
return wrap | Decorator defining that this test gets parameters from the given
build_function.
:param builder_function:
A callable that returns parameters that will be passed to the method
decorated by this decorator.
If the builder_function returns a tuple or list, then that will be
passed as *args to the decorated method.
If the builder_function returns a :class:`GentyArgs`, then that will
be used to pass *args and **kwargs to the decorated method.
Any other return value will be treated as a single parameter, and
passed as such to the decorated method.
:type builder_function:
`callable` | entailment |
def genty_dataset(*args, **kwargs):
"""Decorator defining data sets to provide to a test.
Inspired by http://sebastian-bergmann.de/archives/
702-Data-Providers-in-PHPUnit-3.2.html
The canonical way to call @genty_dataset, with each argument each
representing a data set to be injected in the test method call:
@genty_dataset(
('a1', 'b1'),
('a2', 'b2'),
)
def test_some_function(a, b)
...
If the test function takes only one parameter, you can replace the tuples
by a single value. So instead of the more verbose:
@genty_dataset(
('c1',),
('c2',),
)
def test_some_other_function(c)
...
One can write:
@genty_dataset('c1', 'c2')
def test_some_other_function(c)
...
For each set of arguments, a suffix identifying that argument set is
built by concatenating the string representation of the arguments
together. You can control the test names for each data set by passing
the data sets as keyword args, where the keyword is the desired suffix.
For example:
@genty_dataset(
('a1', 'b1),
)
def test_function(a, b)
...
produces a test named 'test_function_for_a1_and_b1', while
@genty_dataset(
happy_path=('a1', 'b1'),
)
def test_function(a, b)
...
produces a test named test_function_for_happy_path. These are just
parameters to a method call, so one can have unnamed args first
followed by keyword args
@genty_dataset(
('x', 'y'),
('p', 'q'),
Monday=('a1', 'b1'),
Tuesday=('t1', 't2'),
)
def test_function(a, b)
...
Finally, datasets can be chained. Useful for example if there are
distinct sets of params that make sense (cleaner, more readable, or
semantically nicer) if kept separate. A fabricated example:
@genty_dataset(
*([i for i in range(10)] + [(i, i) for i in range(10)])
)
def test_some_other_function(param1, param2=None)
...
-- vs --
@genty_dataset(*[i for i in range(10)])
@genty_dataset(*[(i, i) for i in range(10)])
def test_some_other_function(param1, param2=None)
...
If the names of datasets conflict across chained genty_datasets, the
key&value pair from the outer (first) decorator will override the
data from the inner.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
datasets = _build_datasets(*args, **kwargs)
def wrap(test_method):
# Save the datasets in the test method. This data will be consumed
# by the @genty decorator.
if not hasattr(test_method, 'genty_datasets'):
test_method.genty_datasets = OrderedDict()
test_method.genty_datasets.update(datasets)
return test_method
return wrap | Decorator defining data sets to provide to a test.
Inspired by http://sebastian-bergmann.de/archives/
702-Data-Providers-in-PHPUnit-3.2.html
The canonical way to call @genty_dataset, with each argument each
representing a data set to be injected in the test method call:
@genty_dataset(
('a1', 'b1'),
('a2', 'b2'),
)
def test_some_function(a, b)
...
If the test function takes only one parameter, you can replace the tuples
by a single value. So instead of the more verbose:
@genty_dataset(
('c1',),
('c2',),
)
def test_some_other_function(c)
...
One can write:
@genty_dataset('c1', 'c2')
def test_some_other_function(c)
...
For each set of arguments, a suffix identifying that argument set is
built by concatenating the string representation of the arguments
together. You can control the test names for each data set by passing
the data sets as keyword args, where the keyword is the desired suffix.
For example:
@genty_dataset(
('a1', 'b1),
)
def test_function(a, b)
...
produces a test named 'test_function_for_a1_and_b1', while
@genty_dataset(
happy_path=('a1', 'b1'),
)
def test_function(a, b)
...
produces a test named test_function_for_happy_path. These are just
parameters to a method call, so one can have unnamed args first
followed by keyword args
@genty_dataset(
('x', 'y'),
('p', 'q'),
Monday=('a1', 'b1'),
Tuesday=('t1', 't2'),
)
def test_function(a, b)
...
Finally, datasets can be chained. Useful for example if there are
distinct sets of params that make sense (cleaner, more readable, or
semantically nicer) if kept separate. A fabricated example:
@genty_dataset(
*([i for i in range(10)] + [(i, i) for i in range(10)])
)
def test_some_other_function(param1, param2=None)
...
-- vs --
@genty_dataset(*[i for i in range(10)])
@genty_dataset(*[(i, i) for i in range(10)])
def test_some_other_function(param1, param2=None)
...
If the names of datasets conflict across chained genty_datasets, the
key&value pair from the outer (first) decorator will override the
data from the inner.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies | entailment |
def _build_datasets(*args, **kwargs):
"""Build the datasets into a dict, where the keys are the name of the
data set and the values are the data sets themselves.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
:return:
The dataset dict.
:rtype:
`dict`
"""
datasets = OrderedDict()
_add_arg_datasets(datasets, args)
_add_kwarg_datasets(datasets, kwargs)
return datasets | Build the datasets into a dict, where the keys are the name of the
data set and the values are the data sets themselves.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
:return:
The dataset dict.
:rtype:
`dict` | entailment |
def _add_arg_datasets(datasets, args):
"""Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
"""
for dataset in args:
# turn a value into a 1-tuple.
if not isinstance(dataset, (tuple, GentyArgs)):
dataset = (dataset,)
# Create a test_name_suffix - basically the parameter list
if isinstance(dataset, GentyArgs):
dataset_strings = dataset # GentyArgs supports iteration
else:
dataset_strings = [format_arg(data) for data in dataset]
test_method_suffix = ", ".join(dataset_strings)
datasets[test_method_suffix] = dataset | Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies | entailment |
def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
for test_method_suffix, dataset in six.iteritems(kwargs):
datasets[test_method_suffix] = dataset | Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies | entailment |
def dedent(s):
"""Removes the hanging dedent from all the first line of a string."""
head, _, tail = s.partition('\n')
dedented_tail = textwrap.dedent(tail)
result = "{head}\n{tail}".format(
head=head,
tail=dedented_tail)
return result | Removes the hanging dedent from all the first line of a string. | entailment |
def top_level_doc(self):
"""The top-level documentation string for the program.
"""
return self._doc_template.format(
available_commands='\n '.join(sorted(self._commands)),
program=self.program) | The top-level documentation string for the program. | entailment |
def command(self, name=None):
"""A decorator to add subcommands.
"""
def decorator(f):
self.add_command(f, name)
return f
return decorator | A decorator to add subcommands. | entailment |
def add_command(self, handler, name=None):
"""Add a subcommand `name` which invokes `handler`.
"""
if name is None:
name = docstring_to_subcommand(handler.__doc__)
# TODO: Prevent overwriting 'help'?
self._commands[name] = handler | Add a subcommand `name` which invokes `handler`. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.