partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
normalize_url
|
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
|
capybara/utils.py
|
def normalize_url(url):
"""
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
"""
uri = urlparse(url)
query = uri.query or ""
pairs = parse_qsl(query)
decoded_pairs = [(unquote(key), value) for key, value in pairs]
encoded_pairs = [(quote(key), value) for key, value in decoded_pairs]
normalized_query = urlencode(encoded_pairs)
return ParseResult(
scheme=uri.scheme,
netloc=uri.netloc,
path=uri.path,
params=uri.params,
query=normalized_query,
fragment=uri.fragment).geturl()
|
def normalize_url(url):
"""
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
"""
uri = urlparse(url)
query = uri.query or ""
pairs = parse_qsl(query)
decoded_pairs = [(unquote(key), value) for key, value in pairs]
encoded_pairs = [(quote(key), value) for key, value in decoded_pairs]
normalized_query = urlencode(encoded_pairs)
return ParseResult(
scheme=uri.scheme,
netloc=uri.netloc,
path=uri.path,
params=uri.params,
query=normalized_query,
fragment=uri.fragment).geturl()
|
[
"Returns",
"the",
"given",
"URL",
"with",
"all",
"query",
"keys",
"properly",
"escaped",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/utils.py#L153-L178
|
[
"def",
"normalize_url",
"(",
"url",
")",
":",
"uri",
"=",
"urlparse",
"(",
"url",
")",
"query",
"=",
"uri",
".",
"query",
"or",
"\"\"",
"pairs",
"=",
"parse_qsl",
"(",
"query",
")",
"decoded_pairs",
"=",
"[",
"(",
"unquote",
"(",
"key",
")",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"pairs",
"]",
"encoded_pairs",
"=",
"[",
"(",
"quote",
"(",
"key",
")",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"decoded_pairs",
"]",
"normalized_query",
"=",
"urlencode",
"(",
"encoded_pairs",
")",
"return",
"ParseResult",
"(",
"scheme",
"=",
"uri",
".",
"scheme",
",",
"netloc",
"=",
"uri",
".",
"netloc",
",",
"path",
"=",
"uri",
".",
"path",
",",
"params",
"=",
"uri",
".",
"params",
",",
"query",
"=",
"normalized_query",
",",
"fragment",
"=",
"uri",
".",
"fragment",
")",
".",
"geturl",
"(",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
setter_decorator
|
Define a write-only property that, in addition to the given setter function, also
provides a setter decorator defined as the property's getter function.
This allows one to set the property either through traditional assignment, as a
method argument, or through decoration::
class Widget(object):
@setter_decorator
def handler(self, value):
self._handler = value
widget = Widget()
# Method 1: Traditional assignment
widget.handler = lambda input: process(input)
# Method 2: Assignment via method argument
widget.handler(lambda input: process(input))
# Method 3: Assignment via decoration
@widget.handler
def handler(input):
return process(input)
# Method 3b: Assignment via decoration with extraneous parens
@widget.handler()
def handler(input):
return process(input)
|
capybara/utils.py
|
def setter_decorator(fset):
"""
Define a write-only property that, in addition to the given setter function, also
provides a setter decorator defined as the property's getter function.
This allows one to set the property either through traditional assignment, as a
method argument, or through decoration::
class Widget(object):
@setter_decorator
def handler(self, value):
self._handler = value
widget = Widget()
# Method 1: Traditional assignment
widget.handler = lambda input: process(input)
# Method 2: Assignment via method argument
widget.handler(lambda input: process(input))
# Method 3: Assignment via decoration
@widget.handler
def handler(input):
return process(input)
# Method 3b: Assignment via decoration with extraneous parens
@widget.handler()
def handler(input):
return process(input)
"""
def fget(self):
def inner(value):
fset(self, value)
def outer(value=None):
if value:
# We are being called with the desired value, either directly or
# as a decorator.
inner(value)
else:
# Assume we are being called as a decorator with extraneous parens,
# so return the setter as the actual decorator.
return inner
return outer
fdoc = fset.__doc__
return property(fget, fset, None, fdoc)
|
def setter_decorator(fset):
"""
Define a write-only property that, in addition to the given setter function, also
provides a setter decorator defined as the property's getter function.
This allows one to set the property either through traditional assignment, as a
method argument, or through decoration::
class Widget(object):
@setter_decorator
def handler(self, value):
self._handler = value
widget = Widget()
# Method 1: Traditional assignment
widget.handler = lambda input: process(input)
# Method 2: Assignment via method argument
widget.handler(lambda input: process(input))
# Method 3: Assignment via decoration
@widget.handler
def handler(input):
return process(input)
# Method 3b: Assignment via decoration with extraneous parens
@widget.handler()
def handler(input):
return process(input)
"""
def fget(self):
def inner(value):
fset(self, value)
def outer(value=None):
if value:
# We are being called with the desired value, either directly or
# as a decorator.
inner(value)
else:
# Assume we are being called as a decorator with extraneous parens,
# so return the setter as the actual decorator.
return inner
return outer
fdoc = fset.__doc__
return property(fget, fset, None, fdoc)
|
[
"Define",
"a",
"write",
"-",
"only",
"property",
"that",
"in",
"addition",
"to",
"the",
"given",
"setter",
"function",
"also",
"provides",
"a",
"setter",
"decorator",
"defined",
"as",
"the",
"property",
"s",
"getter",
"function",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/utils.py#L181-L231
|
[
"def",
"setter_decorator",
"(",
"fset",
")",
":",
"def",
"fget",
"(",
"self",
")",
":",
"def",
"inner",
"(",
"value",
")",
":",
"fset",
"(",
"self",
",",
"value",
")",
"def",
"outer",
"(",
"value",
"=",
"None",
")",
":",
"if",
"value",
":",
"# We are being called with the desired value, either directly or",
"# as a decorator.",
"inner",
"(",
"value",
")",
"else",
":",
"# Assume we are being called as a decorator with extraneous parens,",
"# so return the setter as the actual decorator.",
"return",
"inner",
"return",
"outer",
"fdoc",
"=",
"fset",
".",
"__doc__",
"return",
"property",
"(",
"fget",
",",
"fset",
",",
"None",
",",
"fdoc",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
AbstractFilter._valid_value
|
bool: Whether the given value is valid.
|
capybara/selector/abstract_filter.py
|
def _valid_value(self, value):
""" bool: Whether the given value is valid. """
if not self.valid_values:
return True
valid_values = (self.valid_values if isinstance(self.valid_values, list)
else list(self.valid_values))
return value in valid_values
|
def _valid_value(self, value):
""" bool: Whether the given value is valid. """
if not self.valid_values:
return True
valid_values = (self.valid_values if isinstance(self.valid_values, list)
else list(self.valid_values))
return value in valid_values
|
[
"bool",
":",
"Whether",
"the",
"given",
"value",
"is",
"valid",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/abstract_filter.py#L46-L54
|
[
"def",
"_valid_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"valid_values",
":",
"return",
"True",
"valid_values",
"=",
"(",
"self",
".",
"valid_values",
"if",
"isinstance",
"(",
"self",
".",
"valid_values",
",",
"list",
")",
"else",
"list",
"(",
"self",
".",
"valid_values",
")",
")",
"return",
"value",
"in",
"valid_values"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.attach_file
|
Find a file field on the page and attach a file given its path. The file field can be found
via its name, id, or label text. ::
page.attach_file(locator, "/path/to/file.png")
Args:
locator_or_path (str): Which field to attach the file to, or the path of the file that
will be attached.
path (str, optional): The path of the file that will be attached. Defaults to
``locator_or_path``.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Raises:
FileNotFound: No file exists at the given path.
|
capybara/node/actions.py
|
def attach_file(self, locator_or_path, path=None, **kwargs):
"""
Find a file field on the page and attach a file given its path. The file field can be found
via its name, id, or label text. ::
page.attach_file(locator, "/path/to/file.png")
Args:
locator_or_path (str): Which field to attach the file to, or the path of the file that
will be attached.
path (str, optional): The path of the file that will be attached. Defaults to
``locator_or_path``.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Raises:
FileNotFound: No file exists at the given path.
"""
if path is None:
locator, path = None, locator_or_path
else:
locator = locator_or_path
if not os.path.isfile(path):
raise FileNotFound("cannot attach file, {0} does not exist".format(path))
self.find("file_field", locator, **kwargs).set(path)
|
def attach_file(self, locator_or_path, path=None, **kwargs):
"""
Find a file field on the page and attach a file given its path. The file field can be found
via its name, id, or label text. ::
page.attach_file(locator, "/path/to/file.png")
Args:
locator_or_path (str): Which field to attach the file to, or the path of the file that
will be attached.
path (str, optional): The path of the file that will be attached. Defaults to
``locator_or_path``.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Raises:
FileNotFound: No file exists at the given path.
"""
if path is None:
locator, path = None, locator_or_path
else:
locator = locator_or_path
if not os.path.isfile(path):
raise FileNotFound("cannot attach file, {0} does not exist".format(path))
self.find("file_field", locator, **kwargs).set(path)
|
[
"Find",
"a",
"file",
"field",
"on",
"the",
"page",
"and",
"attach",
"a",
"file",
"given",
"its",
"path",
".",
"The",
"file",
"field",
"can",
"be",
"found",
"via",
"its",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L16-L42
|
[
"def",
"attach_file",
"(",
"self",
",",
"locator_or_path",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"locator",
",",
"path",
"=",
"None",
",",
"locator_or_path",
"else",
":",
"locator",
"=",
"locator_or_path",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"FileNotFound",
"(",
"\"cannot attach file, {0} does not exist\"",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"find",
"(",
"\"file_field\"",
",",
"locator",
",",
"*",
"*",
"kwargs",
")",
".",
"set",
"(",
"path",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.check
|
Find a check box and mark it as checked. The check box can be found via name, id, or label
text. ::
page.check("German")
Args:
locator (str, optional): Which check box to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def check(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a check box and mark it as checked. The check box can be found via name, id, or label
text. ::
page.check("German")
Args:
locator (str, optional): Which check box to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"checkbox", True, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
def check(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a check box and mark it as checked. The check box can be found via name, id, or label
text. ::
page.check("German")
Args:
locator (str, optional): Which check box to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"checkbox", True, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
[
"Find",
"a",
"check",
"box",
"and",
"mark",
"it",
"as",
"checked",
".",
"The",
"check",
"box",
"can",
"be",
"found",
"via",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L44-L59
|
[
"def",
"check",
"(",
"self",
",",
"locator",
"=",
"None",
",",
"allow_label_click",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_with_label",
"(",
"\"checkbox\"",
",",
"True",
",",
"locator",
"=",
"locator",
",",
"allow_label_click",
"=",
"allow_label_click",
",",
"*",
"*",
"kwargs",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.choose
|
Find a radio button and mark it as checked. The radio button can be found via name, id, or
label text. ::
page.choose("Male")
Args:
locator (str, optional): Which radio button to choose.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def choose(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a radio button and mark it as checked. The radio button can be found via name, id, or
label text. ::
page.choose("Male")
Args:
locator (str, optional): Which radio button to choose.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"radio_button", True, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
def choose(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a radio button and mark it as checked. The radio button can be found via name, id, or
label text. ::
page.choose("Male")
Args:
locator (str, optional): Which radio button to choose.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"radio_button", True, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
[
"Find",
"a",
"radio",
"button",
"and",
"mark",
"it",
"as",
"checked",
".",
"The",
"radio",
"button",
"can",
"be",
"found",
"via",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L61-L76
|
[
"def",
"choose",
"(",
"self",
",",
"locator",
"=",
"None",
",",
"allow_label_click",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_with_label",
"(",
"\"radio_button\"",
",",
"True",
",",
"locator",
"=",
"locator",
",",
"allow_label_click",
"=",
"allow_label_click",
",",
"*",
"*",
"kwargs",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.fill_in
|
Locate a text field or text area and fill it in with the given text. The field can be found
via its name, id, or label text. ::
page.fill_in("Name", value="Bob")
Args:
locator (str, optional): Which field to fill in.
current_value (str, optional): The current value of the field.
value (str, optional): The value to fill in. Defaults to None.
fill_options (Dict, optional): Driver-specific options regarding how to fill fields.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def fill_in(self, locator=None, current_value=None, value=None, fill_options=None, **kwargs):
"""
Locate a text field or text area and fill it in with the given text. The field can be found
via its name, id, or label text. ::
page.fill_in("Name", value="Bob")
Args:
locator (str, optional): Which field to fill in.
current_value (str, optional): The current value of the field.
value (str, optional): The value to fill in. Defaults to None.
fill_options (Dict, optional): Driver-specific options regarding how to fill fields.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if current_value is not None:
kwargs["value"] = current_value
fill_options = fill_options or {}
self.find("fillable_field", locator, **kwargs).set(value, **fill_options)
|
def fill_in(self, locator=None, current_value=None, value=None, fill_options=None, **kwargs):
"""
Locate a text field or text area and fill it in with the given text. The field can be found
via its name, id, or label text. ::
page.fill_in("Name", value="Bob")
Args:
locator (str, optional): Which field to fill in.
current_value (str, optional): The current value of the field.
value (str, optional): The value to fill in. Defaults to None.
fill_options (Dict, optional): Driver-specific options regarding how to fill fields.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if current_value is not None:
kwargs["value"] = current_value
fill_options = fill_options or {}
self.find("fillable_field", locator, **kwargs).set(value, **fill_options)
|
[
"Locate",
"a",
"text",
"field",
"or",
"text",
"area",
"and",
"fill",
"it",
"in",
"with",
"the",
"given",
"text",
".",
"The",
"field",
"can",
"be",
"found",
"via",
"its",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L119-L139
|
[
"def",
"fill_in",
"(",
"self",
",",
"locator",
"=",
"None",
",",
"current_value",
"=",
"None",
",",
"value",
"=",
"None",
",",
"fill_options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_value",
"is",
"not",
"None",
":",
"kwargs",
"[",
"\"value\"",
"]",
"=",
"current_value",
"fill_options",
"=",
"fill_options",
"or",
"{",
"}",
"self",
".",
"find",
"(",
"\"fillable_field\"",
",",
"locator",
",",
"*",
"*",
"kwargs",
")",
".",
"set",
"(",
"value",
",",
"*",
"*",
"fill_options",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.select
|
If the ``field`` argument is present, ``select`` finds a select box on the page and selects
a particular option from it. Otherwise it finds an option inside the current scope and
selects it. If the select box is a multiple select, ``select`` can be called multiple times
to select more than one option. The select box can be found via its name, id, or label text.
The option can be found by its text. ::
page.select("March", field="Month")
Args:
value (str, optional): Which option to select.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def select(self, value=None, field=None, **kwargs):
"""
If the ``field`` argument is present, ``select`` finds a select box on the page and selects
a particular option from it. Otherwise it finds an option inside the current scope and
selects it. If the select box is a multiple select, ``select`` can be called multiple times
to select more than one option. The select box can be found via its name, id, or label text.
The option can be found by its text. ::
page.select("March", field="Month")
Args:
value (str, optional): Which option to select.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if field:
self.find("select", field, **kwargs).find("option", value, **kwargs).select_option()
else:
self.find("option", value, **kwargs).select_option()
|
def select(self, value=None, field=None, **kwargs):
"""
If the ``field`` argument is present, ``select`` finds a select box on the page and selects
a particular option from it. Otherwise it finds an option inside the current scope and
selects it. If the select box is a multiple select, ``select`` can be called multiple times
to select more than one option. The select box can be found via its name, id, or label text.
The option can be found by its text. ::
page.select("March", field="Month")
Args:
value (str, optional): Which option to select.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if field:
self.find("select", field, **kwargs).find("option", value, **kwargs).select_option()
else:
self.find("option", value, **kwargs).select_option()
|
[
"If",
"the",
"field",
"argument",
"is",
"present",
"select",
"finds",
"a",
"select",
"box",
"on",
"the",
"page",
"and",
"selects",
"a",
"particular",
"option",
"from",
"it",
".",
"Otherwise",
"it",
"finds",
"an",
"option",
"inside",
"the",
"current",
"scope",
"and",
"selects",
"it",
".",
"If",
"the",
"select",
"box",
"is",
"a",
"multiple",
"select",
"select",
"can",
"be",
"called",
"multiple",
"times",
"to",
"select",
"more",
"than",
"one",
"option",
".",
"The",
"select",
"box",
"can",
"be",
"found",
"via",
"its",
"name",
"id",
"or",
"label",
"text",
".",
"The",
"option",
"can",
"be",
"found",
"by",
"its",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L141-L160
|
[
"def",
"select",
"(",
"self",
",",
"value",
"=",
"None",
",",
"field",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
":",
"self",
".",
"find",
"(",
"\"select\"",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
".",
"find",
"(",
"\"option\"",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
".",
"select_option",
"(",
")",
"else",
":",
"self",
".",
"find",
"(",
"\"option\"",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
".",
"select_option",
"(",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.uncheck
|
Find a check box and uncheck it. The check box can be found via name, id, or label text. ::
page.uncheck("German")
Args:
locator (str, optional): Which check box to uncheck.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def uncheck(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a check box and uncheck it. The check box can be found via name, id, or label text. ::
page.uncheck("German")
Args:
locator (str, optional): Which check box to uncheck.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"checkbox", False, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
def uncheck(self, locator=None, allow_label_click=None, **kwargs):
"""
Find a check box and uncheck it. The check box can be found via name, id, or label text. ::
page.uncheck("German")
Args:
locator (str, optional): Which check box to uncheck.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
self._check_with_label(
"checkbox", False, locator=locator, allow_label_click=allow_label_click, **kwargs)
|
[
"Find",
"a",
"check",
"box",
"and",
"uncheck",
"it",
".",
"The",
"check",
"box",
"can",
"be",
"found",
"via",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L162-L176
|
[
"def",
"uncheck",
"(",
"self",
",",
"locator",
"=",
"None",
",",
"allow_label_click",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_with_label",
"(",
"\"checkbox\"",
",",
"False",
",",
"locator",
"=",
"locator",
",",
"allow_label_click",
"=",
"allow_label_click",
",",
"*",
"*",
"kwargs",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin.unselect
|
Find a select box on the page and unselect a particular option from it. If the select box is
a multiple select, ``unselect`` can be called multiple times to unselect more than one
option. The select box can be found via its name, id, or label text. ::
page.unselect("March", field="Month")
Args:
value (str, optional): Which option to unselect.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def unselect(self, value=None, field=None, **kwargs):
"""
Find a select box on the page and unselect a particular option from it. If the select box is
a multiple select, ``unselect`` can be called multiple times to unselect more than one
option. The select box can be found via its name, id, or label text. ::
page.unselect("March", field="Month")
Args:
value (str, optional): Which option to unselect.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if field:
self.find("select", field, **kwargs).find("option", value, **kwargs).unselect_option()
else:
self.find("option", value, **kwargs).unselect_option()
|
def unselect(self, value=None, field=None, **kwargs):
"""
Find a select box on the page and unselect a particular option from it. If the select box is
a multiple select, ``unselect`` can be called multiple times to unselect more than one
option. The select box can be found via its name, id, or label text. ::
page.unselect("March", field="Month")
Args:
value (str, optional): Which option to unselect.
field (str, optional): The id, name, or label of the select box.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if field:
self.find("select", field, **kwargs).find("option", value, **kwargs).unselect_option()
else:
self.find("option", value, **kwargs).unselect_option()
|
[
"Find",
"a",
"select",
"box",
"on",
"the",
"page",
"and",
"unselect",
"a",
"particular",
"option",
"from",
"it",
".",
"If",
"the",
"select",
"box",
"is",
"a",
"multiple",
"select",
"unselect",
"can",
"be",
"called",
"multiple",
"times",
"to",
"unselect",
"more",
"than",
"one",
"option",
".",
"The",
"select",
"box",
"can",
"be",
"found",
"via",
"its",
"name",
"id",
"or",
"label",
"text",
".",
"::"
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L178-L195
|
[
"def",
"unselect",
"(",
"self",
",",
"value",
"=",
"None",
",",
"field",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"field",
":",
"self",
".",
"find",
"(",
"\"select\"",
",",
"field",
",",
"*",
"*",
"kwargs",
")",
".",
"find",
"(",
"\"option\"",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
".",
"unselect_option",
"(",
")",
"else",
":",
"self",
".",
"find",
"(",
"\"option\"",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
".",
"unselect_option",
"(",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
ActionsMixin._check_with_label
|
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
visible (bool | str, optional): The desired element visibility. Defaults to
:data:`capybara.ignore_hidden_elements`.
wait (int | float, optional): The number of seconds to wait to check the element.
Defaults to :data:`capybara.default_max_wait_time`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
|
capybara/node/actions.py
|
def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,
**kwargs):
"""
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
visible (bool | str, optional): The desired element visibility. Defaults to
:data:`capybara.ignore_hidden_elements`.
wait (int | float, optional): The number of seconds to wait to check the element.
Defaults to :data:`capybara.default_max_wait_time`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if allow_label_click is None:
allow_label_click = capybara.automatic_label_click
@self.synchronize(wait=BaseQuery.normalize_wait(wait))
def check_with_label():
element = None
try:
element = self.find(selector, locator, visible=visible, **kwargs)
element.set(checked)
except Exception as e:
if not allow_label_click or not self._should_catch_error(e):
raise
try:
if not element:
element = self.find(selector, locator, visible="all", **kwargs)
label = self.find("label", field=element, visible=True)
if element.checked != checked:
label.click()
except Exception:
raise e
check_with_label()
|
def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None,
**kwargs):
"""
Args:
selector (str): The selector for the type of element that should be checked/unchecked.
checked (bool): Whether the element should be checked.
locator (str, optional): Which element to check.
allow_label_click (bool, optional): Attempt to click the label to toggle state if
element is non-visible. Defaults to :data:`capybara.automatic_label_click`.
visible (bool | str, optional): The desired element visibility. Defaults to
:data:`capybara.ignore_hidden_elements`.
wait (int | float, optional): The number of seconds to wait to check the element.
Defaults to :data:`capybara.default_max_wait_time`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
"""
if allow_label_click is None:
allow_label_click = capybara.automatic_label_click
@self.synchronize(wait=BaseQuery.normalize_wait(wait))
def check_with_label():
element = None
try:
element = self.find(selector, locator, visible=visible, **kwargs)
element.set(checked)
except Exception as e:
if not allow_label_click or not self._should_catch_error(e):
raise
try:
if not element:
element = self.find(selector, locator, visible="all", **kwargs)
label = self.find("label", field=element, visible=True)
if element.checked != checked:
label.click()
except Exception:
raise e
check_with_label()
|
[
"Args",
":",
"selector",
"(",
"str",
")",
":",
"The",
"selector",
"for",
"the",
"type",
"of",
"element",
"that",
"should",
"be",
"checked",
"/",
"unchecked",
".",
"checked",
"(",
"bool",
")",
":",
"Whether",
"the",
"element",
"should",
"be",
"checked",
".",
"locator",
"(",
"str",
"optional",
")",
":",
"Which",
"element",
"to",
"check",
".",
"allow_label_click",
"(",
"bool",
"optional",
")",
":",
"Attempt",
"to",
"click",
"the",
"label",
"to",
"toggle",
"state",
"if",
"element",
"is",
"non",
"-",
"visible",
".",
"Defaults",
"to",
":",
"data",
":",
"capybara",
".",
"automatic_label_click",
".",
"visible",
"(",
"bool",
"|",
"str",
"optional",
")",
":",
"The",
"desired",
"element",
"visibility",
".",
"Defaults",
"to",
":",
"data",
":",
"capybara",
".",
"ignore_hidden_elements",
".",
"wait",
"(",
"int",
"|",
"float",
"optional",
")",
":",
"The",
"number",
"of",
"seconds",
"to",
"wait",
"to",
"check",
"the",
"element",
".",
"Defaults",
"to",
":",
"data",
":",
"capybara",
".",
"default_max_wait_time",
".",
"**",
"kwargs",
":",
"Arbitrary",
"keyword",
"arguments",
"for",
":",
"class",
":",
"SelectorQuery",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/actions.py#L197-L234
|
[
"def",
"_check_with_label",
"(",
"self",
",",
"selector",
",",
"checked",
",",
"locator",
"=",
"None",
",",
"allow_label_click",
"=",
"None",
",",
"visible",
"=",
"None",
",",
"wait",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"allow_label_click",
"is",
"None",
":",
"allow_label_click",
"=",
"capybara",
".",
"automatic_label_click",
"@",
"self",
".",
"synchronize",
"(",
"wait",
"=",
"BaseQuery",
".",
"normalize_wait",
"(",
"wait",
")",
")",
"def",
"check_with_label",
"(",
")",
":",
"element",
"=",
"None",
"try",
":",
"element",
"=",
"self",
".",
"find",
"(",
"selector",
",",
"locator",
",",
"visible",
"=",
"visible",
",",
"*",
"*",
"kwargs",
")",
"element",
".",
"set",
"(",
"checked",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"not",
"allow_label_click",
"or",
"not",
"self",
".",
"_should_catch_error",
"(",
"e",
")",
":",
"raise",
"try",
":",
"if",
"not",
"element",
":",
"element",
"=",
"self",
".",
"find",
"(",
"selector",
",",
"locator",
",",
"visible",
"=",
"\"all\"",
",",
"*",
"*",
"kwargs",
")",
"label",
"=",
"self",
".",
"find",
"(",
"\"label\"",
",",
"field",
"=",
"element",
",",
"visible",
"=",
"True",
")",
"if",
"element",
".",
"checked",
"!=",
"checked",
":",
"label",
".",
"click",
"(",
")",
"except",
"Exception",
":",
"raise",
"e",
"check_with_label",
"(",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
synchronize
|
Decorator for :meth:`synchronize`.
|
capybara/node/base.py
|
def synchronize(func):
""" Decorator for :meth:`synchronize`. """
@wraps(func)
def outer(self, *args, **kwargs):
@self.synchronize
def inner(self, *args, **kwargs):
return func(self, *args, **kwargs)
return inner(self, *args, **kwargs)
return outer
|
def synchronize(func):
""" Decorator for :meth:`synchronize`. """
@wraps(func)
def outer(self, *args, **kwargs):
@self.synchronize
def inner(self, *args, **kwargs):
return func(self, *args, **kwargs)
return inner(self, *args, **kwargs)
return outer
|
[
"Decorator",
"for",
":",
"meth",
":",
"synchronize",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/base.py#L204-L215
|
[
"def",
"synchronize",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"outer",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"self",
".",
"synchronize",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"outer"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Base.synchronize
|
This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated function, instead of bubbling up, are caught, and the function is
re-run.
Certain drivers have no support for asynchronous processes. These drivers run the function,
and any error raised bubbles up immediately. This allows faster turn around in the case
where an expectation fails.
Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
occurs when a node is manipulated which no longer exists on the page. For example, the
Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.
As long as any of these exceptions are thrown, the function is re-run, until a certain
amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
and can be overridden through the ``wait`` argument. This time is compared with the system
time to see how much time has passed. If the return value of ``time.time()`` is stubbed
out, Capybara will raise :exc:`FrozenInTime`.
Args:
func (Callable, optional): The function to decorate.
wait (int, optional): Number of seconds to retry this function.
errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.
Returns:
Callable: The decorated function, or a decorator function.
Raises:
FrozenInTime: If the return value of ``time.time()`` appears stuck.
|
capybara/node/base.py
|
def synchronize(self, func=None, wait=None, errors=()):
"""
This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated function, instead of bubbling up, are caught, and the function is
re-run.
Certain drivers have no support for asynchronous processes. These drivers run the function,
and any error raised bubbles up immediately. This allows faster turn around in the case
where an expectation fails.
Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
occurs when a node is manipulated which no longer exists on the page. For example, the
Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.
As long as any of these exceptions are thrown, the function is re-run, until a certain
amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
and can be overridden through the ``wait`` argument. This time is compared with the system
time to see how much time has passed. If the return value of ``time.time()`` is stubbed
out, Capybara will raise :exc:`FrozenInTime`.
Args:
func (Callable, optional): The function to decorate.
wait (int, optional): Number of seconds to retry this function.
errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.
Returns:
Callable: The decorated function, or a decorator function.
Raises:
FrozenInTime: If the return value of ``time.time()`` appears stuck.
"""
def decorator(func):
@wraps(func)
def outer(*args, **kwargs):
seconds = wait if wait is not None else capybara.default_max_wait_time
def inner():
return func(*args, **kwargs)
if self.session.synchronized:
return inner()
else:
timer = Timer(seconds)
self.session.synchronized = True
try:
while True:
try:
return inner()
except Exception as e:
self.session.raise_server_error()
if not self._should_catch_error(e, errors):
raise
if timer.expired:
raise
sleep(0.05)
if timer.stalled:
raise FrozenInTime(
"time appears to be frozen, Capybara does not work with "
"libraries which freeze time, consider using time "
"traveling instead")
if capybara.automatic_reload:
self.reload()
finally:
self.session.synchronized = False
return outer
if func:
return decorator(func)
else:
return decorator
|
def synchronize(self, func=None, wait=None, errors=()):
"""
This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated function, instead of bubbling up, are caught, and the function is
re-run.
Certain drivers have no support for asynchronous processes. These drivers run the function,
and any error raised bubbles up immediately. This allows faster turn around in the case
where an expectation fails.
Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
occurs when a node is manipulated which no longer exists on the page. For example, the
Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.
As long as any of these exceptions are thrown, the function is re-run, until a certain
amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
and can be overridden through the ``wait`` argument. This time is compared with the system
time to see how much time has passed. If the return value of ``time.time()`` is stubbed
out, Capybara will raise :exc:`FrozenInTime`.
Args:
func (Callable, optional): The function to decorate.
wait (int, optional): Number of seconds to retry this function.
errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.
Returns:
Callable: The decorated function, or a decorator function.
Raises:
FrozenInTime: If the return value of ``time.time()`` appears stuck.
"""
def decorator(func):
@wraps(func)
def outer(*args, **kwargs):
seconds = wait if wait is not None else capybara.default_max_wait_time
def inner():
return func(*args, **kwargs)
if self.session.synchronized:
return inner()
else:
timer = Timer(seconds)
self.session.synchronized = True
try:
while True:
try:
return inner()
except Exception as e:
self.session.raise_server_error()
if not self._should_catch_error(e, errors):
raise
if timer.expired:
raise
sleep(0.05)
if timer.stalled:
raise FrozenInTime(
"time appears to be frozen, Capybara does not work with "
"libraries which freeze time, consider using time "
"traveling instead")
if capybara.automatic_reload:
self.reload()
finally:
self.session.synchronized = False
return outer
if func:
return decorator(func)
else:
return decorator
|
[
"This",
"method",
"is",
"Capybara",
"s",
"primary",
"defense",
"against",
"asynchronicity",
"problems",
".",
"It",
"works",
"by",
"attempting",
"to",
"run",
"a",
"given",
"decorated",
"function",
"until",
"it",
"succeeds",
".",
"The",
"exact",
"behavior",
"of",
"this",
"method",
"depends",
"on",
"a",
"number",
"of",
"factors",
".",
"Basically",
"there",
"are",
"certain",
"exceptions",
"which",
"when",
"raised",
"from",
"the",
"decorated",
"function",
"instead",
"of",
"bubbling",
"up",
"are",
"caught",
"and",
"the",
"function",
"is",
"re",
"-",
"run",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/base.py#L97-L175
|
[
"def",
"synchronize",
"(",
"self",
",",
"func",
"=",
"None",
",",
"wait",
"=",
"None",
",",
"errors",
"=",
"(",
")",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"outer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"seconds",
"=",
"wait",
"if",
"wait",
"is",
"not",
"None",
"else",
"capybara",
".",
"default_max_wait_time",
"def",
"inner",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"session",
".",
"synchronized",
":",
"return",
"inner",
"(",
")",
"else",
":",
"timer",
"=",
"Timer",
"(",
"seconds",
")",
"self",
".",
"session",
".",
"synchronized",
"=",
"True",
"try",
":",
"while",
"True",
":",
"try",
":",
"return",
"inner",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"raise_server_error",
"(",
")",
"if",
"not",
"self",
".",
"_should_catch_error",
"(",
"e",
",",
"errors",
")",
":",
"raise",
"if",
"timer",
".",
"expired",
":",
"raise",
"sleep",
"(",
"0.05",
")",
"if",
"timer",
".",
"stalled",
":",
"raise",
"FrozenInTime",
"(",
"\"time appears to be frozen, Capybara does not work with \"",
"\"libraries which freeze time, consider using time \"",
"\"traveling instead\"",
")",
"if",
"capybara",
".",
"automatic_reload",
":",
"self",
".",
"reload",
"(",
")",
"finally",
":",
"self",
".",
"session",
".",
"synchronized",
"=",
"False",
"return",
"outer",
"if",
"func",
":",
"return",
"decorator",
"(",
"func",
")",
"else",
":",
"return",
"decorator"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Base._should_catch_error
|
Returns whether to catch the given error.
Args:
error (Exception): The error to consider.
errors (Tuple[Type[Exception], ...], optional): The exception types that should be
caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
element errors.
Returns:
bool: Whether to catch the given error.
|
capybara/node/base.py
|
def _should_catch_error(self, error, errors=()):
"""
Returns whether to catch the given error.
Args:
error (Exception): The error to consider.
errors (Tuple[Type[Exception], ...], optional): The exception types that should be
caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
element errors.
Returns:
bool: Whether to catch the given error.
"""
caught_errors = (
errors or
self.session.driver.invalid_element_errors + (ElementNotFound,))
return isinstance(error, caught_errors)
|
def _should_catch_error(self, error, errors=()):
"""
Returns whether to catch the given error.
Args:
error (Exception): The error to consider.
errors (Tuple[Type[Exception], ...], optional): The exception types that should be
caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
element errors.
Returns:
bool: Whether to catch the given error.
"""
caught_errors = (
errors or
self.session.driver.invalid_element_errors + (ElementNotFound,))
return isinstance(error, caught_errors)
|
[
"Returns",
"whether",
"to",
"catch",
"the",
"given",
"error",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/base.py#L177-L195
|
[
"def",
"_should_catch_error",
"(",
"self",
",",
"error",
",",
"errors",
"=",
"(",
")",
")",
":",
"caught_errors",
"=",
"(",
"errors",
"or",
"self",
".",
"session",
".",
"driver",
".",
"invalid_element_errors",
"+",
"(",
"ElementNotFound",
",",
")",
")",
"return",
"isinstance",
"(",
"error",
",",
"caught_errors",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Result.compare_count
|
Returns how the result count compares to the query options.
The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.
Returns:
int: -1, 0, or 1.
|
capybara/result.py
|
def compare_count(self):
"""
Returns how the result count compares to the query options.
The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.
Returns:
int: -1, 0, or 1.
"""
if self.query.options["count"] is not None:
count_opt = int(self.query.options["count"])
self._cache_at_least(count_opt + 1)
return cmp(len(self._result_cache), count_opt)
if self.query.options["minimum"] is not None:
min_opt = int(self.query.options["minimum"])
if not self._cache_at_least(min_opt):
return -1
if self.query.options["maximum"] is not None:
max_opt = int(self.query.options["maximum"])
if self._cache_at_least(max_opt + 1):
return 1
if self.query.options["between"] is not None:
between = self.query.options["between"]
min_opt, max_opt = between[0], between[-1]
if not self._cache_at_least(min_opt):
return -1
if self._cache_at_least(max_opt + 1):
return 1
return 0
return 0
|
def compare_count(self):
"""
Returns how the result count compares to the query options.
The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.
Returns:
int: -1, 0, or 1.
"""
if self.query.options["count"] is not None:
count_opt = int(self.query.options["count"])
self._cache_at_least(count_opt + 1)
return cmp(len(self._result_cache), count_opt)
if self.query.options["minimum"] is not None:
min_opt = int(self.query.options["minimum"])
if not self._cache_at_least(min_opt):
return -1
if self.query.options["maximum"] is not None:
max_opt = int(self.query.options["maximum"])
if self._cache_at_least(max_opt + 1):
return 1
if self.query.options["between"] is not None:
between = self.query.options["between"]
min_opt, max_opt = between[0], between[-1]
if not self._cache_at_least(min_opt):
return -1
if self._cache_at_least(max_opt + 1):
return 1
return 0
return 0
|
[
"Returns",
"how",
"the",
"result",
"count",
"compares",
"to",
"the",
"query",
"options",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/result.py#L54-L89
|
[
"def",
"compare_count",
"(",
"self",
")",
":",
"if",
"self",
".",
"query",
".",
"options",
"[",
"\"count\"",
"]",
"is",
"not",
"None",
":",
"count_opt",
"=",
"int",
"(",
"self",
".",
"query",
".",
"options",
"[",
"\"count\"",
"]",
")",
"self",
".",
"_cache_at_least",
"(",
"count_opt",
"+",
"1",
")",
"return",
"cmp",
"(",
"len",
"(",
"self",
".",
"_result_cache",
")",
",",
"count_opt",
")",
"if",
"self",
".",
"query",
".",
"options",
"[",
"\"minimum\"",
"]",
"is",
"not",
"None",
":",
"min_opt",
"=",
"int",
"(",
"self",
".",
"query",
".",
"options",
"[",
"\"minimum\"",
"]",
")",
"if",
"not",
"self",
".",
"_cache_at_least",
"(",
"min_opt",
")",
":",
"return",
"-",
"1",
"if",
"self",
".",
"query",
".",
"options",
"[",
"\"maximum\"",
"]",
"is",
"not",
"None",
":",
"max_opt",
"=",
"int",
"(",
"self",
".",
"query",
".",
"options",
"[",
"\"maximum\"",
"]",
")",
"if",
"self",
".",
"_cache_at_least",
"(",
"max_opt",
"+",
"1",
")",
":",
"return",
"1",
"if",
"self",
".",
"query",
".",
"options",
"[",
"\"between\"",
"]",
"is",
"not",
"None",
":",
"between",
"=",
"self",
".",
"query",
".",
"options",
"[",
"\"between\"",
"]",
"min_opt",
",",
"max_opt",
"=",
"between",
"[",
"0",
"]",
",",
"between",
"[",
"-",
"1",
"]",
"if",
"not",
"self",
".",
"_cache_at_least",
"(",
"min_opt",
")",
":",
"return",
"-",
"1",
"if",
"self",
".",
"_cache_at_least",
"(",
"max_opt",
"+",
"1",
")",
":",
"return",
"1",
"return",
"0",
"return",
"0"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Result.failure_message
|
str: A message describing the query failure.
|
capybara/result.py
|
def failure_message(self):
""" str: A message describing the query failure. """
message = failure_message(self.query.description, self.query.options)
if len(self) > 0:
message += ", found {count} {matches}: {results}".format(
count=len(self),
matches=declension("match", "matches", len(self)),
results=", ".join([desc(node.text) for node in self]))
else:
message += " but there were no matches"
if self._rest:
elements = ", ".join([desc(element.text) for element in self._rest])
message += (". Also found {}, which matched the selector"
" but not all filters.".format(elements))
return message
|
def failure_message(self):
""" str: A message describing the query failure. """
message = failure_message(self.query.description, self.query.options)
if len(self) > 0:
message += ", found {count} {matches}: {results}".format(
count=len(self),
matches=declension("match", "matches", len(self)),
results=", ".join([desc(node.text) for node in self]))
else:
message += " but there were no matches"
if self._rest:
elements = ", ".join([desc(element.text) for element in self._rest])
message += (". Also found {}, which matched the selector"
" but not all filters.".format(elements))
return message
|
[
"str",
":",
"A",
"message",
"describing",
"the",
"query",
"failure",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/result.py#L97-L115
|
[
"def",
"failure_message",
"(",
"self",
")",
":",
"message",
"=",
"failure_message",
"(",
"self",
".",
"query",
".",
"description",
",",
"self",
".",
"query",
".",
"options",
")",
"if",
"len",
"(",
"self",
")",
">",
"0",
":",
"message",
"+=",
"\", found {count} {matches}: {results}\"",
".",
"format",
"(",
"count",
"=",
"len",
"(",
"self",
")",
",",
"matches",
"=",
"declension",
"(",
"\"match\"",
",",
"\"matches\"",
",",
"len",
"(",
"self",
")",
")",
",",
"results",
"=",
"\", \"",
".",
"join",
"(",
"[",
"desc",
"(",
"node",
".",
"text",
")",
"for",
"node",
"in",
"self",
"]",
")",
")",
"else",
":",
"message",
"+=",
"\" but there were no matches\"",
"if",
"self",
".",
"_rest",
":",
"elements",
"=",
"\", \"",
".",
"join",
"(",
"[",
"desc",
"(",
"element",
".",
"text",
")",
"for",
"element",
"in",
"self",
".",
"_rest",
"]",
")",
"message",
"+=",
"(",
"\". Also found {}, which matched the selector\"",
"\" but not all filters.\"",
".",
"format",
"(",
"elements",
")",
")",
"return",
"message"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Result._cache_at_least
|
Attempts to fill the result cache with at least the given number of results.
Returns:
bool: Whether the cache contains at least the given size.
|
capybara/result.py
|
def _cache_at_least(self, size):
"""
Attempts to fill the result cache with at least the given number of results.
Returns:
bool: Whether the cache contains at least the given size.
"""
try:
while len(self._result_cache) < size:
self._result_cache.append(next(self._result_iter))
return True
except StopIteration:
return False
|
def _cache_at_least(self, size):
"""
Attempts to fill the result cache with at least the given number of results.
Returns:
bool: Whether the cache contains at least the given size.
"""
try:
while len(self._result_cache) < size:
self._result_cache.append(next(self._result_iter))
return True
except StopIteration:
return False
|
[
"Attempts",
"to",
"fill",
"the",
"result",
"cache",
"with",
"at",
"least",
"the",
"given",
"number",
"of",
"results",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/result.py#L121-L134
|
[
"def",
"_cache_at_least",
"(",
"self",
",",
"size",
")",
":",
"try",
":",
"while",
"len",
"(",
"self",
".",
"_result_cache",
")",
"<",
"size",
":",
"self",
".",
"_result_cache",
".",
"append",
"(",
"next",
"(",
"self",
".",
"_result_iter",
")",
")",
"return",
"True",
"except",
"StopIteration",
":",
"return",
"False"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
desc
|
str: A normalized representation for a user-provided value.
|
capybara/helpers.py
|
def desc(value):
""" str: A normalized representation for a user-provided value. """
def normalize_strings(value):
if isinstance(value, list):
value = [normalize_strings(e) for e in value]
if isinstance(value, dict):
value = {normalize_strings(k): normalize_strings(v) for k, v in iter(value.items())}
if isregex(value):
value = value.pattern
if isbytes(value):
value = decode_bytes(value)
if PY2:
if isstring(value):
# In Python 2, strings (``unicode`` objects) represent as ``u'...'``, so ensure
# the string is encoded (as a ``str`` object) for cleaner representation.
value = encode_string(value)
return value
value = normalize_strings(value)
return repr(value)
|
def desc(value):
""" str: A normalized representation for a user-provided value. """
def normalize_strings(value):
if isinstance(value, list):
value = [normalize_strings(e) for e in value]
if isinstance(value, dict):
value = {normalize_strings(k): normalize_strings(v) for k, v in iter(value.items())}
if isregex(value):
value = value.pattern
if isbytes(value):
value = decode_bytes(value)
if PY2:
if isstring(value):
# In Python 2, strings (``unicode`` objects) represent as ``u'...'``, so ensure
# the string is encoded (as a ``str`` object) for cleaner representation.
value = encode_string(value)
return value
value = normalize_strings(value)
return repr(value)
|
[
"str",
":",
"A",
"normalized",
"representation",
"for",
"a",
"user",
"-",
"provided",
"value",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L24-L50
|
[
"def",
"desc",
"(",
"value",
")",
":",
"def",
"normalize_strings",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"normalize_strings",
"(",
"e",
")",
"for",
"e",
"in",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"{",
"normalize_strings",
"(",
"k",
")",
":",
"normalize_strings",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iter",
"(",
"value",
".",
"items",
"(",
")",
")",
"}",
"if",
"isregex",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"pattern",
"if",
"isbytes",
"(",
"value",
")",
":",
"value",
"=",
"decode_bytes",
"(",
"value",
")",
"if",
"PY2",
":",
"if",
"isstring",
"(",
"value",
")",
":",
"# In Python 2, strings (``unicode`` objects) represent as ``u'...'``, so ensure",
"# the string is encoded (as a ``str`` object) for cleaner representation.",
"value",
"=",
"encode_string",
"(",
"value",
")",
"return",
"value",
"value",
"=",
"normalize_strings",
"(",
"value",
")",
"return",
"repr",
"(",
"value",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
expects_none
|
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
|
capybara/helpers.py
|
def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
if any(options.get(key) is not None for key in ["count", "maximum", "minimum", "between"]):
return matches_count(0, options)
else:
return False
|
def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
if any(options.get(key) is not None for key in ["count", "maximum", "minimum", "between"]):
return matches_count(0, options)
else:
return False
|
[
"Returns",
"whether",
"the",
"given",
"query",
"options",
"expect",
"a",
"possible",
"count",
"of",
"zero",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L53-L67
|
[
"def",
"expects_none",
"(",
"options",
")",
":",
"if",
"any",
"(",
"options",
".",
"get",
"(",
"key",
")",
"is",
"not",
"None",
"for",
"key",
"in",
"[",
"\"count\"",
",",
"\"maximum\"",
",",
"\"minimum\"",
",",
"\"between\"",
"]",
")",
":",
"return",
"matches_count",
"(",
"0",
",",
"options",
")",
"else",
":",
"return",
"False"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
failure_message
|
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
|
capybara/helpers.py
|
def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""
message = "expected to find {}".format(description)
if options["count"] is not None:
message += " {count} {times}".format(
count=options["count"],
times=declension("time", "times", options["count"]))
elif options["between"] is not None:
between = options["between"]
if between:
first, last = between[0], between[-1]
else:
first, last = None, None
message += " between {first} and {last} times".format(
first=first,
last=last)
elif options["maximum"] is not None:
message += " at most {maximum} {times}".format(
maximum=options["maximum"],
times=declension("time", "times", options["maximum"]))
elif options["minimum"] is not None:
message += " at least {minimum} {times}".format(
minimum=options["minimum"],
times=declension("time", "times", options["minimum"]))
return message
|
def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""
message = "expected to find {}".format(description)
if options["count"] is not None:
message += " {count} {times}".format(
count=options["count"],
times=declension("time", "times", options["count"]))
elif options["between"] is not None:
between = options["between"]
if between:
first, last = between[0], between[-1]
else:
first, last = None, None
message += " between {first} and {last} times".format(
first=first,
last=last)
elif options["maximum"] is not None:
message += " at most {maximum} {times}".format(
maximum=options["maximum"],
times=declension("time", "times", options["maximum"]))
elif options["minimum"] is not None:
message += " at least {minimum} {times}".format(
minimum=options["minimum"],
times=declension("time", "times", options["minimum"]))
return message
|
[
"Returns",
"a",
"expectation",
"failure",
"message",
"for",
"the",
"given",
"query",
"description",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L70-L107
|
[
"def",
"failure_message",
"(",
"description",
",",
"options",
")",
":",
"message",
"=",
"\"expected to find {}\"",
".",
"format",
"(",
"description",
")",
"if",
"options",
"[",
"\"count\"",
"]",
"is",
"not",
"None",
":",
"message",
"+=",
"\" {count} {times}\"",
".",
"format",
"(",
"count",
"=",
"options",
"[",
"\"count\"",
"]",
",",
"times",
"=",
"declension",
"(",
"\"time\"",
",",
"\"times\"",
",",
"options",
"[",
"\"count\"",
"]",
")",
")",
"elif",
"options",
"[",
"\"between\"",
"]",
"is",
"not",
"None",
":",
"between",
"=",
"options",
"[",
"\"between\"",
"]",
"if",
"between",
":",
"first",
",",
"last",
"=",
"between",
"[",
"0",
"]",
",",
"between",
"[",
"-",
"1",
"]",
"else",
":",
"first",
",",
"last",
"=",
"None",
",",
"None",
"message",
"+=",
"\" between {first} and {last} times\"",
".",
"format",
"(",
"first",
"=",
"first",
",",
"last",
"=",
"last",
")",
"elif",
"options",
"[",
"\"maximum\"",
"]",
"is",
"not",
"None",
":",
"message",
"+=",
"\" at most {maximum} {times}\"",
".",
"format",
"(",
"maximum",
"=",
"options",
"[",
"\"maximum\"",
"]",
",",
"times",
"=",
"declension",
"(",
"\"time\"",
",",
"\"times\"",
",",
"options",
"[",
"\"maximum\"",
"]",
")",
")",
"elif",
"options",
"[",
"\"minimum\"",
"]",
"is",
"not",
"None",
":",
"message",
"+=",
"\" at least {minimum} {times}\"",
".",
"format",
"(",
"minimum",
"=",
"options",
"[",
"\"minimum\"",
"]",
",",
"times",
"=",
"declension",
"(",
"\"time\"",
",",
"\"times\"",
",",
"options",
"[",
"\"minimum\"",
"]",
")",
")",
"return",
"message"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
matches_count
|
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether the count matches the options.
|
capybara/helpers.py
|
def matches_count(count, options):
"""
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether the count matches the options.
"""
if options.get("count") is not None:
return count == int(options["count"])
if options.get("maximum") is not None and int(options["maximum"]) < count:
return False
if options.get("minimum") is not None and int(options["minimum"]) > count:
return False
if options.get("between") is not None and count not in options["between"]:
return False
return True
|
def matches_count(count, options):
"""
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether the count matches the options.
"""
if options.get("count") is not None:
return count == int(options["count"])
if options.get("maximum") is not None and int(options["maximum"]) < count:
return False
if options.get("minimum") is not None and int(options["minimum"]) > count:
return False
if options.get("between") is not None and count not in options["between"]:
return False
return True
|
[
"Returns",
"whether",
"the",
"given",
"count",
"matches",
"the",
"given",
"query",
"options",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L110-L132
|
[
"def",
"matches_count",
"(",
"count",
",",
"options",
")",
":",
"if",
"options",
".",
"get",
"(",
"\"count\"",
")",
"is",
"not",
"None",
":",
"return",
"count",
"==",
"int",
"(",
"options",
"[",
"\"count\"",
"]",
")",
"if",
"options",
".",
"get",
"(",
"\"maximum\"",
")",
"is",
"not",
"None",
"and",
"int",
"(",
"options",
"[",
"\"maximum\"",
"]",
")",
"<",
"count",
":",
"return",
"False",
"if",
"options",
".",
"get",
"(",
"\"minimum\"",
")",
"is",
"not",
"None",
"and",
"int",
"(",
"options",
"[",
"\"minimum\"",
"]",
")",
">",
"count",
":",
"return",
"False",
"if",
"options",
".",
"get",
"(",
"\"between\"",
")",
"is",
"not",
"None",
"and",
"count",
"not",
"in",
"options",
"[",
"\"between\"",
"]",
":",
"return",
"False",
"return",
"True"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
normalize_text
|
Normalizes the given value to a string of text with extra whitespace removed.
Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
is simply cast to a string.
Args:
value (Any): The data to normalize.
Returns:
str: The normalized text.
|
capybara/helpers.py
|
def normalize_text(value):
"""
Normalizes the given value to a string of text with extra whitespace removed.
Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
is simply cast to a string.
Args:
value (Any): The data to normalize.
Returns:
str: The normalized text.
"""
if value is None:
return ""
text = decode_bytes(value) if isbytes(value) else str_(value)
return normalize_whitespace(text)
|
def normalize_text(value):
"""
Normalizes the given value to a string of text with extra whitespace removed.
Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
is simply cast to a string.
Args:
value (Any): The data to normalize.
Returns:
str: The normalized text.
"""
if value is None:
return ""
text = decode_bytes(value) if isbytes(value) else str_(value)
return normalize_whitespace(text)
|
[
"Normalizes",
"the",
"given",
"value",
"to",
"a",
"string",
"of",
"text",
"with",
"extra",
"whitespace",
"removed",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L143-L162
|
[
"def",
"normalize_text",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"\"\"",
"text",
"=",
"decode_bytes",
"(",
"value",
")",
"if",
"isbytes",
"(",
"value",
")",
"else",
"str_",
"(",
"value",
")",
"return",
"normalize_whitespace",
"(",
"text",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
normalize_whitespace
|
Returns the given text with outer whitespace removed and inner whitespace collapsed.
Args:
text (str): The text to normalize.
Returns:
str: The normalized text.
|
capybara/helpers.py
|
def normalize_whitespace(text):
"""
Returns the given text with outer whitespace removed and inner whitespace collapsed.
Args:
text (str): The text to normalize.
Returns:
str: The normalized text.
"""
return re.sub(r"\s+", " ", text, flags=re.UNICODE).strip()
|
def normalize_whitespace(text):
"""
Returns the given text with outer whitespace removed and inner whitespace collapsed.
Args:
text (str): The text to normalize.
Returns:
str: The normalized text.
"""
return re.sub(r"\s+", " ", text, flags=re.UNICODE).strip()
|
[
"Returns",
"the",
"given",
"text",
"with",
"outer",
"whitespace",
"removed",
"and",
"inner",
"whitespace",
"collapsed",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L165-L176
|
[
"def",
"normalize_whitespace",
"(",
"text",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
",",
"flags",
"=",
"re",
".",
"UNICODE",
")",
".",
"strip",
"(",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
toregex
|
Returns a compiled regular expression for the given text.
Args:
text (str | RegexObject): The text to match.
exact (bool, optional): Whether the generated regular expression should match exact
strings. Defaults to False.
Returns:
RegexObject: A compiled regular expression that will match the text.
|
capybara/helpers.py
|
def toregex(text, exact=False):
"""
Returns a compiled regular expression for the given text.
Args:
text (str | RegexObject): The text to match.
exact (bool, optional): Whether the generated regular expression should match exact
strings. Defaults to False.
Returns:
RegexObject: A compiled regular expression that will match the text.
"""
if isregex(text):
return text
escaped = re.escape(normalize_text(text))
if exact:
escaped = r"\A{}\Z".format(escaped)
return re.compile(escaped)
|
def toregex(text, exact=False):
"""
Returns a compiled regular expression for the given text.
Args:
text (str | RegexObject): The text to match.
exact (bool, optional): Whether the generated regular expression should match exact
strings. Defaults to False.
Returns:
RegexObject: A compiled regular expression that will match the text.
"""
if isregex(text):
return text
escaped = re.escape(normalize_text(text))
if exact:
escaped = r"\A{}\Z".format(escaped)
return re.compile(escaped)
|
[
"Returns",
"a",
"compiled",
"regular",
"expression",
"for",
"the",
"given",
"text",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/helpers.py#L200-L220
|
[
"def",
"toregex",
"(",
"text",
",",
"exact",
"=",
"False",
")",
":",
"if",
"isregex",
"(",
"text",
")",
":",
"return",
"text",
"escaped",
"=",
"re",
".",
"escape",
"(",
"normalize_text",
"(",
"text",
")",
")",
"if",
"exact",
":",
"escaped",
"=",
"r\"\\A{}\\Z\"",
".",
"format",
"(",
"escaped",
")",
"return",
"re",
".",
"compile",
"(",
"escaped",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
CurrentPathQuery.resolves_for
|
Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves.
|
capybara/queries/current_path_query.py
|
def resolves_for(self, session):
"""
Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves.
"""
if self.url:
self.actual_path = session.current_url
else:
result = urlparse(session.current_url)
if self.only_path:
self.actual_path = result.path
else:
request_uri = result.path
if result.query:
request_uri += "?{0}".format(result.query)
self.actual_path = request_uri
if isregex(self.expected_path):
return self.expected_path.search(self.actual_path)
else:
return normalize_url(self.actual_path) == normalize_url(self.expected_path)
|
def resolves_for(self, session):
"""
Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves.
"""
if self.url:
self.actual_path = session.current_url
else:
result = urlparse(session.current_url)
if self.only_path:
self.actual_path = result.path
else:
request_uri = result.path
if result.query:
request_uri += "?{0}".format(result.query)
self.actual_path = request_uri
if isregex(self.expected_path):
return self.expected_path.search(self.actual_path)
else:
return normalize_url(self.actual_path) == normalize_url(self.expected_path)
|
[
"Returns",
"whether",
"this",
"query",
"resolves",
"for",
"the",
"given",
"session",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/current_path_query.py#L26-L54
|
[
"def",
"resolves_for",
"(",
"self",
",",
"session",
")",
":",
"if",
"self",
".",
"url",
":",
"self",
".",
"actual_path",
"=",
"session",
".",
"current_url",
"else",
":",
"result",
"=",
"urlparse",
"(",
"session",
".",
"current_url",
")",
"if",
"self",
".",
"only_path",
":",
"self",
".",
"actual_path",
"=",
"result",
".",
"path",
"else",
":",
"request_uri",
"=",
"result",
".",
"path",
"if",
"result",
".",
"query",
":",
"request_uri",
"+=",
"\"?{0}\"",
".",
"format",
"(",
"result",
".",
"query",
")",
"self",
".",
"actual_path",
"=",
"request_uri",
"if",
"isregex",
"(",
"self",
".",
"expected_path",
")",
":",
"return",
"self",
".",
"expected_path",
".",
"search",
"(",
"self",
".",
"actual_path",
")",
"else",
":",
"return",
"normalize_url",
"(",
"self",
".",
"actual_path",
")",
"==",
"normalize_url",
"(",
"self",
".",
"expected_path",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Window.current
|
bool: Whether this window is the window in which commands are being executed.
|
capybara/window.py
|
def current(self):
""" bool: Whether this window is the window in which commands are being executed. """
try:
return self.driver.current_window_handle == self.handle
except self.driver.no_such_window_error:
return False
|
def current(self):
""" bool: Whether this window is the window in which commands are being executed. """
try:
return self.driver.current_window_handle == self.handle
except self.driver.no_such_window_error:
return False
|
[
"bool",
":",
"Whether",
"this",
"window",
"is",
"the",
"window",
"in",
"which",
"commands",
"are",
"being",
"executed",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/window.py#L58-L63
|
[
"def",
"current",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"driver",
".",
"current_window_handle",
"==",
"self",
".",
"handle",
"except",
"self",
".",
"driver",
".",
"no_such_window_error",
":",
"return",
"False"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Window.resize_to
|
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width (int): The new window width in pixels.
height (int): The new window height in pixels.
|
capybara/window.py
|
def resize_to(self, width, height):
"""
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width (int): The new window width in pixels.
height (int): The new window height in pixels.
"""
self.driver.resize_window_to(self.handle, width, height)
|
def resize_to(self, width, height):
"""
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width (int): The new window width in pixels.
height (int): The new window height in pixels.
"""
self.driver.resize_window_to(self.handle, width, height)
|
[
"Resizes",
"the",
"window",
"to",
"the",
"given",
"dimensions",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/window.py#L106-L118
|
[
"def",
"resize_to",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"self",
".",
"driver",
".",
"resize_window_to",
"(",
"self",
".",
"handle",
",",
"width",
",",
"height",
")"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Server.boot
|
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
|
capybara/server.py
|
def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_key] = self.port
init_func = capybara.servers[capybara.server_name]
init_args = (self.middleware, self.port, self.host)
self.server_thread = Thread(target=init_func, args=init_args)
# Inform Python that it shouldn't wait for this thread to terminate before
# exiting. (It will still be appropriately terminated when the process exits.)
self.server_thread.daemon = True
self.server_thread.start()
# Make sure the server actually starts and becomes responsive.
timer = Timer(60)
while not self.responsive:
if timer.expired:
raise RuntimeError("WSGI application timed out during boot")
self.server_thread.join(0.1)
return self
|
def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_key] = self.port
init_func = capybara.servers[capybara.server_name]
init_args = (self.middleware, self.port, self.host)
self.server_thread = Thread(target=init_func, args=init_args)
# Inform Python that it shouldn't wait for this thread to terminate before
# exiting. (It will still be appropriately terminated when the process exits.)
self.server_thread.daemon = True
self.server_thread.start()
# Make sure the server actually starts and becomes responsive.
timer = Timer(60)
while not self.responsive:
if timer.expired:
raise RuntimeError("WSGI application timed out during boot")
self.server_thread.join(0.1)
return self
|
[
"Boots",
"a",
"server",
"for",
"the",
"app",
"if",
"it",
"isn",
"t",
"already",
"booted",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/server.py#L68-L98
|
[
"def",
"boot",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"responsive",
":",
"# Remember the port so we can reuse it if we try to serve this same app again.",
"type",
"(",
"self",
")",
".",
"_ports",
"[",
"self",
".",
"port_key",
"]",
"=",
"self",
".",
"port",
"init_func",
"=",
"capybara",
".",
"servers",
"[",
"capybara",
".",
"server_name",
"]",
"init_args",
"=",
"(",
"self",
".",
"middleware",
",",
"self",
".",
"port",
",",
"self",
".",
"host",
")",
"self",
".",
"server_thread",
"=",
"Thread",
"(",
"target",
"=",
"init_func",
",",
"args",
"=",
"init_args",
")",
"# Inform Python that it shouldn't wait for this thread to terminate before",
"# exiting. (It will still be appropriately terminated when the process exits.)",
"self",
".",
"server_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"server_thread",
".",
"start",
"(",
")",
"# Make sure the server actually starts and becomes responsive.",
"timer",
"=",
"Timer",
"(",
"60",
")",
"while",
"not",
"self",
".",
"responsive",
":",
"if",
"timer",
".",
"expired",
":",
"raise",
"RuntimeError",
"(",
"\"WSGI application timed out during boot\"",
")",
"self",
".",
"server_thread",
".",
"join",
"(",
"0.1",
")",
"return",
"self"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
Server.responsive
|
bool: Whether the server for this app is up and responsive.
|
capybara/server.py
|
def responsive(self):
""" bool: Whether the server for this app is up and responsive. """
if self.server_thread and self.server_thread.join(0):
return False
try:
# Try to fetch the endpoint added by the middleware.
identify_url = "http://{0}:{1}/__identify__".format(self.host, self.port)
with closing(urlopen(identify_url)) as response:
body, status_code = response.read(), response.getcode()
if str(status_code)[0] == "2" or str(status_code)[0] == "3":
return decode_bytes(body) == str(id(self.app))
except URLError:
pass
return False
|
def responsive(self):
""" bool: Whether the server for this app is up and responsive. """
if self.server_thread and self.server_thread.join(0):
return False
try:
# Try to fetch the endpoint added by the middleware.
identify_url = "http://{0}:{1}/__identify__".format(self.host, self.port)
with closing(urlopen(identify_url)) as response:
body, status_code = response.read(), response.getcode()
if str(status_code)[0] == "2" or str(status_code)[0] == "3":
return decode_bytes(body) == str(id(self.app))
except URLError:
pass
return False
|
[
"bool",
":",
"Whether",
"the",
"server",
"for",
"this",
"app",
"is",
"up",
"and",
"responsive",
"."
] |
elliterate/capybara.py
|
python
|
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/server.py#L101-L119
|
[
"def",
"responsive",
"(",
"self",
")",
":",
"if",
"self",
".",
"server_thread",
"and",
"self",
".",
"server_thread",
".",
"join",
"(",
"0",
")",
":",
"return",
"False",
"try",
":",
"# Try to fetch the endpoint added by the middleware.",
"identify_url",
"=",
"\"http://{0}:{1}/__identify__\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"with",
"closing",
"(",
"urlopen",
"(",
"identify_url",
")",
")",
"as",
"response",
":",
"body",
",",
"status_code",
"=",
"response",
".",
"read",
"(",
")",
",",
"response",
".",
"getcode",
"(",
")",
"if",
"str",
"(",
"status_code",
")",
"[",
"0",
"]",
"==",
"\"2\"",
"or",
"str",
"(",
"status_code",
")",
"[",
"0",
"]",
"==",
"\"3\"",
":",
"return",
"decode_bytes",
"(",
"body",
")",
"==",
"str",
"(",
"id",
"(",
"self",
".",
"app",
")",
")",
"except",
"URLError",
":",
"pass",
"return",
"False"
] |
0c6ae449cc37e4445ec3cd6af95674533beedc6c
|
test
|
AdvancedProperty.cgetter
|
Descriptor to change the class wide getter on a property.
:param fcget: new class-wide getter.
:type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]]
:return: AdvancedProperty
:rtype: AdvancedProperty
|
advanced_descriptors/advanced_property.py
|
def cgetter(self, fcget: typing.Optional[typing.Callable[[typing.Any], typing.Any]]) -> "AdvancedProperty":
"""Descriptor to change the class wide getter on a property.
:param fcget: new class-wide getter.
:type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]]
:return: AdvancedProperty
:rtype: AdvancedProperty
"""
self.__fcget = fcget
return self
|
def cgetter(self, fcget: typing.Optional[typing.Callable[[typing.Any], typing.Any]]) -> "AdvancedProperty":
"""Descriptor to change the class wide getter on a property.
:param fcget: new class-wide getter.
:type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]]
:return: AdvancedProperty
:rtype: AdvancedProperty
"""
self.__fcget = fcget
return self
|
[
"Descriptor",
"to",
"change",
"the",
"class",
"wide",
"getter",
"on",
"a",
"property",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/advanced_property.py#L164-L173
|
[
"def",
"cgetter",
"(",
"self",
",",
"fcget",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Callable",
"[",
"[",
"typing",
".",
"Any",
"]",
",",
"typing",
".",
"Any",
"]",
"]",
")",
"->",
"\"AdvancedProperty\"",
":",
"self",
".",
"__fcget",
"=",
"fcget",
"return",
"self"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
SeparateClassMethod.instance_method
|
Descriptor to change instance method.
:param imeth: New instance method.
:type imeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
|
advanced_descriptors/separate_class_method.py
|
def instance_method(self, imeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change instance method.
:param imeth: New instance method.
:type imeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__instance_method = imeth
return self
|
def instance_method(self, imeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change instance method.
:param imeth: New instance method.
:type imeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__instance_method = imeth
return self
|
[
"Descriptor",
"to",
"change",
"instance",
"method",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/separate_class_method.py#L151-L160
|
[
"def",
"instance_method",
"(",
"self",
",",
"imeth",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Callable",
"[",
"...",
",",
"typing",
".",
"Any",
"]",
"]",
")",
"->",
"\"SeparateClassMethod\"",
":",
"self",
".",
"__instance_method",
"=",
"imeth",
"return",
"self"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
SeparateClassMethod.class_method
|
Descriptor to change class method.
:param cmeth: New class method.
:type cmeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
|
advanced_descriptors/separate_class_method.py
|
def class_method(self, cmeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change class method.
:param cmeth: New class method.
:type cmeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__class_method = cmeth
return self
|
def class_method(self, cmeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change class method.
:param cmeth: New class method.
:type cmeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__class_method = cmeth
return self
|
[
"Descriptor",
"to",
"change",
"class",
"method",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/separate_class_method.py#L162-L171
|
[
"def",
"class_method",
"(",
"self",
",",
"cmeth",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Callable",
"[",
"...",
",",
"typing",
".",
"Any",
"]",
"]",
")",
"->",
"\"SeparateClassMethod\"",
":",
"self",
".",
"__class_method",
"=",
"cmeth",
"return",
"self"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
LogOnAccess.__traceback
|
Get outer traceback text for logging.
|
advanced_descriptors/log_on_access.py
|
def __traceback(self) -> str:
"""Get outer traceback text for logging."""
if not self.log_traceback:
return ""
exc_info = sys.exc_info()
stack = traceback.extract_stack()
exc_tb = traceback.extract_tb(exc_info[2])
full_tb = stack[:1] + exc_tb # cut decorator and build full traceback
exc_line: typing.List[str] = traceback.format_exception_only(*exc_info[:2])
# Make standard traceback string
tb_text = "\nTraceback (most recent call last):\n" + "".join(traceback.format_list(full_tb)) + "".join(exc_line)
return tb_text
|
def __traceback(self) -> str:
"""Get outer traceback text for logging."""
if not self.log_traceback:
return ""
exc_info = sys.exc_info()
stack = traceback.extract_stack()
exc_tb = traceback.extract_tb(exc_info[2])
full_tb = stack[:1] + exc_tb # cut decorator and build full traceback
exc_line: typing.List[str] = traceback.format_exception_only(*exc_info[:2])
# Make standard traceback string
tb_text = "\nTraceback (most recent call last):\n" + "".join(traceback.format_list(full_tb)) + "".join(exc_line)
return tb_text
|
[
"Get",
"outer",
"traceback",
"text",
"for",
"logging",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/log_on_access.py#L183-L194
|
[
"def",
"__traceback",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"log_traceback",
":",
"return",
"\"\"",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"stack",
"=",
"traceback",
".",
"extract_stack",
"(",
")",
"exc_tb",
"=",
"traceback",
".",
"extract_tb",
"(",
"exc_info",
"[",
"2",
"]",
")",
"full_tb",
"=",
"stack",
"[",
":",
"1",
"]",
"+",
"exc_tb",
"# cut decorator and build full traceback",
"exc_line",
":",
"typing",
".",
"List",
"[",
"str",
"]",
"=",
"traceback",
".",
"format_exception_only",
"(",
"*",
"exc_info",
"[",
":",
"2",
"]",
")",
"# Make standard traceback string",
"tb_text",
"=",
"\"\\nTraceback (most recent call last):\\n\"",
"+",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_list",
"(",
"full_tb",
")",
")",
"+",
"\"\"",
".",
"join",
"(",
"exc_line",
")",
"return",
"tb_text"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
LogOnAccess.__get_obj_source
|
Get object repr block.
|
advanced_descriptors/log_on_access.py
|
def __get_obj_source(self, instance: typing.Any, owner: typing.Optional[type] = None) -> str:
"""Get object repr block."""
if self.log_object_repr:
return f"{instance!r}"
return f"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>"
|
def __get_obj_source(self, instance: typing.Any, owner: typing.Optional[type] = None) -> str:
"""Get object repr block."""
if self.log_object_repr:
return f"{instance!r}"
return f"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>"
|
[
"Get",
"object",
"repr",
"block",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/log_on_access.py#L196-L200
|
[
"def",
"__get_obj_source",
"(",
"self",
",",
"instance",
":",
"typing",
".",
"Any",
",",
"owner",
":",
"typing",
".",
"Optional",
"[",
"type",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"self",
".",
"log_object_repr",
":",
"return",
"f\"{instance!r}\"",
"return",
"f\"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>\""
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
LogOnAccess._get_logger_for_instance
|
Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
|
advanced_descriptors/log_on_access.py
|
def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
"""
if self.logger is not None: # pylint: disable=no-else-return
return self.logger
elif hasattr(instance, "logger") and isinstance(instance.logger, logging.Logger):
return instance.logger
elif hasattr(instance, "log") and isinstance(instance.log, logging.Logger):
return instance.log
return _LOGGER
|
def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
"""
if self.logger is not None: # pylint: disable=no-else-return
return self.logger
elif hasattr(instance, "logger") and isinstance(instance.logger, logging.Logger):
return instance.logger
elif hasattr(instance, "log") and isinstance(instance.log, logging.Logger):
return instance.log
return _LOGGER
|
[
"Get",
"logger",
"for",
"log",
"calls",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/log_on_access.py#L202-L216
|
[
"def",
"_get_logger_for_instance",
"(",
"self",
",",
"instance",
":",
"typing",
".",
"Any",
")",
"->",
"logging",
".",
"Logger",
":",
"if",
"self",
".",
"logger",
"is",
"not",
"None",
":",
"# pylint: disable=no-else-return",
"return",
"self",
".",
"logger",
"elif",
"hasattr",
"(",
"instance",
",",
"\"logger\"",
")",
"and",
"isinstance",
"(",
"instance",
".",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"return",
"instance",
".",
"logger",
"elif",
"hasattr",
"(",
"instance",
",",
"\"log\"",
")",
"and",
"isinstance",
"(",
"instance",
".",
"log",
",",
"logging",
".",
"Logger",
")",
":",
"return",
"instance",
".",
"log",
"return",
"_LOGGER"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
LogOnAccess.logger
|
Logger instance to use as override.
|
advanced_descriptors/log_on_access.py
|
def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None:
"""Logger instance to use as override."""
if logger is None or isinstance(logger, logging.Logger):
self.__logger = logger
else:
self.__logger = logging.getLogger(logger)
|
def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None:
"""Logger instance to use as override."""
if logger is None or isinstance(logger, logging.Logger):
self.__logger = logger
else:
self.__logger = logging.getLogger(logger)
|
[
"Logger",
"instance",
"to",
"use",
"as",
"override",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/log_on_access.py#L300-L305
|
[
"def",
"logger",
"(",
"self",
",",
"logger",
":",
"typing",
".",
"Union",
"[",
"logging",
".",
"Logger",
",",
"str",
",",
"None",
"]",
")",
"->",
"None",
":",
"if",
"logger",
"is",
"None",
"or",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"self",
".",
"__logger",
"=",
"logger",
"else",
":",
"self",
".",
"__logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
get_simple_vars_from_src
|
Get simple (string/number/boolean and None) assigned values from source.
:param src: Source code
:type src: str
:returns: OrderedDict with keys, values = variable names, values
:rtype: typing.Dict[
str,
typing.Union[
str, bytes,
int, float, complex,
list, set, dict, tuple,
None,
]
]
Limitations: Only defined from scratch variables.
Not supported by design:
* Imports
* Executable code, including string formatting and comprehensions.
Examples:
>>> string_sample = "a = '1'"
>>> get_simple_vars_from_src(string_sample)
OrderedDict([('a', '1')])
>>> int_sample = "b = 1"
>>> get_simple_vars_from_src(int_sample)
OrderedDict([('b', 1)])
>>> list_sample = "c = [u'1', b'1', 1, 1.0, 1j, None]"
>>> result = get_simple_vars_from_src(list_sample)
>>> result == collections.OrderedDict(
... [('c', [u'1', b'1', 1, 1.0, 1j, None])]
... )
True
>>> iterable_sample = "d = ([1], {1: 1}, {1})"
>>> get_simple_vars_from_src(iterable_sample)
OrderedDict([('d', ([1], {1: 1}, {1}))])
>>> multiple_assign = "e = f = g = 1"
>>> get_simple_vars_from_src(multiple_assign)
OrderedDict([('e', 1), ('f', 1), ('g', 1)])
|
setup.py
|
def get_simple_vars_from_src(src):
"""Get simple (string/number/boolean and None) assigned values from source.
:param src: Source code
:type src: str
:returns: OrderedDict with keys, values = variable names, values
:rtype: typing.Dict[
str,
typing.Union[
str, bytes,
int, float, complex,
list, set, dict, tuple,
None,
]
]
Limitations: Only defined from scratch variables.
Not supported by design:
* Imports
* Executable code, including string formatting and comprehensions.
Examples:
>>> string_sample = "a = '1'"
>>> get_simple_vars_from_src(string_sample)
OrderedDict([('a', '1')])
>>> int_sample = "b = 1"
>>> get_simple_vars_from_src(int_sample)
OrderedDict([('b', 1)])
>>> list_sample = "c = [u'1', b'1', 1, 1.0, 1j, None]"
>>> result = get_simple_vars_from_src(list_sample)
>>> result == collections.OrderedDict(
... [('c', [u'1', b'1', 1, 1.0, 1j, None])]
... )
True
>>> iterable_sample = "d = ([1], {1: 1}, {1})"
>>> get_simple_vars_from_src(iterable_sample)
OrderedDict([('d', ([1], {1: 1}, {1}))])
>>> multiple_assign = "e = f = g = 1"
>>> get_simple_vars_from_src(multiple_assign)
OrderedDict([('e', 1), ('f', 1), ('g', 1)])
"""
ast_data = (ast.Str, ast.Num, ast.List, ast.Set, ast.Dict, ast.Tuple, ast.Bytes, ast.NameConstant)
tree = ast.parse(src)
result = collections.OrderedDict()
for node in ast.iter_child_nodes(tree):
if not isinstance(node, ast.Assign): # We parse assigns only
continue
try:
if isinstance(node.value, ast_data):
value = ast.literal_eval(node.value)
else:
continue
except ValueError:
continue
for tgt in node.targets:
if isinstance(tgt, ast.Name) and isinstance(tgt.ctx, ast.Store):
result[tgt.id] = value
return result
|
def get_simple_vars_from_src(src):
"""Get simple (string/number/boolean and None) assigned values from source.
:param src: Source code
:type src: str
:returns: OrderedDict with keys, values = variable names, values
:rtype: typing.Dict[
str,
typing.Union[
str, bytes,
int, float, complex,
list, set, dict, tuple,
None,
]
]
Limitations: Only defined from scratch variables.
Not supported by design:
* Imports
* Executable code, including string formatting and comprehensions.
Examples:
>>> string_sample = "a = '1'"
>>> get_simple_vars_from_src(string_sample)
OrderedDict([('a', '1')])
>>> int_sample = "b = 1"
>>> get_simple_vars_from_src(int_sample)
OrderedDict([('b', 1)])
>>> list_sample = "c = [u'1', b'1', 1, 1.0, 1j, None]"
>>> result = get_simple_vars_from_src(list_sample)
>>> result == collections.OrderedDict(
... [('c', [u'1', b'1', 1, 1.0, 1j, None])]
... )
True
>>> iterable_sample = "d = ([1], {1: 1}, {1})"
>>> get_simple_vars_from_src(iterable_sample)
OrderedDict([('d', ([1], {1: 1}, {1}))])
>>> multiple_assign = "e = f = g = 1"
>>> get_simple_vars_from_src(multiple_assign)
OrderedDict([('e', 1), ('f', 1), ('g', 1)])
"""
ast_data = (ast.Str, ast.Num, ast.List, ast.Set, ast.Dict, ast.Tuple, ast.Bytes, ast.NameConstant)
tree = ast.parse(src)
result = collections.OrderedDict()
for node in ast.iter_child_nodes(tree):
if not isinstance(node, ast.Assign): # We parse assigns only
continue
try:
if isinstance(node.value, ast_data):
value = ast.literal_eval(node.value)
else:
continue
except ValueError:
continue
for tgt in node.targets:
if isinstance(tgt, ast.Name) and isinstance(tgt.ctx, ast.Store):
result[tgt.id] = value
return result
|
[
"Get",
"simple",
"(",
"string",
"/",
"number",
"/",
"boolean",
"and",
"None",
")",
"assigned",
"values",
"from",
"source",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/setup.py#L120-L185
|
[
"def",
"get_simple_vars_from_src",
"(",
"src",
")",
":",
"ast_data",
"=",
"(",
"ast",
".",
"Str",
",",
"ast",
".",
"Num",
",",
"ast",
".",
"List",
",",
"ast",
".",
"Set",
",",
"ast",
".",
"Dict",
",",
"ast",
".",
"Tuple",
",",
"ast",
".",
"Bytes",
",",
"ast",
".",
"NameConstant",
")",
"tree",
"=",
"ast",
".",
"parse",
"(",
"src",
")",
"result",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"node",
"in",
"ast",
".",
"iter_child_nodes",
"(",
"tree",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Assign",
")",
":",
"# We parse assigns only",
"continue",
"try",
":",
"if",
"isinstance",
"(",
"node",
".",
"value",
",",
"ast_data",
")",
":",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"node",
".",
"value",
")",
"else",
":",
"continue",
"except",
"ValueError",
":",
"continue",
"for",
"tgt",
"in",
"node",
".",
"targets",
":",
"if",
"isinstance",
"(",
"tgt",
",",
"ast",
".",
"Name",
")",
"and",
"isinstance",
"(",
"tgt",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"result",
"[",
"tgt",
".",
"id",
"]",
"=",
"value",
"return",
"result"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
AllowFailRepair.run
|
Run.
:raises BuildFailed: extension build failed and need to skip cython part.
|
setup.py
|
def run(self):
"""Run.
:raises BuildFailed: extension build failed and need to skip cython part.
"""
try:
build_ext.build_ext.run(self)
# Copy __init__.py back to repair package.
build_dir = os.path.abspath(self.build_lib)
root_dir = os.path.abspath(os.path.join(__file__, ".."))
target_dir = build_dir if not self.inplace else root_dir
src_file = os.path.join("advanced_descriptors", "__init__.py")
src = os.path.join(root_dir, src_file)
dst = os.path.join(target_dir, src_file)
if src != dst:
shutil.copyfile(src, dst)
except (
distutils.errors.DistutilsPlatformError,
FileNotFoundError,
):
raise BuildFailed()
|
def run(self):
"""Run.
:raises BuildFailed: extension build failed and need to skip cython part.
"""
try:
build_ext.build_ext.run(self)
# Copy __init__.py back to repair package.
build_dir = os.path.abspath(self.build_lib)
root_dir = os.path.abspath(os.path.join(__file__, ".."))
target_dir = build_dir if not self.inplace else root_dir
src_file = os.path.join("advanced_descriptors", "__init__.py")
src = os.path.join(root_dir, src_file)
dst = os.path.join(target_dir, src_file)
if src != dst:
shutil.copyfile(src, dst)
except (
distutils.errors.DistutilsPlatformError,
FileNotFoundError,
):
raise BuildFailed()
|
[
"Run",
"."
] |
python-useful-helpers/advanced-descriptors
|
python
|
https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/setup.py#L77-L101
|
[
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"build_ext",
".",
"build_ext",
".",
"run",
"(",
"self",
")",
"# Copy __init__.py back to repair package.",
"build_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"build_lib",
")",
"root_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"\"..\"",
")",
")",
"target_dir",
"=",
"build_dir",
"if",
"not",
"self",
".",
"inplace",
"else",
"root_dir",
"src_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"advanced_descriptors\"",
",",
"\"__init__.py\"",
")",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"src_file",
")",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"src_file",
")",
"if",
"src",
"!=",
"dst",
":",
"shutil",
".",
"copyfile",
"(",
"src",
",",
"dst",
")",
"except",
"(",
"distutils",
".",
"errors",
".",
"DistutilsPlatformError",
",",
"FileNotFoundError",
",",
")",
":",
"raise",
"BuildFailed",
"(",
")"
] |
17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003
|
test
|
SlackAPI._call_api
|
Low-level method to call the Slack API.
Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added
|
djangobot/slack.py
|
def _call_api(self, method, params=None):
"""
Low-level method to call the Slack API.
Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added
"""
url = self.url.format(method=method)
if not params:
params = {'token': self.token}
else:
params['token'] = self.token
logger.debug('Send request to %s', url)
response = requests.get(url, params=params).json()
if self.verify:
if not response['ok']:
msg = 'For {url} API returned this bad response {response}'
raise Exception(msg.format(url=url, response=response))
return response
|
def _call_api(self, method, params=None):
"""
Low-level method to call the Slack API.
Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added
"""
url = self.url.format(method=method)
if not params:
params = {'token': self.token}
else:
params['token'] = self.token
logger.debug('Send request to %s', url)
response = requests.get(url, params=params).json()
if self.verify:
if not response['ok']:
msg = 'For {url} API returned this bad response {response}'
raise Exception(msg.format(url=url, response=response))
return response
|
[
"Low",
"-",
"level",
"method",
"to",
"call",
"the",
"Slack",
"API",
"."
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/slack.py#L45-L65
|
[
"def",
"_call_api",
"(",
"self",
",",
"method",
",",
"params",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"url",
".",
"format",
"(",
"method",
"=",
"method",
")",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"'token'",
":",
"self",
".",
"token",
"}",
"else",
":",
"params",
"[",
"'token'",
"]",
"=",
"self",
".",
"token",
"logger",
".",
"debug",
"(",
"'Send request to %s'",
",",
"url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
".",
"json",
"(",
")",
"if",
"self",
".",
"verify",
":",
"if",
"not",
"response",
"[",
"'ok'",
"]",
":",
"msg",
"=",
"'For {url} API returned this bad response {response}'",
"raise",
"Exception",
"(",
"msg",
".",
"format",
"(",
"url",
"=",
"url",
",",
"response",
"=",
"response",
")",
")",
"return",
"response"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackAPI.channels
|
List of channels of this slack team
|
djangobot/slack.py
|
def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
self._channels = self._call_api('channels.list')['channels']
return self._channels
|
def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
self._channels = self._call_api('channels.list')['channels']
return self._channels
|
[
"List",
"of",
"channels",
"of",
"this",
"slack",
"team"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/slack.py#L68-L74
|
[
"def",
"channels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_channels",
":",
"self",
".",
"_channels",
"=",
"self",
".",
"_call_api",
"(",
"'channels.list'",
")",
"[",
"'channels'",
"]",
"return",
"self",
".",
"_channels"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackAPI.users
|
List of users of this slack team
|
djangobot/slack.py
|
def users(self):
"""
List of users of this slack team
"""
if not self._users:
self._users = self._call_api('users.list')['members']
return self._users
|
def users(self):
"""
List of users of this slack team
"""
if not self._users:
self._users = self._call_api('users.list')['members']
return self._users
|
[
"List",
"of",
"users",
"of",
"this",
"slack",
"team"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/slack.py#L77-L83
|
[
"def",
"users",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_users",
":",
"self",
".",
"_users",
"=",
"self",
".",
"_call_api",
"(",
"'users.list'",
")",
"[",
"'members'",
"]",
"return",
"self",
".",
"_users"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackAPI.channel_from_name
|
Return the channel dict given by human-readable {name}
|
djangobot/slack.py
|
def channel_from_name(self, name):
"""
Return the channel dict given by human-readable {name}
"""
try:
channel = [channel for channel in self.channels
if channel['name'] == name][0]
except IndexError:
raise ValueError('Unknown channel for name: "{}"'.format(name))
return channel
|
def channel_from_name(self, name):
"""
Return the channel dict given by human-readable {name}
"""
try:
channel = [channel for channel in self.channels
if channel['name'] == name][0]
except IndexError:
raise ValueError('Unknown channel for name: "{}"'.format(name))
return channel
|
[
"Return",
"the",
"channel",
"dict",
"given",
"by",
"human",
"-",
"readable",
"{",
"name",
"}"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/slack.py#L99-L108
|
[
"def",
"channel_from_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"channel",
"=",
"[",
"channel",
"for",
"channel",
"in",
"self",
".",
"channels",
"if",
"channel",
"[",
"'name'",
"]",
"==",
"name",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'Unknown channel for name: \"{}\"'",
".",
"format",
"(",
"name",
")",
")",
"return",
"channel"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackClientProtocol.make_message
|
High-level function for creating messages. Return packed bytes.
Args:
text: {str}
channel: {str} Either name or ID
|
djangobot/client.py
|
def make_message(self, text, channel):
"""
High-level function for creating messages. Return packed bytes.
Args:
text: {str}
channel: {str} Either name or ID
"""
try:
channel_id = self.slack.channel_from_name(channel)['id']
except ValueError:
channel_id = channel
return pack({
'text': text,
'type': 'message',
'channel': channel_id,
'id': self.message_id,
})
|
def make_message(self, text, channel):
"""
High-level function for creating messages. Return packed bytes.
Args:
text: {str}
channel: {str} Either name or ID
"""
try:
channel_id = self.slack.channel_from_name(channel)['id']
except ValueError:
channel_id = channel
return pack({
'text': text,
'type': 'message',
'channel': channel_id,
'id': self.message_id,
})
|
[
"High",
"-",
"level",
"function",
"for",
"creating",
"messages",
".",
"Return",
"packed",
"bytes",
"."
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L49-L66
|
[
"def",
"make_message",
"(",
"self",
",",
"text",
",",
"channel",
")",
":",
"try",
":",
"channel_id",
"=",
"self",
".",
"slack",
".",
"channel_from_name",
"(",
"channel",
")",
"[",
"'id'",
"]",
"except",
"ValueError",
":",
"channel_id",
"=",
"channel",
"return",
"pack",
"(",
"{",
"'text'",
":",
"text",
",",
"'type'",
":",
"'message'",
",",
"'channel'",
":",
"channel_id",
",",
"'id'",
":",
"self",
".",
"message_id",
",",
"}",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackClientProtocol.translate
|
Translate machine identifiers into human-readable
|
djangobot/client.py
|
def translate(self, message):
"""
Translate machine identifiers into human-readable
"""
# translate user
try:
user_id = message.pop('user')
user = self.slack.user_from_id(user_id)
message[u'user'] = user['name']
except (KeyError, IndexError, ValueError):
pass
# translate channel
try:
if type(message['channel']) == str:
channel_id = message.pop('channel')
else:
channel_id = message.pop('channel')['id']
self.slack.reload_channels()
channel = self.slack.channel_from_id(channel_id)
message[u'channel'] = channel['name']
except (KeyError, IndexError, ValueError):
pass
return message
|
def translate(self, message):
"""
Translate machine identifiers into human-readable
"""
# translate user
try:
user_id = message.pop('user')
user = self.slack.user_from_id(user_id)
message[u'user'] = user['name']
except (KeyError, IndexError, ValueError):
pass
# translate channel
try:
if type(message['channel']) == str:
channel_id = message.pop('channel')
else:
channel_id = message.pop('channel')['id']
self.slack.reload_channels()
channel = self.slack.channel_from_id(channel_id)
message[u'channel'] = channel['name']
except (KeyError, IndexError, ValueError):
pass
return message
|
[
"Translate",
"machine",
"identifiers",
"into",
"human",
"-",
"readable"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L68-L90
|
[
"def",
"translate",
"(",
"self",
",",
"message",
")",
":",
"# translate user",
"try",
":",
"user_id",
"=",
"message",
".",
"pop",
"(",
"'user'",
")",
"user",
"=",
"self",
".",
"slack",
".",
"user_from_id",
"(",
"user_id",
")",
"message",
"[",
"u'user'",
"]",
"=",
"user",
"[",
"'name'",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
",",
"ValueError",
")",
":",
"pass",
"# translate channel",
"try",
":",
"if",
"type",
"(",
"message",
"[",
"'channel'",
"]",
")",
"==",
"str",
":",
"channel_id",
"=",
"message",
".",
"pop",
"(",
"'channel'",
")",
"else",
":",
"channel_id",
"=",
"message",
".",
"pop",
"(",
"'channel'",
")",
"[",
"'id'",
"]",
"self",
".",
"slack",
".",
"reload_channels",
"(",
")",
"channel",
"=",
"self",
".",
"slack",
".",
"channel_from_id",
"(",
"channel_id",
")",
"message",
"[",
"u'channel'",
"]",
"=",
"channel",
"[",
"'name'",
"]",
"except",
"(",
"KeyError",
",",
"IndexError",
",",
"ValueError",
")",
":",
"pass",
"return",
"message"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackClientProtocol.onMessage
|
Send the payload onto the {slack.[payload['type]'} channel.
The message is transalated from IDs to human-readable identifiers.
Note: The slack API only sends JSON, isBinary will always be false.
|
djangobot/client.py
|
def onMessage(self, payload, isBinary):
"""
Send the payload onto the {slack.[payload['type]'} channel.
The message is transalated from IDs to human-readable identifiers.
Note: The slack API only sends JSON, isBinary will always be false.
"""
msg = self.translate(unpack(payload))
if 'type' in msg:
channel_name = 'slack.{}'.format(msg['type'])
print('Sending on {}'.format(channel_name))
channels.Channel(channel_name).send({'text': pack(msg)})
|
def onMessage(self, payload, isBinary):
"""
Send the payload onto the {slack.[payload['type]'} channel.
The message is transalated from IDs to human-readable identifiers.
Note: The slack API only sends JSON, isBinary will always be false.
"""
msg = self.translate(unpack(payload))
if 'type' in msg:
channel_name = 'slack.{}'.format(msg['type'])
print('Sending on {}'.format(channel_name))
channels.Channel(channel_name).send({'text': pack(msg)})
|
[
"Send",
"the",
"payload",
"onto",
"the",
"{",
"slack",
".",
"[",
"payload",
"[",
"type",
"]",
"}",
"channel",
".",
"The",
"message",
"is",
"transalated",
"from",
"IDs",
"to",
"human",
"-",
"readable",
"identifiers",
"."
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L98-L109
|
[
"def",
"onMessage",
"(",
"self",
",",
"payload",
",",
"isBinary",
")",
":",
"msg",
"=",
"self",
".",
"translate",
"(",
"unpack",
"(",
"payload",
")",
")",
"if",
"'type'",
"in",
"msg",
":",
"channel_name",
"=",
"'slack.{}'",
".",
"format",
"(",
"msg",
"[",
"'type'",
"]",
")",
"print",
"(",
"'Sending on {}'",
".",
"format",
"(",
"channel_name",
")",
")",
"channels",
".",
"Channel",
"(",
"channel_name",
")",
".",
"send",
"(",
"{",
"'text'",
":",
"pack",
"(",
"msg",
")",
"}",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackClientProtocol.sendSlack
|
Send message to Slack
|
djangobot/client.py
|
def sendSlack(self, message):
"""
Send message to Slack
"""
channel = message.get('channel', 'general')
self.sendMessage(self.make_message(message['text'], channel))
|
def sendSlack(self, message):
"""
Send message to Slack
"""
channel = message.get('channel', 'general')
self.sendMessage(self.make_message(message['text'], channel))
|
[
"Send",
"message",
"to",
"Slack"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L111-L116
|
[
"def",
"sendSlack",
"(",
"self",
",",
"message",
")",
":",
"channel",
"=",
"message",
".",
"get",
"(",
"'channel'",
",",
"'general'",
")",
"self",
".",
"sendMessage",
"(",
"self",
".",
"make_message",
"(",
"message",
"[",
"'text'",
"]",
",",
"channel",
")",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
SlackClientFactory.read_channel
|
Get available messages and send through to the protocol
|
djangobot/client.py
|
def read_channel(self):
"""
Get available messages and send through to the protocol
"""
channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False)
delay = 0.1
if channel:
self.protocols[0].sendSlack(message)
reactor.callLater(delay, self.read_channel)
|
def read_channel(self):
"""
Get available messages and send through to the protocol
"""
channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False)
delay = 0.1
if channel:
self.protocols[0].sendSlack(message)
reactor.callLater(delay, self.read_channel)
|
[
"Get",
"available",
"messages",
"and",
"send",
"through",
"to",
"the",
"protocol"
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L131-L139
|
[
"def",
"read_channel",
"(",
"self",
")",
":",
"channel",
",",
"message",
"=",
"self",
".",
"protocol",
".",
"channel_layer",
".",
"receive_many",
"(",
"[",
"u'slack.send'",
"]",
",",
"block",
"=",
"False",
")",
"delay",
"=",
"0.1",
"if",
"channel",
":",
"self",
".",
"protocols",
"[",
"0",
"]",
".",
"sendSlack",
"(",
"message",
")",
"reactor",
".",
"callLater",
"(",
"delay",
",",
"self",
".",
"read_channel",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
Client.run
|
Main interface. Instantiate the SlackAPI, connect to RTM
and start the client.
|
djangobot/client.py
|
def run(self):
"""
Main interface. Instantiate the SlackAPI, connect to RTM
and start the client.
"""
slack = SlackAPI(token=self.token)
rtm = slack.rtm_start()
factory = SlackClientFactory(rtm['url'])
# Attach attributes
factory.protocol = SlackClientProtocol
factory.protocol.slack = slack
factory.protocol.channel_layer = self.channel_layer
factory.channel_name = self.channel_name
# Here we go
factory.run()
|
def run(self):
"""
Main interface. Instantiate the SlackAPI, connect to RTM
and start the client.
"""
slack = SlackAPI(token=self.token)
rtm = slack.rtm_start()
factory = SlackClientFactory(rtm['url'])
# Attach attributes
factory.protocol = SlackClientProtocol
factory.protocol.slack = slack
factory.protocol.channel_layer = self.channel_layer
factory.channel_name = self.channel_name
# Here we go
factory.run()
|
[
"Main",
"interface",
".",
"Instantiate",
"the",
"SlackAPI",
"connect",
"to",
"RTM",
"and",
"start",
"the",
"client",
"."
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/client.py#L159-L175
|
[
"def",
"run",
"(",
"self",
")",
":",
"slack",
"=",
"SlackAPI",
"(",
"token",
"=",
"self",
".",
"token",
")",
"rtm",
"=",
"slack",
".",
"rtm_start",
"(",
")",
"factory",
"=",
"SlackClientFactory",
"(",
"rtm",
"[",
"'url'",
"]",
")",
"# Attach attributes",
"factory",
".",
"protocol",
"=",
"SlackClientProtocol",
"factory",
".",
"protocol",
".",
"slack",
"=",
"slack",
"factory",
".",
"protocol",
".",
"channel_layer",
"=",
"self",
".",
"channel_layer",
"factory",
".",
"channel_name",
"=",
"self",
".",
"channel_name",
"# Here we go",
"factory",
".",
"run",
"(",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
CLI.run
|
Pass in raw arguments, instantiate Slack API and begin client.
|
djangobot/cli.py
|
def run(self, args):
"""
Pass in raw arguments, instantiate Slack API and begin client.
"""
args = self.parser.parse_args(args)
if not args.token:
raise ValueError('Supply the slack token through --token or setting DJANGOBOT_TOKEN')
# Import the channel layer
sys.path.insert(0, ".")
module_path, object_path = args.channel_layer.split(':', 1)
channel_layer = importlib.import_module(module_path)
for part in object_path.split('.'):
channel_layer = getattr(channel_layer, part)
# Boot up the client
Client(
channel_layer=channel_layer,
token=args.token,
).run()
|
def run(self, args):
"""
Pass in raw arguments, instantiate Slack API and begin client.
"""
args = self.parser.parse_args(args)
if not args.token:
raise ValueError('Supply the slack token through --token or setting DJANGOBOT_TOKEN')
# Import the channel layer
sys.path.insert(0, ".")
module_path, object_path = args.channel_layer.split(':', 1)
channel_layer = importlib.import_module(module_path)
for part in object_path.split('.'):
channel_layer = getattr(channel_layer, part)
# Boot up the client
Client(
channel_layer=channel_layer,
token=args.token,
).run()
|
[
"Pass",
"in",
"raw",
"arguments",
"instantiate",
"Slack",
"API",
"and",
"begin",
"client",
"."
] |
djangobot/djangobot
|
python
|
https://github.com/djangobot/djangobot/blob/0ec951891812ea4114c27a08c790f63d0f0fd254/djangobot/cli.py#L38-L57
|
[
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"if",
"not",
"args",
".",
"token",
":",
"raise",
"ValueError",
"(",
"'Supply the slack token through --token or setting DJANGOBOT_TOKEN'",
")",
"# Import the channel layer",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"\".\"",
")",
"module_path",
",",
"object_path",
"=",
"args",
".",
"channel_layer",
".",
"split",
"(",
"':'",
",",
"1",
")",
"channel_layer",
"=",
"importlib",
".",
"import_module",
"(",
"module_path",
")",
"for",
"part",
"in",
"object_path",
".",
"split",
"(",
"'.'",
")",
":",
"channel_layer",
"=",
"getattr",
"(",
"channel_layer",
",",
"part",
")",
"# Boot up the client",
"Client",
"(",
"channel_layer",
"=",
"channel_layer",
",",
"token",
"=",
"args",
".",
"token",
",",
")",
".",
"run",
"(",
")"
] |
0ec951891812ea4114c27a08c790f63d0f0fd254
|
test
|
yc_individual_napalm_star_wars__universe_individual._set_affiliation
|
Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_affiliation is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_affiliation() directly.
|
docs/root/yang/napalm_star_wars.py
|
def _set_affiliation(self, v, load=False):
"""
Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_affiliation is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_affiliation() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=unicode,
restriction_type="dict_key",
restriction_arg={
u"napalm-star-wars:EMPIRE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"EMPIRE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"napalm-star-wars:REBEL_ALLIANCE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"REBEL_ALLIANCE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
},
),
is_leaf=True,
yang_name="affiliation",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="https://napalm-yang.readthedocs.io/napalm-star-wars",
defining_module="napalm-star-wars",
yang_type="identityref",
is_config=True,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """affiliation must be of a type compatible with identityref""",
"defined-type": "napalm-star-wars:identityref",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'napalm-star-wars:EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'napalm-star-wars:REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}},), is_leaf=True, yang_name="affiliation", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='https://napalm-yang.readthedocs.io/napalm-star-wars', defining_module='napalm-star-wars', yang_type='identityref', is_config=True)""",
}
)
self.__affiliation = t
if hasattr(self, "_set"):
self._set()
|
def _set_affiliation(self, v, load=False):
"""
Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_affiliation is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_affiliation() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=unicode,
restriction_type="dict_key",
restriction_arg={
u"napalm-star-wars:EMPIRE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"EMPIRE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"napalm-star-wars:REBEL_ALLIANCE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
u"REBEL_ALLIANCE": {
"@namespace": u"https://napalm-yang.readthedocs.io/napalm-star-wars",
"@module": u"napalm-star-wars",
},
},
),
is_leaf=True,
yang_name="affiliation",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="https://napalm-yang.readthedocs.io/napalm-star-wars",
defining_module="napalm-star-wars",
yang_type="identityref",
is_config=True,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """affiliation must be of a type compatible with identityref""",
"defined-type": "napalm-star-wars:identityref",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'napalm-star-wars:EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'napalm-star-wars:REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}},), is_leaf=True, yang_name="affiliation", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='https://napalm-yang.readthedocs.io/napalm-star-wars', defining_module='napalm-star-wars', yang_type='identityref', is_config=True)""",
}
)
self.__affiliation = t
if hasattr(self, "_set"):
self._set()
|
[
"Setter",
"method",
"for",
"affiliation",
"mapped",
"from",
"YANG",
"variable",
"/",
"universe",
"/",
"individual",
"/",
"affiliation",
"(",
"identityref",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
"_set_affiliation",
"is",
"considered",
"as",
"a",
"private",
"method",
".",
"Backends",
"looking",
"to",
"populate",
"this",
"variable",
"should",
"do",
"so",
"via",
"calling",
"thisObj",
".",
"_set_affiliation",
"()",
"directly",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/docs/root/yang/napalm_star_wars.py#L289-L346
|
[
"def",
"_set_affiliation",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=",
"RestrictedClassType",
"(",
"base_type",
"=",
"unicode",
",",
"restriction_type",
"=",
"\"dict_key\"",
",",
"restriction_arg",
"=",
"{",
"u\"napalm-star-wars:EMPIRE\"",
":",
"{",
"\"@namespace\"",
":",
"u\"https://napalm-yang.readthedocs.io/napalm-star-wars\"",
",",
"\"@module\"",
":",
"u\"napalm-star-wars\"",
",",
"}",
",",
"u\"EMPIRE\"",
":",
"{",
"\"@namespace\"",
":",
"u\"https://napalm-yang.readthedocs.io/napalm-star-wars\"",
",",
"\"@module\"",
":",
"u\"napalm-star-wars\"",
",",
"}",
",",
"u\"napalm-star-wars:REBEL_ALLIANCE\"",
":",
"{",
"\"@namespace\"",
":",
"u\"https://napalm-yang.readthedocs.io/napalm-star-wars\"",
",",
"\"@module\"",
":",
"u\"napalm-star-wars\"",
",",
"}",
",",
"u\"REBEL_ALLIANCE\"",
":",
"{",
"\"@namespace\"",
":",
"u\"https://napalm-yang.readthedocs.io/napalm-star-wars\"",
",",
"\"@module\"",
":",
"u\"napalm-star-wars\"",
",",
"}",
",",
"}",
",",
")",
",",
"is_leaf",
"=",
"True",
",",
"yang_name",
"=",
"\"affiliation\"",
",",
"parent",
"=",
"self",
",",
"path_helper",
"=",
"self",
".",
"_path_helper",
",",
"extmethods",
"=",
"self",
".",
"_extmethods",
",",
"register_paths",
"=",
"True",
",",
"namespace",
"=",
"\"https://napalm-yang.readthedocs.io/napalm-star-wars\"",
",",
"defining_module",
"=",
"\"napalm-star-wars\"",
",",
"yang_type",
"=",
"\"identityref\"",
",",
"is_config",
"=",
"True",
",",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"{",
"\"error-string\"",
":",
"\"\"\"affiliation must be of a type compatible with identityref\"\"\"",
",",
"\"defined-type\"",
":",
"\"napalm-star-wars:identityref\"",
",",
"\"generated-type\"",
":",
"\"\"\"YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type=\"dict_key\", restriction_arg={u'napalm-star-wars:EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'EMPIRE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'napalm-star-wars:REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}, u'REBEL_ALLIANCE': {'@namespace': u'https://napalm-yang.readthedocs.io/napalm-star-wars', '@module': u'napalm-star-wars'}},), is_leaf=True, yang_name=\"affiliation\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='https://napalm-yang.readthedocs.io/napalm-star-wars', defining_module='napalm-star-wars', yang_type='identityref', is_config=True)\"\"\"",
",",
"}",
")",
"self",
".",
"__affiliation",
"=",
"t",
"if",
"hasattr",
"(",
"self",
",",
"\"_set\"",
")",
":",
"self",
".",
"_set",
"(",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
dict_diff
|
Return a dict of keys that differ with another config object.
|
interactive_demo/ansible/callback/selective.py
|
def dict_diff(prv, nxt):
"""Return a dict of keys that differ with another config object."""
keys = set(prv.keys() + nxt.keys())
result = {}
for k in keys:
if prv.get(k) != nxt.get(k):
result[k] = (prv.get(k), nxt.get(k))
return result
|
def dict_diff(prv, nxt):
"""Return a dict of keys that differ with another config object."""
keys = set(prv.keys() + nxt.keys())
result = {}
for k in keys:
if prv.get(k) != nxt.get(k):
result[k] = (prv.get(k), nxt.get(k))
return result
|
[
"Return",
"a",
"dict",
"of",
"keys",
"that",
"differ",
"with",
"another",
"config",
"object",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L63-L70
|
[
"def",
"dict_diff",
"(",
"prv",
",",
"nxt",
")",
":",
"keys",
"=",
"set",
"(",
"prv",
".",
"keys",
"(",
")",
"+",
"nxt",
".",
"keys",
"(",
")",
")",
"result",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"if",
"prv",
".",
"get",
"(",
"k",
")",
"!=",
"nxt",
".",
"get",
"(",
"k",
")",
":",
"result",
"[",
"k",
"]",
"=",
"(",
"prv",
".",
"get",
"(",
"k",
")",
",",
"nxt",
".",
"get",
"(",
"k",
")",
")",
"return",
"result"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
colorize
|
Given a string add necessary codes to format the string.
|
interactive_demo/ansible/callback/selective.py
|
def colorize(msg, color):
"""Given a string add necessary codes to format the string."""
if DONT_COLORIZE:
return msg
else:
return "{}{}{}".format(COLORS[color], msg, COLORS["endc"])
|
def colorize(msg, color):
"""Given a string add necessary codes to format the string."""
if DONT_COLORIZE:
return msg
else:
return "{}{}{}".format(COLORS[color], msg, COLORS["endc"])
|
[
"Given",
"a",
"string",
"add",
"necessary",
"codes",
"to",
"format",
"the",
"string",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L73-L78
|
[
"def",
"colorize",
"(",
"msg",
",",
"color",
")",
":",
"if",
"DONT_COLORIZE",
":",
"return",
"msg",
"else",
":",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"COLORS",
"[",
"color",
"]",
",",
"msg",
",",
"COLORS",
"[",
"\"endc\"",
"]",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
CallbackModule.v2_playbook_on_task_start
|
Run when a task starts.
|
interactive_demo/ansible/callback/selective.py
|
def v2_playbook_on_task_start(self, task, **kwargs):
"""Run when a task starts."""
self.last_task_name = task.get_name()
self.printed_last_task = False
|
def v2_playbook_on_task_start(self, task, **kwargs):
"""Run when a task starts."""
self.last_task_name = task.get_name()
self.printed_last_task = False
|
[
"Run",
"when",
"a",
"task",
"starts",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L180-L183
|
[
"def",
"v2_playbook_on_task_start",
"(",
"self",
",",
"task",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"last_task_name",
"=",
"task",
".",
"get_name",
"(",
")",
"self",
".",
"printed_last_task",
"=",
"False"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
CallbackModule.v2_runner_on_ok
|
Run when a task finishes correctly.
|
interactive_demo/ansible/callback/selective.py
|
def v2_runner_on_ok(self, result, **kwargs):
"""Run when a task finishes correctly."""
failed = "failed" in result._result
unreachable = "unreachable" in result._result
if (
"print_action" in result._task.tags
or failed
or unreachable
or self._display.verbosity > 1
):
self._print_task()
self.last_skipped = False
msg = unicode(result._result.get("msg", "")) or unicode(
result._result.get("reason", "")
) or unicode(
result._result.get("message", "")
)
stderr = [
result._result.get("exception", None),
result._result.get("module_stderr", None),
]
stderr = "\n".join([e for e in stderr if e]).strip()
self._print_host_or_item(
result._host,
result._result.get("changed", False),
msg,
result._result.get("diff", None),
is_host=True,
error=failed or unreachable,
stdout=result._result.get("module_stdout", None),
stderr=stderr.strip(),
)
if "results" in result._result:
for r in result._result["results"]:
failed = "failed" in r
stderr = [r.get("exception", None), r.get("module_stderr", None)]
stderr = "\n".join([e for e in stderr if e]).strip()
self._print_host_or_item(
r["item"],
r.get("changed", False),
unicode(r.get("msg", "")),
r.get("diff", None),
is_host=False,
error=failed,
stdout=r.get("module_stdout", None),
stderr=stderr.strip(),
)
else:
self.last_skipped = True
print(".", end="")
|
def v2_runner_on_ok(self, result, **kwargs):
"""Run when a task finishes correctly."""
failed = "failed" in result._result
unreachable = "unreachable" in result._result
if (
"print_action" in result._task.tags
or failed
or unreachable
or self._display.verbosity > 1
):
self._print_task()
self.last_skipped = False
msg = unicode(result._result.get("msg", "")) or unicode(
result._result.get("reason", "")
) or unicode(
result._result.get("message", "")
)
stderr = [
result._result.get("exception", None),
result._result.get("module_stderr", None),
]
stderr = "\n".join([e for e in stderr if e]).strip()
self._print_host_or_item(
result._host,
result._result.get("changed", False),
msg,
result._result.get("diff", None),
is_host=True,
error=failed or unreachable,
stdout=result._result.get("module_stdout", None),
stderr=stderr.strip(),
)
if "results" in result._result:
for r in result._result["results"]:
failed = "failed" in r
stderr = [r.get("exception", None), r.get("module_stderr", None)]
stderr = "\n".join([e for e in stderr if e]).strip()
self._print_host_or_item(
r["item"],
r.get("changed", False),
unicode(r.get("msg", "")),
r.get("diff", None),
is_host=False,
error=failed,
stdout=r.get("module_stdout", None),
stderr=stderr.strip(),
)
else:
self.last_skipped = True
print(".", end="")
|
[
"Run",
"when",
"a",
"task",
"finishes",
"correctly",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L185-L240
|
[
"def",
"v2_runner_on_ok",
"(",
"self",
",",
"result",
",",
"*",
"*",
"kwargs",
")",
":",
"failed",
"=",
"\"failed\"",
"in",
"result",
".",
"_result",
"unreachable",
"=",
"\"unreachable\"",
"in",
"result",
".",
"_result",
"if",
"(",
"\"print_action\"",
"in",
"result",
".",
"_task",
".",
"tags",
"or",
"failed",
"or",
"unreachable",
"or",
"self",
".",
"_display",
".",
"verbosity",
">",
"1",
")",
":",
"self",
".",
"_print_task",
"(",
")",
"self",
".",
"last_skipped",
"=",
"False",
"msg",
"=",
"unicode",
"(",
"result",
".",
"_result",
".",
"get",
"(",
"\"msg\"",
",",
"\"\"",
")",
")",
"or",
"unicode",
"(",
"result",
".",
"_result",
".",
"get",
"(",
"\"reason\"",
",",
"\"\"",
")",
")",
"or",
"unicode",
"(",
"result",
".",
"_result",
".",
"get",
"(",
"\"message\"",
",",
"\"\"",
")",
")",
"stderr",
"=",
"[",
"result",
".",
"_result",
".",
"get",
"(",
"\"exception\"",
",",
"None",
")",
",",
"result",
".",
"_result",
".",
"get",
"(",
"\"module_stderr\"",
",",
"None",
")",
",",
"]",
"stderr",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"e",
"for",
"e",
"in",
"stderr",
"if",
"e",
"]",
")",
".",
"strip",
"(",
")",
"self",
".",
"_print_host_or_item",
"(",
"result",
".",
"_host",
",",
"result",
".",
"_result",
".",
"get",
"(",
"\"changed\"",
",",
"False",
")",
",",
"msg",
",",
"result",
".",
"_result",
".",
"get",
"(",
"\"diff\"",
",",
"None",
")",
",",
"is_host",
"=",
"True",
",",
"error",
"=",
"failed",
"or",
"unreachable",
",",
"stdout",
"=",
"result",
".",
"_result",
".",
"get",
"(",
"\"module_stdout\"",
",",
"None",
")",
",",
"stderr",
"=",
"stderr",
".",
"strip",
"(",
")",
",",
")",
"if",
"\"results\"",
"in",
"result",
".",
"_result",
":",
"for",
"r",
"in",
"result",
".",
"_result",
"[",
"\"results\"",
"]",
":",
"failed",
"=",
"\"failed\"",
"in",
"r",
"stderr",
"=",
"[",
"r",
".",
"get",
"(",
"\"exception\"",
",",
"None",
")",
",",
"r",
".",
"get",
"(",
"\"module_stderr\"",
",",
"None",
")",
"]",
"stderr",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"e",
"for",
"e",
"in",
"stderr",
"if",
"e",
"]",
")",
".",
"strip",
"(",
")",
"self",
".",
"_print_host_or_item",
"(",
"r",
"[",
"\"item\"",
"]",
",",
"r",
".",
"get",
"(",
"\"changed\"",
",",
"False",
")",
",",
"unicode",
"(",
"r",
".",
"get",
"(",
"\"msg\"",
",",
"\"\"",
")",
")",
",",
"r",
".",
"get",
"(",
"\"diff\"",
",",
"None",
")",
",",
"is_host",
"=",
"False",
",",
"error",
"=",
"failed",
",",
"stdout",
"=",
"r",
".",
"get",
"(",
"\"module_stdout\"",
",",
"None",
")",
",",
"stderr",
"=",
"stderr",
".",
"strip",
"(",
")",
",",
")",
"else",
":",
"self",
".",
"last_skipped",
"=",
"True",
"print",
"(",
"\".\"",
",",
"end",
"=",
"\"\"",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
CallbackModule.v2_playbook_on_stats
|
Display info about playbook statistics.
|
interactive_demo/ansible/callback/selective.py
|
def v2_playbook_on_stats(self, stats):
"""Display info about playbook statistics."""
print()
self.printed_last_task = False
self._print_task("STATS")
hosts = sorted(stats.processed.keys())
for host in hosts:
s = stats.summarize(host)
if s["failures"] or s["unreachable"]:
color = "failed"
elif s["changed"]:
color = "changed"
else:
color = "ok"
msg = "{} : ok={}\tchanged={}\tfailed={}\tunreachable={}".format(
host, s["ok"], s["changed"], s["failures"], s["unreachable"]
)
print(colorize(msg, color))
|
def v2_playbook_on_stats(self, stats):
"""Display info about playbook statistics."""
print()
self.printed_last_task = False
self._print_task("STATS")
hosts = sorted(stats.processed.keys())
for host in hosts:
s = stats.summarize(host)
if s["failures"] or s["unreachable"]:
color = "failed"
elif s["changed"]:
color = "changed"
else:
color = "ok"
msg = "{} : ok={}\tchanged={}\tfailed={}\tunreachable={}".format(
host, s["ok"], s["changed"], s["failures"], s["unreachable"]
)
print(colorize(msg, color))
|
[
"Display",
"info",
"about",
"playbook",
"statistics",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L242-L262
|
[
"def",
"v2_playbook_on_stats",
"(",
"self",
",",
"stats",
")",
":",
"print",
"(",
")",
"self",
".",
"printed_last_task",
"=",
"False",
"self",
".",
"_print_task",
"(",
"\"STATS\"",
")",
"hosts",
"=",
"sorted",
"(",
"stats",
".",
"processed",
".",
"keys",
"(",
")",
")",
"for",
"host",
"in",
"hosts",
":",
"s",
"=",
"stats",
".",
"summarize",
"(",
"host",
")",
"if",
"s",
"[",
"\"failures\"",
"]",
"or",
"s",
"[",
"\"unreachable\"",
"]",
":",
"color",
"=",
"\"failed\"",
"elif",
"s",
"[",
"\"changed\"",
"]",
":",
"color",
"=",
"\"changed\"",
"else",
":",
"color",
"=",
"\"ok\"",
"msg",
"=",
"\"{} : ok={}\\tchanged={}\\tfailed={}\\tunreachable={}\"",
".",
"format",
"(",
"host",
",",
"s",
"[",
"\"ok\"",
"]",
",",
"s",
"[",
"\"changed\"",
"]",
",",
"s",
"[",
"\"failures\"",
"]",
",",
"s",
"[",
"\"unreachable\"",
"]",
")",
"print",
"(",
"colorize",
"(",
"msg",
",",
"color",
")",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
CallbackModule.v2_runner_on_skipped
|
Run when a task is skipped.
|
interactive_demo/ansible/callback/selective.py
|
def v2_runner_on_skipped(self, result, **kwargs):
"""Run when a task is skipped."""
if self._display.verbosity > 1:
self._print_task()
self.last_skipped = False
line_length = 120
spaces = " " * (31 - len(result._host.name) - 4)
line = " * {}{}- {}".format(
colorize(result._host.name, "not_so_bold"),
spaces,
colorize("skipped", "skipped"),
)
reason = result._result.get("skipped_reason", "") or result._result.get(
"skip_reason", ""
)
if len(reason) < 50:
line += " -- {}".format(reason)
print("{} {}---------".format(line, "-" * (line_length - len(line))))
else:
print("{} {}".format(line, "-" * (line_length - len(line))))
print(self._indent_text(reason, 8))
print(reason)
|
def v2_runner_on_skipped(self, result, **kwargs):
"""Run when a task is skipped."""
if self._display.verbosity > 1:
self._print_task()
self.last_skipped = False
line_length = 120
spaces = " " * (31 - len(result._host.name) - 4)
line = " * {}{}- {}".format(
colorize(result._host.name, "not_so_bold"),
spaces,
colorize("skipped", "skipped"),
)
reason = result._result.get("skipped_reason", "") or result._result.get(
"skip_reason", ""
)
if len(reason) < 50:
line += " -- {}".format(reason)
print("{} {}---------".format(line, "-" * (line_length - len(line))))
else:
print("{} {}".format(line, "-" * (line_length - len(line))))
print(self._indent_text(reason, 8))
print(reason)
|
[
"Run",
"when",
"a",
"task",
"is",
"skipped",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L264-L288
|
[
"def",
"v2_runner_on_skipped",
"(",
"self",
",",
"result",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_display",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"_print_task",
"(",
")",
"self",
".",
"last_skipped",
"=",
"False",
"line_length",
"=",
"120",
"spaces",
"=",
"\" \"",
"*",
"(",
"31",
"-",
"len",
"(",
"result",
".",
"_host",
".",
"name",
")",
"-",
"4",
")",
"line",
"=",
"\" * {}{}- {}\"",
".",
"format",
"(",
"colorize",
"(",
"result",
".",
"_host",
".",
"name",
",",
"\"not_so_bold\"",
")",
",",
"spaces",
",",
"colorize",
"(",
"\"skipped\"",
",",
"\"skipped\"",
")",
",",
")",
"reason",
"=",
"result",
".",
"_result",
".",
"get",
"(",
"\"skipped_reason\"",
",",
"\"\"",
")",
"or",
"result",
".",
"_result",
".",
"get",
"(",
"\"skip_reason\"",
",",
"\"\"",
")",
"if",
"len",
"(",
"reason",
")",
"<",
"50",
":",
"line",
"+=",
"\" -- {}\"",
".",
"format",
"(",
"reason",
")",
"print",
"(",
"\"{} {}---------\"",
".",
"format",
"(",
"line",
",",
"\"-\"",
"*",
"(",
"line_length",
"-",
"len",
"(",
"line",
")",
")",
")",
")",
"else",
":",
"print",
"(",
"\"{} {}\"",
".",
"format",
"(",
"line",
",",
"\"-\"",
"*",
"(",
"line_length",
"-",
"len",
"(",
"line",
")",
")",
")",
")",
"print",
"(",
"self",
".",
"_indent_text",
"(",
"reason",
",",
"8",
")",
")",
"print",
"(",
"reason",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
parse_indented_config
|
This methid basically reads a configuration that conforms to a very poor industry standard
and returns a nested structure that behaves like a dict. For example:
{'enable password whatever': {},
'interface GigabitEthernet1': {
'description "bleh"': {},
'fake nested': {
'nested nested configuration': {}},
'switchport mode trunk': {}},
'interface GigabitEthernet2': {
'no ip address': {}},
'interface GigabitEthernet3': {
'negotiation auto': {},
'no ip address': {},
'shutdown': {}},
'interface Loopback0': {
'description "blah"': {}}}
|
napalm_yang/parsers/text_tree.py
|
def parse_indented_config(config, current_indent=0, previous_indent=0, nested=False):
"""
This methid basically reads a configuration that conforms to a very poor industry standard
and returns a nested structure that behaves like a dict. For example:
{'enable password whatever': {},
'interface GigabitEthernet1': {
'description "bleh"': {},
'fake nested': {
'nested nested configuration': {}},
'switchport mode trunk': {}},
'interface GigabitEthernet2': {
'no ip address': {}},
'interface GigabitEthernet3': {
'negotiation auto': {},
'no ip address': {},
'shutdown': {}},
'interface Loopback0': {
'description "blah"': {}}}
"""
parsed = OrderedDict()
while True:
if not config:
break
line = config.pop(0)
if line.lstrip().startswith("!"):
continue
last = line.lstrip()
leading_spaces = len(line) - len(last)
# print("current_indent:{}, previous:{}, leading:{} - {}".format(
# current_indent, previous_indent, leading_spaces, line))
if leading_spaces > current_indent:
current = parse_indented_config(
config, leading_spaces, current_indent, True
)
_attach_data_to_path(parsed, last, current, nested)
elif leading_spaces < current_indent:
config.insert(0, line)
break
else:
if not nested:
current = parse_indented_config(
config, leading_spaces, current_indent, True
)
_attach_data_to_path(parsed, last, current, nested)
else:
config.insert(0, line)
break
return parsed
|
def parse_indented_config(config, current_indent=0, previous_indent=0, nested=False):
"""
This methid basically reads a configuration that conforms to a very poor industry standard
and returns a nested structure that behaves like a dict. For example:
{'enable password whatever': {},
'interface GigabitEthernet1': {
'description "bleh"': {},
'fake nested': {
'nested nested configuration': {}},
'switchport mode trunk': {}},
'interface GigabitEthernet2': {
'no ip address': {}},
'interface GigabitEthernet3': {
'negotiation auto': {},
'no ip address': {},
'shutdown': {}},
'interface Loopback0': {
'description "blah"': {}}}
"""
parsed = OrderedDict()
while True:
if not config:
break
line = config.pop(0)
if line.lstrip().startswith("!"):
continue
last = line.lstrip()
leading_spaces = len(line) - len(last)
# print("current_indent:{}, previous:{}, leading:{} - {}".format(
# current_indent, previous_indent, leading_spaces, line))
if leading_spaces > current_indent:
current = parse_indented_config(
config, leading_spaces, current_indent, True
)
_attach_data_to_path(parsed, last, current, nested)
elif leading_spaces < current_indent:
config.insert(0, line)
break
else:
if not nested:
current = parse_indented_config(
config, leading_spaces, current_indent, True
)
_attach_data_to_path(parsed, last, current, nested)
else:
config.insert(0, line)
break
return parsed
|
[
"This",
"methid",
"basically",
"reads",
"a",
"configuration",
"that",
"conforms",
"to",
"a",
"very",
"poor",
"industry",
"standard",
"and",
"returns",
"a",
"nested",
"structure",
"that",
"behaves",
"like",
"a",
"dict",
".",
"For",
"example",
":",
"{",
"enable",
"password",
"whatever",
":",
"{}",
"interface",
"GigabitEthernet1",
":",
"{",
"description",
"bleh",
":",
"{}",
"fake",
"nested",
":",
"{",
"nested",
"nested",
"configuration",
":",
"{}",
"}",
"switchport",
"mode",
"trunk",
":",
"{}",
"}",
"interface",
"GigabitEthernet2",
":",
"{",
"no",
"ip",
"address",
":",
"{}",
"}",
"interface",
"GigabitEthernet3",
":",
"{",
"negotiation",
"auto",
":",
"{}",
"no",
"ip",
"address",
":",
"{}",
"shutdown",
":",
"{}",
"}",
"interface",
"Loopback0",
":",
"{",
"description",
"blah",
":",
"{}",
"}}"
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/parsers/text_tree.py#L39-L91
|
[
"def",
"parse_indented_config",
"(",
"config",
",",
"current_indent",
"=",
"0",
",",
"previous_indent",
"=",
"0",
",",
"nested",
"=",
"False",
")",
":",
"parsed",
"=",
"OrderedDict",
"(",
")",
"while",
"True",
":",
"if",
"not",
"config",
":",
"break",
"line",
"=",
"config",
".",
"pop",
"(",
"0",
")",
"if",
"line",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"\"!\"",
")",
":",
"continue",
"last",
"=",
"line",
".",
"lstrip",
"(",
")",
"leading_spaces",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"last",
")",
"# print(\"current_indent:{}, previous:{}, leading:{} - {}\".format(",
"# current_indent, previous_indent, leading_spaces, line))",
"if",
"leading_spaces",
">",
"current_indent",
":",
"current",
"=",
"parse_indented_config",
"(",
"config",
",",
"leading_spaces",
",",
"current_indent",
",",
"True",
")",
"_attach_data_to_path",
"(",
"parsed",
",",
"last",
",",
"current",
",",
"nested",
")",
"elif",
"leading_spaces",
"<",
"current_indent",
":",
"config",
".",
"insert",
"(",
"0",
",",
"line",
")",
"break",
"else",
":",
"if",
"not",
"nested",
":",
"current",
"=",
"parse_indented_config",
"(",
"config",
",",
"leading_spaces",
",",
"current_indent",
",",
"True",
")",
"_attach_data_to_path",
"(",
"parsed",
",",
"last",
",",
"current",
",",
"nested",
")",
"else",
":",
"config",
".",
"insert",
"(",
"0",
",",
"line",
")",
"break",
"return",
"parsed"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
prefix_to_addrmask
|
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.168.0.1 255.255.255.0"
>>> "{{ '192.168.0.1/24|prefix_to_addrmask('/') }}" -> "192.168.0.1/255.255.255.0"
|
napalm_yang/jinja_filters/ip_filters.py
|
def prefix_to_addrmask(value, sep=" "):
"""
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.168.0.1 255.255.255.0"
>>> "{{ '192.168.0.1/24|prefix_to_addrmask('/') }}" -> "192.168.0.1/255.255.255.0"
"""
prefix = netaddr.IPNetwork(value)
return "{}{}{}".format(prefix.ip, sep, prefix.netmask)
|
def prefix_to_addrmask(value, sep=" "):
"""
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.168.0.1 255.255.255.0"
>>> "{{ '192.168.0.1/24|prefix_to_addrmask('/') }}" -> "192.168.0.1/255.255.255.0"
"""
prefix = netaddr.IPNetwork(value)
return "{}{}{}".format(prefix.ip, sep, prefix.netmask)
|
[
"Converts",
"a",
"CIDR",
"formatted",
"prefix",
"into",
"an",
"address",
"netmask",
"representation",
".",
"Argument",
"sep",
"specifies",
"the",
"separator",
"between",
"the",
"address",
"and",
"netmask",
"parts",
".",
"By",
"default",
"it",
"s",
"a",
"single",
"space",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/jinja_filters/ip_filters.py#L73-L84
|
[
"def",
"prefix_to_addrmask",
"(",
"value",
",",
"sep",
"=",
"\" \"",
")",
":",
"prefix",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"value",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"prefix",
".",
"ip",
",",
"sep",
",",
"prefix",
".",
"netmask",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
state._set_keepalive_interval
|
Setter method for keepalive_interval, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/keepalive_interval (decimal64)
If this variable is read-only (config: false) in the
source YANG file, then _set_keepalive_interval is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_keepalive_interval() directly.
YANG Description: Time interval in seconds between transmission of keepalive
messages to the neighbor. Typically set to 1/3 the
hold-time.
|
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/__init__.py
|
def _set_keepalive_interval(self, v, load=False):
"""
Setter method for keepalive_interval, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/keepalive_interval (decimal64)
If this variable is read-only (config: false) in the
source YANG file, then _set_keepalive_interval is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_keepalive_interval() directly.
YANG Description: Time interval in seconds between transmission of keepalive
messages to the neighbor. Typically set to 1/3 the
hold-time.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedPrecisionDecimalType(precision=2),
default=Decimal(30),
is_leaf=True,
yang_name="keepalive-interval",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="decimal64",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """keepalive_interval must be of a type compatible with decimal64""",
"defined-type": "decimal64",
"generated-type": """YANGDynClass(base=RestrictedPrecisionDecimalType(precision=2), default=Decimal(30), is_leaf=True, yang_name="keepalive-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='decimal64', is_config=False)""",
}
)
self.__keepalive_interval = t
if hasattr(self, "_set"):
self._set()
|
def _set_keepalive_interval(self, v, load=False):
"""
Setter method for keepalive_interval, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/keepalive_interval (decimal64)
If this variable is read-only (config: false) in the
source YANG file, then _set_keepalive_interval is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_keepalive_interval() directly.
YANG Description: Time interval in seconds between transmission of keepalive
messages to the neighbor. Typically set to 1/3 the
hold-time.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedPrecisionDecimalType(precision=2),
default=Decimal(30),
is_leaf=True,
yang_name="keepalive-interval",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="decimal64",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """keepalive_interval must be of a type compatible with decimal64""",
"defined-type": "decimal64",
"generated-type": """YANGDynClass(base=RestrictedPrecisionDecimalType(precision=2), default=Decimal(30), is_leaf=True, yang_name="keepalive-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='decimal64', is_config=False)""",
}
)
self.__keepalive_interval = t
if hasattr(self, "_set"):
self._set()
|
[
"Setter",
"method",
"for",
"keepalive_interval",
"mapped",
"from",
"YANG",
"variable",
"/",
"network_instances",
"/",
"network_instance",
"/",
"protocols",
"/",
"protocol",
"/",
"bgp",
"/",
"peer_groups",
"/",
"peer_group",
"/",
"timers",
"/",
"state",
"/",
"keepalive_interval",
"(",
"decimal64",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
"_set_keepalive_interval",
"is",
"considered",
"as",
"a",
"private",
"method",
".",
"Backends",
"looking",
"to",
"populate",
"this",
"variable",
"should",
"do",
"so",
"via",
"calling",
"thisObj",
".",
"_set_keepalive_interval",
"()",
"directly",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/__init__.py#L295-L336
|
[
"def",
"_set_keepalive_interval",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=",
"RestrictedPrecisionDecimalType",
"(",
"precision",
"=",
"2",
")",
",",
"default",
"=",
"Decimal",
"(",
"30",
")",
",",
"is_leaf",
"=",
"True",
",",
"yang_name",
"=",
"\"keepalive-interval\"",
",",
"parent",
"=",
"self",
",",
"path_helper",
"=",
"self",
".",
"_path_helper",
",",
"extmethods",
"=",
"self",
".",
"_extmethods",
",",
"register_paths",
"=",
"True",
",",
"namespace",
"=",
"\"http://openconfig.net/yang/network-instance\"",
",",
"defining_module",
"=",
"\"openconfig-network-instance\"",
",",
"yang_type",
"=",
"\"decimal64\"",
",",
"is_config",
"=",
"False",
",",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"{",
"\"error-string\"",
":",
"\"\"\"keepalive_interval must be of a type compatible with decimal64\"\"\"",
",",
"\"defined-type\"",
":",
"\"decimal64\"",
",",
"\"generated-type\"",
":",
"\"\"\"YANGDynClass(base=RestrictedPrecisionDecimalType(precision=2), default=Decimal(30), is_leaf=True, yang_name=\"keepalive-interval\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='decimal64', is_config=False)\"\"\"",
",",
"}",
")",
"self",
".",
"__keepalive_interval",
"=",
"t",
"if",
"hasattr",
"(",
"self",
",",
"\"_set\"",
")",
":",
"self",
".",
"_set",
"(",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
check_empty
|
Decorator that checks if a value passed to a Jinja filter evaluates to false
and returns an empty string. Otherwise calls the original Jinja filter.
Example usage:
@check_empty
def my_jinja_filter(value, arg1):
|
napalm_yang/jinja_filters/helpers.py
|
def check_empty(default=""):
"""
Decorator that checks if a value passed to a Jinja filter evaluates to false
and returns an empty string. Otherwise calls the original Jinja filter.
Example usage:
@check_empty
def my_jinja_filter(value, arg1):
"""
def real_decorator(func):
@wraps(func)
def wrapper(value, *args, **kwargs):
if not value:
return default
else:
return func(value, *args, **kwargs)
return wrapper
return real_decorator
|
def check_empty(default=""):
"""
Decorator that checks if a value passed to a Jinja filter evaluates to false
and returns an empty string. Otherwise calls the original Jinja filter.
Example usage:
@check_empty
def my_jinja_filter(value, arg1):
"""
def real_decorator(func):
@wraps(func)
def wrapper(value, *args, **kwargs):
if not value:
return default
else:
return func(value, *args, **kwargs)
return wrapper
return real_decorator
|
[
"Decorator",
"that",
"checks",
"if",
"a",
"value",
"passed",
"to",
"a",
"Jinja",
"filter",
"evaluates",
"to",
"false",
"and",
"returns",
"an",
"empty",
"string",
".",
"Otherwise",
"calls",
"the",
"original",
"Jinja",
"filter",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/jinja_filters/helpers.py#L4-L25
|
[
"def",
"check_empty",
"(",
"default",
"=",
"\"\"",
")",
":",
"def",
"real_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
":",
"return",
"default",
"else",
":",
"return",
"func",
"(",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"real_decorator"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.add_model
|
Add a model.
The model will be asssigned to a class attribute with the YANG name of the model.
Args:
model (PybindBase): Model to add.
force (bool): If not set, verify the model is in SUPPORTED_MODELS
Examples:
>>> import napalm_yang
>>> config = napalm_yang.base.Root()
>>> config.add_model(napalm_yang.models.openconfig_interfaces)
>>> config.interfaces
<pyangbind.lib.yangtypes.YANGBaseClass object at 0x10bef6680>
|
napalm_yang/base.py
|
def add_model(self, model, force=False):
"""
Add a model.
The model will be asssigned to a class attribute with the YANG name of the model.
Args:
model (PybindBase): Model to add.
force (bool): If not set, verify the model is in SUPPORTED_MODELS
Examples:
>>> import napalm_yang
>>> config = napalm_yang.base.Root()
>>> config.add_model(napalm_yang.models.openconfig_interfaces)
>>> config.interfaces
<pyangbind.lib.yangtypes.YANGBaseClass object at 0x10bef6680>
"""
if isinstance(model, str):
self._load_model(model)
return
try:
model = model()
except Exception:
pass
if model._yang_name not in [a[0] for a in SUPPORTED_MODELS] and not force:
raise ValueError(
"Only models in SUPPORTED_MODELS can be added without `force=True`"
)
for k, v in model:
self._elements[k] = v
setattr(self, k, v)
|
def add_model(self, model, force=False):
"""
Add a model.
The model will be asssigned to a class attribute with the YANG name of the model.
Args:
model (PybindBase): Model to add.
force (bool): If not set, verify the model is in SUPPORTED_MODELS
Examples:
>>> import napalm_yang
>>> config = napalm_yang.base.Root()
>>> config.add_model(napalm_yang.models.openconfig_interfaces)
>>> config.interfaces
<pyangbind.lib.yangtypes.YANGBaseClass object at 0x10bef6680>
"""
if isinstance(model, str):
self._load_model(model)
return
try:
model = model()
except Exception:
pass
if model._yang_name not in [a[0] for a in SUPPORTED_MODELS] and not force:
raise ValueError(
"Only models in SUPPORTED_MODELS can be added without `force=True`"
)
for k, v in model:
self._elements[k] = v
setattr(self, k, v)
|
[
"Add",
"a",
"model",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L37-L71
|
[
"def",
"add_model",
"(",
"self",
",",
"model",
",",
"force",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"str",
")",
":",
"self",
".",
"_load_model",
"(",
"model",
")",
"return",
"try",
":",
"model",
"=",
"model",
"(",
")",
"except",
"Exception",
":",
"pass",
"if",
"model",
".",
"_yang_name",
"not",
"in",
"[",
"a",
"[",
"0",
"]",
"for",
"a",
"in",
"SUPPORTED_MODELS",
"]",
"and",
"not",
"force",
":",
"raise",
"ValueError",
"(",
"\"Only models in SUPPORTED_MODELS can be added without `force=True`\"",
")",
"for",
"k",
",",
"v",
"in",
"model",
":",
"self",
".",
"_elements",
"[",
"k",
"]",
"=",
"v",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.get
|
Returns a dictionary with the values of the model. Note that the values
of the leafs are YANG classes.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.get(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
|
napalm_yang/base.py
|
def get(self, filter=False):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are YANG classes.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.get(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
"""
result = {}
for k, v in self.elements().items():
intermediate = v.get(filter=filter)
if intermediate:
result[k] = intermediate
return result
|
def get(self, filter=False):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are YANG classes.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.get(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
"""
result = {}
for k, v in self.elements().items():
intermediate = v.get(filter=filter)
if intermediate:
result[k] = intermediate
return result
|
[
"Returns",
"a",
"dictionary",
"with",
"the",
"values",
"of",
"the",
"model",
".",
"Note",
"that",
"the",
"values",
"of",
"the",
"leafs",
"are",
"YANG",
"classes",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L73-L116
|
[
"def",
"get",
"(",
"self",
",",
"filter",
"=",
"False",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"elements",
"(",
")",
".",
"items",
"(",
")",
":",
"intermediate",
"=",
"v",
".",
"get",
"(",
"filter",
"=",
"filter",
")",
"if",
"intermediate",
":",
"result",
"[",
"k",
"]",
"=",
"intermediate",
"return",
"result"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.load_dict
|
Load a dictionary into the model.
Args:
data(dict): Dictionary to load
overwrite(bool): Whether the data present in the model should be overwritten by the
data in the dict or not.
auto_load_model(bool): If set to true models will be loaded as they are needed
Examples:
>>> vlans_dict = {
>>> "vlans": { "vlan": { 100: {
>>> "config": {
>>> "vlan_id": 100, "name": "production"}},
>>> 200: {
>>> "config": {
>>> "vlan_id": 200, "name": "dev"}}}}}
>>> config.load_dict(vlans_dict)
>>> print(config.vlans.vlan.keys())
... [200, 100]
>>> print(100, config.vlans.vlan[100].config.name)
... (100, u'production')
>>> print(200, config.vlans.vlan[200].config.name)
... (200, u'dev')
|
napalm_yang/base.py
|
def load_dict(self, data, overwrite=False, auto_load_model=True):
"""
Load a dictionary into the model.
Args:
data(dict): Dictionary to load
overwrite(bool): Whether the data present in the model should be overwritten by the
data in the dict or not.
auto_load_model(bool): If set to true models will be loaded as they are needed
Examples:
>>> vlans_dict = {
>>> "vlans": { "vlan": { 100: {
>>> "config": {
>>> "vlan_id": 100, "name": "production"}},
>>> 200: {
>>> "config": {
>>> "vlan_id": 200, "name": "dev"}}}}}
>>> config.load_dict(vlans_dict)
>>> print(config.vlans.vlan.keys())
... [200, 100]
>>> print(100, config.vlans.vlan[100].config.name)
... (100, u'production')
>>> print(200, config.vlans.vlan[200].config.name)
... (200, u'dev')
"""
for k, v in data.items():
if k not in self._elements.keys() and not auto_load_model:
raise AttributeError("Model {} is not loaded".format(k))
elif k not in self._elements.keys() and auto_load_model:
self._load_model(k)
attr = getattr(self, k)
_load_dict(attr, v)
|
def load_dict(self, data, overwrite=False, auto_load_model=True):
"""
Load a dictionary into the model.
Args:
data(dict): Dictionary to load
overwrite(bool): Whether the data present in the model should be overwritten by the
data in the dict or not.
auto_load_model(bool): If set to true models will be loaded as they are needed
Examples:
>>> vlans_dict = {
>>> "vlans": { "vlan": { 100: {
>>> "config": {
>>> "vlan_id": 100, "name": "production"}},
>>> 200: {
>>> "config": {
>>> "vlan_id": 200, "name": "dev"}}}}}
>>> config.load_dict(vlans_dict)
>>> print(config.vlans.vlan.keys())
... [200, 100]
>>> print(100, config.vlans.vlan[100].config.name)
... (100, u'production')
>>> print(200, config.vlans.vlan[200].config.name)
... (200, u'dev')
"""
for k, v in data.items():
if k not in self._elements.keys() and not auto_load_model:
raise AttributeError("Model {} is not loaded".format(k))
elif k not in self._elements.keys() and auto_load_model:
self._load_model(k)
attr = getattr(self, k)
_load_dict(attr, v)
|
[
"Load",
"a",
"dictionary",
"into",
"the",
"model",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L131-L166
|
[
"def",
"load_dict",
"(",
"self",
",",
"data",
",",
"overwrite",
"=",
"False",
",",
"auto_load_model",
"=",
"True",
")",
":",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"_elements",
".",
"keys",
"(",
")",
"and",
"not",
"auto_load_model",
":",
"raise",
"AttributeError",
"(",
"\"Model {} is not loaded\"",
".",
"format",
"(",
"k",
")",
")",
"elif",
"k",
"not",
"in",
"self",
".",
"_elements",
".",
"keys",
"(",
")",
"and",
"auto_load_model",
":",
"self",
".",
"_load_model",
"(",
"k",
")",
"attr",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"_load_dict",
"(",
"attr",
",",
"v",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.to_dict
|
Returns a dictionary with the values of the model. Note that the values
of the leafs are evaluated to python types.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.to_dict(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
|
napalm_yang/base.py
|
def to_dict(self, filter=True):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are evaluated to python types.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.to_dict(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
"""
result = {}
for k, v in self:
r = _to_dict(v, filter)
if r:
result[k] = r
return result
|
def to_dict(self, filter=True):
"""
Returns a dictionary with the values of the model. Note that the values
of the leafs are evaluated to python types.
Args:
filter (bool): If set to ``True``, show only values that have been set.
Returns:
dict: A dictionary with the values of the model.
Example:
>>> pretty_print(config.to_dict(filter=True))
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "et1": {
>>> "config": {
>>> "description": "My description",
>>> "mtu": 1500
>>> },
>>> "name": "et1"
>>> },
>>> "et2": {
>>> "config": {
>>> "description": "Another description",
>>> "mtu": 9000
>>> },
>>> "name": "et2"
>>> }
>>> }
>>> }
>>> }
"""
result = {}
for k, v in self:
r = _to_dict(v, filter)
if r:
result[k] = r
return result
|
[
"Returns",
"a",
"dictionary",
"with",
"the",
"values",
"of",
"the",
"model",
".",
"Note",
"that",
"the",
"values",
"of",
"the",
"leafs",
"are",
"evaluated",
"to",
"python",
"types",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L168-L209
|
[
"def",
"to_dict",
"(",
"self",
",",
"filter",
"=",
"True",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
":",
"r",
"=",
"_to_dict",
"(",
"v",
",",
"filter",
")",
"if",
"r",
":",
"result",
"[",
"k",
"]",
"=",
"r",
"return",
"result"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.parse_config
|
Parse native configuration and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list of strings): Native configuration to parse.
Examples:
>>> # Load from device
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(device=d)
>>> # Load from file
>>> with open("junos.config", "r") as f:
>>> config = f.read()
>>>
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(native=[config], profile="junos")
|
napalm_yang/base.py
|
def parse_config(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native configuration and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list of strings): Native configuration to parse.
Examples:
>>> # Load from device
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(device=d)
>>> # Load from file
>>> with open("junos.config", "r") as f:
>>> config = f.read()
>>>
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(native=[config], profile="junos")
"""
if attrs is None:
attrs = self.elements().values()
for v in attrs:
parser = Parser(
v, device=device, profile=profile, native=native, is_config=True
)
parser.parse()
|
def parse_config(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native configuration and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list of strings): Native configuration to parse.
Examples:
>>> # Load from device
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(device=d)
>>> # Load from file
>>> with open("junos.config", "r") as f:
>>> config = f.read()
>>>
>>> running_config = napalm_yang.base.Root()
>>> running_config.add_model(napalm_yang.models.openconfig_interfaces)
>>> running_config.parse_config(native=[config], profile="junos")
"""
if attrs is None:
attrs = self.elements().values()
for v in attrs:
parser = Parser(
v, device=device, profile=profile, native=native, is_config=True
)
parser.parse()
|
[
"Parse",
"native",
"configuration",
"and",
"load",
"it",
"into",
"the",
"corresponding",
"models",
".",
"Only",
"models",
"that",
"have",
"been",
"added",
"to",
"the",
"root",
"object",
"will",
"be",
"parsed",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L211-L247
|
[
"def",
"parse_config",
"(",
"self",
",",
"device",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"native",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"self",
".",
"elements",
"(",
")",
".",
"values",
"(",
")",
"for",
"v",
"in",
"attrs",
":",
"parser",
"=",
"Parser",
"(",
"v",
",",
"device",
"=",
"device",
",",
"profile",
"=",
"profile",
",",
"native",
"=",
"native",
",",
"is_config",
"=",
"True",
")",
"parser",
".",
"parse",
"(",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.parse_state
|
Parse native state and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list string): Native output to parse.
Examples:
>>> # Load from device
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(device=d)
>>> # Load from file
>>> with open("junos.state", "r") as f:
>>> state_data = f.read()
>>>
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(native=[state_data], profile="junos")
|
napalm_yang/base.py
|
def parse_state(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native state and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list string): Native output to parse.
Examples:
>>> # Load from device
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(device=d)
>>> # Load from file
>>> with open("junos.state", "r") as f:
>>> state_data = f.read()
>>>
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(native=[state_data], profile="junos")
"""
if attrs is None:
attrs = self.elements().values()
for v in attrs:
parser = Parser(
v, device=device, profile=profile, native=native, is_config=False
)
parser.parse()
|
def parse_state(self, device=None, profile=None, native=None, attrs=None):
"""
Parse native state and load it into the corresponding models. Only models
that have been added to the root object will be parsed.
If ``native`` is passed to the method that's what we will parse, otherwise, we will use the
``device`` to retrieve it.
Args:
device (NetworkDriver): Device to load the configuration from.
profile (list): Profiles that the device supports. If no ``profile`` is passed it will
be read from ``device``.
native (list string): Native output to parse.
Examples:
>>> # Load from device
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(device=d)
>>> # Load from file
>>> with open("junos.state", "r") as f:
>>> state_data = f.read()
>>>
>>> state = napalm_yang.base.Root()
>>> state.add_model(napalm_yang.models.openconfig_interfaces)
>>> state.parse_config(native=[state_data], profile="junos")
"""
if attrs is None:
attrs = self.elements().values()
for v in attrs:
parser = Parser(
v, device=device, profile=profile, native=native, is_config=False
)
parser.parse()
|
[
"Parse",
"native",
"state",
"and",
"load",
"it",
"into",
"the",
"corresponding",
"models",
".",
"Only",
"models",
"that",
"have",
"been",
"added",
"to",
"the",
"root",
"object",
"will",
"be",
"parsed",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L249-L285
|
[
"def",
"parse_state",
"(",
"self",
",",
"device",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"native",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"self",
".",
"elements",
"(",
")",
".",
"values",
"(",
")",
"for",
"v",
"in",
"attrs",
":",
"parser",
"=",
"Parser",
"(",
"v",
",",
"device",
"=",
"device",
",",
"profile",
"=",
"profile",
",",
"native",
"=",
"native",
",",
"is_config",
"=",
"False",
")",
"parser",
".",
"parse",
"(",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Root.translate_config
|
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`` unless ``self`` specifies a new one. Elements that exist only
in ``self`` will be translated as they are and elements present only in ``merge``
will be removed.
* **Replace** - All the elements in ``replace`` will either be removed or replaced by
elements in ``self``.
You can specify one of ``merge``, ``replace`` or none of them. If none of them are set we
will just translate configuration.
Args:
profile (list): Which profiles to use.
merge (Root): Object we want to merge with.
replace (Root): Object we want to replace.
|
napalm_yang/base.py
|
def translate_config(self, profile, merge=None, replace=None):
"""
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`` unless ``self`` specifies a new one. Elements that exist only
in ``self`` will be translated as they are and elements present only in ``merge``
will be removed.
* **Replace** - All the elements in ``replace`` will either be removed or replaced by
elements in ``self``.
You can specify one of ``merge``, ``replace`` or none of them. If none of them are set we
will just translate configuration.
Args:
profile (list): Which profiles to use.
merge (Root): Object we want to merge with.
replace (Root): Object we want to replace.
"""
result = []
for k, v in self:
other_merge = getattr(merge, k) if merge else None
other_replace = getattr(replace, k) if replace else None
translator = Translator(
v, profile, merge=other_merge, replace=other_replace
)
result.append(translator.translate())
return "\n".join(result)
|
def translate_config(self, profile, merge=None, replace=None):
"""
Translate the object to native configuration.
In this context, merge and replace means the following:
* **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the
values in ``merge`` unless ``self`` specifies a new one. Elements that exist only
in ``self`` will be translated as they are and elements present only in ``merge``
will be removed.
* **Replace** - All the elements in ``replace`` will either be removed or replaced by
elements in ``self``.
You can specify one of ``merge``, ``replace`` or none of them. If none of them are set we
will just translate configuration.
Args:
profile (list): Which profiles to use.
merge (Root): Object we want to merge with.
replace (Root): Object we want to replace.
"""
result = []
for k, v in self:
other_merge = getattr(merge, k) if merge else None
other_replace = getattr(replace, k) if replace else None
translator = Translator(
v, profile, merge=other_merge, replace=other_replace
)
result.append(translator.translate())
return "\n".join(result)
|
[
"Translate",
"the",
"object",
"to",
"native",
"configuration",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/base.py#L287-L317
|
[
"def",
"translate_config",
"(",
"self",
",",
"profile",
",",
"merge",
"=",
"None",
",",
"replace",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
":",
"other_merge",
"=",
"getattr",
"(",
"merge",
",",
"k",
")",
"if",
"merge",
"else",
"None",
"other_replace",
"=",
"getattr",
"(",
"replace",
",",
"k",
")",
"if",
"replace",
"else",
"None",
"translator",
"=",
"Translator",
"(",
"v",
",",
"profile",
",",
"merge",
"=",
"other_merge",
",",
"replace",
"=",
"other_replace",
")",
"result",
".",
"append",
"(",
"translator",
".",
"translate",
"(",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"result",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
load_filters
|
Loads and returns all filters.
|
napalm_yang/jinja_filters/__init__.py
|
def load_filters():
"""
Loads and returns all filters.
"""
all_filters = {}
for m in JINJA_FILTERS:
if hasattr(m, "filters"):
all_filters.update(m.filters())
return all_filters
|
def load_filters():
"""
Loads and returns all filters.
"""
all_filters = {}
for m in JINJA_FILTERS:
if hasattr(m, "filters"):
all_filters.update(m.filters())
return all_filters
|
[
"Loads",
"and",
"returns",
"all",
"filters",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/jinja_filters/__init__.py#L9-L17
|
[
"def",
"load_filters",
"(",
")",
":",
"all_filters",
"=",
"{",
"}",
"for",
"m",
"in",
"JINJA_FILTERS",
":",
"if",
"hasattr",
"(",
"m",
",",
"\"filters\"",
")",
":",
"all_filters",
".",
"update",
"(",
"m",
".",
"filters",
"(",
")",
")",
"return",
"all_filters"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
XMLParser._parse_list_nested_recursive
|
This helps parsing shit like:
<protocols>
<bgp>
<group>
<name>my_peers</name>
<neighbor>
<name>192.168.100.2</name>
<description>adsasd</description>
<peer-as>65100</peer-as>
</neighbor>
<neighbor>
<name>192.168.100.3</name>
<peer-as>65100</peer-as>
</neighbor>
</group>
<group>
<name>my_other_peers</name>
<neighbor>
<name>172.20.0.1</name>
<peer-as>65200</peer-as>
</neighbor>
</group>
</bgp>
</protocols>
|
napalm_yang/parsers/xml_deprecated.py
|
def _parse_list_nested_recursive(
cls, data, path, iterators, list_vars, cur_vars=None
):
"""
This helps parsing shit like:
<protocols>
<bgp>
<group>
<name>my_peers</name>
<neighbor>
<name>192.168.100.2</name>
<description>adsasd</description>
<peer-as>65100</peer-as>
</neighbor>
<neighbor>
<name>192.168.100.3</name>
<peer-as>65100</peer-as>
</neighbor>
</group>
<group>
<name>my_other_peers</name>
<neighbor>
<name>172.20.0.1</name>
<peer-as>65200</peer-as>
</neighbor>
</group>
</bgp>
</protocols>
"""
cur_vars = dict(cur_vars) if cur_vars else {}
if path:
p = path[0]
path = path[1:]
else:
for _ in data:
list_vars.append(cur_vars)
iterators.append(data)
return data
if p.startswith("?"):
for x in data:
key, var_path = p.split(".")
cur_vars.update({key.lstrip("?"): x.xpath(var_path)[0].text})
cls._parse_list_nested_recursive(
x, path, iterators, list_vars, cur_vars
)
else:
x = data.xpath(p)
cls._parse_list_nested_recursive(x, path, iterators, list_vars, cur_vars)
|
def _parse_list_nested_recursive(
cls, data, path, iterators, list_vars, cur_vars=None
):
"""
This helps parsing shit like:
<protocols>
<bgp>
<group>
<name>my_peers</name>
<neighbor>
<name>192.168.100.2</name>
<description>adsasd</description>
<peer-as>65100</peer-as>
</neighbor>
<neighbor>
<name>192.168.100.3</name>
<peer-as>65100</peer-as>
</neighbor>
</group>
<group>
<name>my_other_peers</name>
<neighbor>
<name>172.20.0.1</name>
<peer-as>65200</peer-as>
</neighbor>
</group>
</bgp>
</protocols>
"""
cur_vars = dict(cur_vars) if cur_vars else {}
if path:
p = path[0]
path = path[1:]
else:
for _ in data:
list_vars.append(cur_vars)
iterators.append(data)
return data
if p.startswith("?"):
for x in data:
key, var_path = p.split(".")
cur_vars.update({key.lstrip("?"): x.xpath(var_path)[0].text})
cls._parse_list_nested_recursive(
x, path, iterators, list_vars, cur_vars
)
else:
x = data.xpath(p)
cls._parse_list_nested_recursive(x, path, iterators, list_vars, cur_vars)
|
[
"This",
"helps",
"parsing",
"shit",
"like",
":"
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/parsers/xml_deprecated.py#L41-L91
|
[
"def",
"_parse_list_nested_recursive",
"(",
"cls",
",",
"data",
",",
"path",
",",
"iterators",
",",
"list_vars",
",",
"cur_vars",
"=",
"None",
")",
":",
"cur_vars",
"=",
"dict",
"(",
"cur_vars",
")",
"if",
"cur_vars",
"else",
"{",
"}",
"if",
"path",
":",
"p",
"=",
"path",
"[",
"0",
"]",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"else",
":",
"for",
"_",
"in",
"data",
":",
"list_vars",
".",
"append",
"(",
"cur_vars",
")",
"iterators",
".",
"append",
"(",
"data",
")",
"return",
"data",
"if",
"p",
".",
"startswith",
"(",
"\"?\"",
")",
":",
"for",
"x",
"in",
"data",
":",
"key",
",",
"var_path",
"=",
"p",
".",
"split",
"(",
"\".\"",
")",
"cur_vars",
".",
"update",
"(",
"{",
"key",
".",
"lstrip",
"(",
"\"?\"",
")",
":",
"x",
".",
"xpath",
"(",
"var_path",
")",
"[",
"0",
"]",
".",
"text",
"}",
")",
"cls",
".",
"_parse_list_nested_recursive",
"(",
"x",
",",
"path",
",",
"iterators",
",",
"list_vars",
",",
"cur_vars",
")",
"else",
":",
"x",
"=",
"data",
".",
"xpath",
"(",
"p",
")",
"cls",
".",
"_parse_list_nested_recursive",
"(",
"x",
",",
"path",
",",
"iterators",
",",
"list_vars",
",",
"cur_vars",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
_flatten_dictionary
|
This method tries to use the path `?my_field` to convert:
a:
aa: 1
ab: 2
b:
ba: 3
ba: 4
into:
- my_field: a
aa: 1
ab: 2
- my_field: b
ba: 3
ba: 4
|
napalm_yang/parsers/base.py
|
def _flatten_dictionary(obj, path, key_name):
"""
This method tries to use the path `?my_field` to convert:
a:
aa: 1
ab: 2
b:
ba: 3
ba: 4
into:
- my_field: a
aa: 1
ab: 2
- my_field: b
ba: 3
ba: 4
"""
result = []
if ">" in key_name:
key_name, group_key = key_name.split(">")
else:
group_key = None
for k, v in obj.items():
if path:
if k == path[0]:
path.pop(0)
if k.startswith("#"):
continue
r = _resolve_path(v, list(path))
if isinstance(r, dict):
# You can either have a dict here, which means your path is like ?a.b
# or a list, which means you have a path like ?a.?b
r = [r]
for e in r:
if group_key:
e[group_key] = {kk: vv for kk, vv in v.items() if kk not in path}
e[key_name] = k
result.append(e)
return result
|
def _flatten_dictionary(obj, path, key_name):
"""
This method tries to use the path `?my_field` to convert:
a:
aa: 1
ab: 2
b:
ba: 3
ba: 4
into:
- my_field: a
aa: 1
ab: 2
- my_field: b
ba: 3
ba: 4
"""
result = []
if ">" in key_name:
key_name, group_key = key_name.split(">")
else:
group_key = None
for k, v in obj.items():
if path:
if k == path[0]:
path.pop(0)
if k.startswith("#"):
continue
r = _resolve_path(v, list(path))
if isinstance(r, dict):
# You can either have a dict here, which means your path is like ?a.b
# or a list, which means you have a path like ?a.?b
r = [r]
for e in r:
if group_key:
e[group_key] = {kk: vv for kk, vv in v.items() if kk not in path}
e[key_name] = k
result.append(e)
return result
|
[
"This",
"method",
"tries",
"to",
"use",
"the",
"path",
"?my_field",
"to",
"convert",
":"
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/parsers/base.py#L7-L51
|
[
"def",
"_flatten_dictionary",
"(",
"obj",
",",
"path",
",",
"key_name",
")",
":",
"result",
"=",
"[",
"]",
"if",
"\">\"",
"in",
"key_name",
":",
"key_name",
",",
"group_key",
"=",
"key_name",
".",
"split",
"(",
"\">\"",
")",
"else",
":",
"group_key",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
":",
"if",
"path",
":",
"if",
"k",
"==",
"path",
"[",
"0",
"]",
":",
"path",
".",
"pop",
"(",
"0",
")",
"if",
"k",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"continue",
"r",
"=",
"_resolve_path",
"(",
"v",
",",
"list",
"(",
"path",
")",
")",
"if",
"isinstance",
"(",
"r",
",",
"dict",
")",
":",
"# You can either have a dict here, which means your path is like ?a.b",
"# or a list, which means you have a path like ?a.?b",
"r",
"=",
"[",
"r",
"]",
"for",
"e",
"in",
"r",
":",
"if",
"group_key",
":",
"e",
"[",
"group_key",
"]",
"=",
"{",
"kk",
":",
"vv",
"for",
"kk",
",",
"vv",
"in",
"v",
".",
"items",
"(",
")",
"if",
"kk",
"not",
"in",
"path",
"}",
"e",
"[",
"key_name",
"]",
"=",
"k",
"result",
".",
"append",
"(",
"e",
")",
"return",
"result"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
state._set_trunk_vlans
|
Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_vlans is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_trunk_vlans() directly.
YANG Description: Specify VLANs, or ranges thereof, that the interface may
carry when in trunk mode. If not specified, all VLANs are
allowed on the interface. Ranges are specified in the form
x..y, where x<y - ranges are assumed to be inclusive (such
that the VLAN range is x <= range <= y.
|
napalm_yang/models/openconfig/interfaces/interface/aggregation/switched_vlan/state/__init__.py
|
def _set_trunk_vlans(self, v, load=False):
"""
Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_vlans is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_trunk_vlans() directly.
YANG Description: Specify VLANs, or ranges thereof, that the interface may
carry when in trunk mode. If not specified, all VLANs are
allowed on the interface. Ranges are specified in the form
x..y, where x<y - ranges are assumed to be inclusive (such
that the VLAN range is x <= range <= y.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=TypedListType(
allowed_type=[
RestrictedClassType(
base_type=RestrictedClassType(
base_type=int,
restriction_dict={"range": ["0..65535"]},
int_size=16,
),
restriction_dict={"range": ["1..4094"]},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])"
},
),
]
),
is_leaf=False,
yang_name="trunk-vlans",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/vlan",
defining_module="openconfig-vlan",
yang_type="union",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """trunk_vlans must be of a type compatible with union""",
"defined-type": "openconfig-vlan:union",
"generated-type": """YANGDynClass(base=TypedListType(allowed_type=[RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), restriction_dict={'range': ['1..4094']}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),]), is_leaf=False, yang_name="trunk-vlans", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='union', is_config=False)""",
}
)
self.__trunk_vlans = t
if hasattr(self, "_set"):
self._set()
|
def _set_trunk_vlans(self, v, load=False):
"""
Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_vlans is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_trunk_vlans() directly.
YANG Description: Specify VLANs, or ranges thereof, that the interface may
carry when in trunk mode. If not specified, all VLANs are
allowed on the interface. Ranges are specified in the form
x..y, where x<y - ranges are assumed to be inclusive (such
that the VLAN range is x <= range <= y.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=TypedListType(
allowed_type=[
RestrictedClassType(
base_type=RestrictedClassType(
base_type=int,
restriction_dict={"range": ["0..65535"]},
int_size=16,
),
restriction_dict={"range": ["1..4094"]},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)"
},
),
RestrictedClassType(
base_type=six.text_type,
restriction_dict={
"pattern": "(\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])"
},
),
]
),
is_leaf=False,
yang_name="trunk-vlans",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/vlan",
defining_module="openconfig-vlan",
yang_type="union",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """trunk_vlans must be of a type compatible with union""",
"defined-type": "openconfig-vlan:union",
"generated-type": """YANGDynClass(base=TypedListType(allowed_type=[RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), restriction_dict={'range': ['1..4094']}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\.\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),]), is_leaf=False, yang_name="trunk-vlans", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='union', is_config=False)""",
}
)
self.__trunk_vlans = t
if hasattr(self, "_set"):
self._set()
|
[
"Setter",
"method",
"for",
"trunk_vlans",
"mapped",
"from",
"YANG",
"variable",
"/",
"interfaces",
"/",
"interface",
"/",
"aggregation",
"/",
"switched_vlan",
"/",
"state",
"/",
"trunk_vlans",
"(",
"union",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
"_set_trunk_vlans",
"is",
"considered",
"as",
"a",
"private",
"method",
".",
"Backends",
"looking",
"to",
"populate",
"this",
"variable",
"should",
"do",
"so",
"via",
"calling",
"thisObj",
".",
"_set_trunk_vlans",
"()",
"directly",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/models/openconfig/interfaces/interface/aggregation/switched_vlan/state/__init__.py#L476-L553
|
[
"def",
"_set_trunk_vlans",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=",
"TypedListType",
"(",
"allowed_type",
"=",
"[",
"RestrictedClassType",
"(",
"base_type",
"=",
"RestrictedClassType",
"(",
"base_type",
"=",
"int",
",",
"restriction_dict",
"=",
"{",
"\"range\"",
":",
"[",
"\"0..65535\"",
"]",
"}",
",",
"int_size",
"=",
"16",
",",
")",
",",
"restriction_dict",
"=",
"{",
"\"range\"",
":",
"[",
"\"1..4094\"",
"]",
"}",
",",
")",
",",
"RestrictedClassType",
"(",
"base_type",
"=",
"six",
".",
"text_type",
",",
"restriction_dict",
"=",
"{",
"\"pattern\"",
":",
"\"(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\"",
"}",
",",
")",
",",
"RestrictedClassType",
"(",
"base_type",
"=",
"six",
".",
"text_type",
",",
"restriction_dict",
"=",
"{",
"\"pattern\"",
":",
"\"(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\\\*)\"",
"}",
",",
")",
",",
"RestrictedClassType",
"(",
"base_type",
"=",
"six",
".",
"text_type",
",",
"restriction_dict",
"=",
"{",
"\"pattern\"",
":",
"\"(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\\\*)\"",
"}",
",",
")",
",",
"RestrictedClassType",
"(",
"base_type",
"=",
"six",
".",
"text_type",
",",
"restriction_dict",
"=",
"{",
"\"pattern\"",
":",
"\"(\\\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\"",
"}",
",",
")",
",",
"]",
")",
",",
"is_leaf",
"=",
"False",
",",
"yang_name",
"=",
"\"trunk-vlans\"",
",",
"parent",
"=",
"self",
",",
"path_helper",
"=",
"self",
".",
"_path_helper",
",",
"extmethods",
"=",
"self",
".",
"_extmethods",
",",
"register_paths",
"=",
"True",
",",
"namespace",
"=",
"\"http://openconfig.net/yang/vlan\"",
",",
"defining_module",
"=",
"\"openconfig-vlan\"",
",",
"yang_type",
"=",
"\"union\"",
",",
"is_config",
"=",
"False",
",",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"{",
"\"error-string\"",
":",
"\"\"\"trunk_vlans must be of a type compatible with union\"\"\"",
",",
"\"defined-type\"",
":",
"\"openconfig-vlan:union\"",
",",
"\"generated-type\"",
":",
"\"\"\"YANGDynClass(base=TypedListType(allowed_type=[RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), restriction_dict={'range': ['1..4094']}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.((409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])|\\\\*)'}),RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '(\\\\*|(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9]))\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])\\\\.\\\\.(409[0-4]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{1,2}|[1-9])'}),]), is_leaf=False, yang_name=\"trunk-vlans\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/vlan', defining_module='openconfig-vlan', yang_type='union', is_config=False)\"\"\"",
",",
"}",
")",
"self",
".",
"__trunk_vlans",
"=",
"t",
"if",
"hasattr",
"(",
"self",
",",
"\"_set\"",
")",
":",
"self",
".",
"_set",
"(",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
find_yang_file
|
Find the necessary file for the given test case.
Args:
device(napalm device connection): for which device
filename(str): file to find
path(str): where to find it relative to where the module is installed
|
napalm_yang/helpers.py
|
def find_yang_file(profile, filename, path):
"""
Find the necessary file for the given test case.
Args:
device(napalm device connection): for which device
filename(str): file to find
path(str): where to find it relative to where the module is installed
"""
# Find base_dir of submodule
module_dir = os.path.dirname(__file__)
full_path = os.path.join(module_dir, "mappings", profile, path, filename)
if os.path.exists(full_path):
return full_path
else:
msg = "Couldn't find parsing file: {}".format(full_path)
logger.error(msg)
raise IOError(msg)
|
def find_yang_file(profile, filename, path):
"""
Find the necessary file for the given test case.
Args:
device(napalm device connection): for which device
filename(str): file to find
path(str): where to find it relative to where the module is installed
"""
# Find base_dir of submodule
module_dir = os.path.dirname(__file__)
full_path = os.path.join(module_dir, "mappings", profile, path, filename)
if os.path.exists(full_path):
return full_path
else:
msg = "Couldn't find parsing file: {}".format(full_path)
logger.error(msg)
raise IOError(msg)
|
[
"Find",
"the",
"necessary",
"file",
"for",
"the",
"given",
"test",
"case",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/helpers.py#L32-L50
|
[
"def",
"find_yang_file",
"(",
"profile",
",",
"filename",
",",
"path",
")",
":",
"# Find base_dir of submodule",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"module_dir",
",",
"\"mappings\"",
",",
"profile",
",",
"path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
":",
"return",
"full_path",
"else",
":",
"msg",
"=",
"\"Couldn't find parsing file: {}\"",
".",
"format",
"(",
"full_path",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"IOError",
"(",
"msg",
")"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
model_to_dict
|
Given a model, return a representation of the model in a dict.
This is mostly useful to have a quick visual represenation of the model.
Args:
model (PybindBase): Model to transform.
mode (string): Whether to print config, state or all elements ("" for all)
Returns:
dict: A dictionary representing the model.
Examples:
>>> config = napalm_yang.base.Root()
>>>
>>> # Adding models to the object
>>> config.add_model(napalm_yang.models.openconfig_interfaces())
>>> config.add_model(napalm_yang.models.openconfig_vlan())
>>> # Printing the model in a human readable format
>>> pretty_print(napalm_yang.utils.model_to_dict(config))
>>> {
>>> "openconfig-interfaces:interfaces [rw]": {
>>> "interface [rw]": {
>>> "config [rw]": {
>>> "description [rw]": "string",
>>> "enabled [rw]": "boolean",
>>> "mtu [rw]": "uint16",
>>> "name [rw]": "string",
>>> "type [rw]": "identityref"
>>> },
>>> "hold_time [rw]": {
>>> "config [rw]": {
>>> "down [rw]": "uint32",
>>> "up [rw]": "uint32"
(trimmed for clarity)
|
napalm_yang/utils.py
|
def model_to_dict(model, mode="", show_defaults=False):
"""
Given a model, return a representation of the model in a dict.
This is mostly useful to have a quick visual represenation of the model.
Args:
model (PybindBase): Model to transform.
mode (string): Whether to print config, state or all elements ("" for all)
Returns:
dict: A dictionary representing the model.
Examples:
>>> config = napalm_yang.base.Root()
>>>
>>> # Adding models to the object
>>> config.add_model(napalm_yang.models.openconfig_interfaces())
>>> config.add_model(napalm_yang.models.openconfig_vlan())
>>> # Printing the model in a human readable format
>>> pretty_print(napalm_yang.utils.model_to_dict(config))
>>> {
>>> "openconfig-interfaces:interfaces [rw]": {
>>> "interface [rw]": {
>>> "config [rw]": {
>>> "description [rw]": "string",
>>> "enabled [rw]": "boolean",
>>> "mtu [rw]": "uint16",
>>> "name [rw]": "string",
>>> "type [rw]": "identityref"
>>> },
>>> "hold_time [rw]": {
>>> "config [rw]": {
>>> "down [rw]": "uint32",
>>> "up [rw]": "uint32"
(trimmed for clarity)
"""
def is_mode(obj, mode):
if mode == "":
return True
elif mode == "config":
return obj._yang_name == "config" or obj._is_config
elif mode == "state":
return obj._yang_name == "state" or not obj._is_config
else:
raise ValueError(
"mode can only be config, state or ''. Passed: {}".format(mode)
)
def get_key(key, model, parent_defining_module, show_defaults):
if not show_defaults:
# No need to display rw/ro when showing the defaults.
key = "{} {}".format(key, "[rw]" if model._is_config else "[ro]")
if parent_defining_module != model._defining_module:
key = "{}:{}".format(model._defining_module, key)
return key
if model._yang_type in ("container", "list"):
cls = model if model._yang_type in ("container",) else model._contained_class()
result = {}
for k, v in cls:
r = model_to_dict(v, mode=mode, show_defaults=show_defaults)
if r:
result[get_key(k, v, model._defining_module, show_defaults)] = r
return result
else:
if show_defaults:
if model._default is False:
if model._yang_type != "boolean":
# Unless the datatype is bool, when the _default attribute
# is False, it means there is not default value defined in
# the YANG model.
return None
return model._default
return model._yang_type if is_mode(model, mode) else None
|
def model_to_dict(model, mode="", show_defaults=False):
"""
Given a model, return a representation of the model in a dict.
This is mostly useful to have a quick visual represenation of the model.
Args:
model (PybindBase): Model to transform.
mode (string): Whether to print config, state or all elements ("" for all)
Returns:
dict: A dictionary representing the model.
Examples:
>>> config = napalm_yang.base.Root()
>>>
>>> # Adding models to the object
>>> config.add_model(napalm_yang.models.openconfig_interfaces())
>>> config.add_model(napalm_yang.models.openconfig_vlan())
>>> # Printing the model in a human readable format
>>> pretty_print(napalm_yang.utils.model_to_dict(config))
>>> {
>>> "openconfig-interfaces:interfaces [rw]": {
>>> "interface [rw]": {
>>> "config [rw]": {
>>> "description [rw]": "string",
>>> "enabled [rw]": "boolean",
>>> "mtu [rw]": "uint16",
>>> "name [rw]": "string",
>>> "type [rw]": "identityref"
>>> },
>>> "hold_time [rw]": {
>>> "config [rw]": {
>>> "down [rw]": "uint32",
>>> "up [rw]": "uint32"
(trimmed for clarity)
"""
def is_mode(obj, mode):
if mode == "":
return True
elif mode == "config":
return obj._yang_name == "config" or obj._is_config
elif mode == "state":
return obj._yang_name == "state" or not obj._is_config
else:
raise ValueError(
"mode can only be config, state or ''. Passed: {}".format(mode)
)
def get_key(key, model, parent_defining_module, show_defaults):
if not show_defaults:
# No need to display rw/ro when showing the defaults.
key = "{} {}".format(key, "[rw]" if model._is_config else "[ro]")
if parent_defining_module != model._defining_module:
key = "{}:{}".format(model._defining_module, key)
return key
if model._yang_type in ("container", "list"):
cls = model if model._yang_type in ("container",) else model._contained_class()
result = {}
for k, v in cls:
r = model_to_dict(v, mode=mode, show_defaults=show_defaults)
if r:
result[get_key(k, v, model._defining_module, show_defaults)] = r
return result
else:
if show_defaults:
if model._default is False:
if model._yang_type != "boolean":
# Unless the datatype is bool, when the _default attribute
# is False, it means there is not default value defined in
# the YANG model.
return None
return model._default
return model._yang_type if is_mode(model, mode) else None
|
[
"Given",
"a",
"model",
"return",
"a",
"representation",
"of",
"the",
"model",
"in",
"a",
"dict",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/utils.py#L4-L83
|
[
"def",
"model_to_dict",
"(",
"model",
",",
"mode",
"=",
"\"\"",
",",
"show_defaults",
"=",
"False",
")",
":",
"def",
"is_mode",
"(",
"obj",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"\"\"",
":",
"return",
"True",
"elif",
"mode",
"==",
"\"config\"",
":",
"return",
"obj",
".",
"_yang_name",
"==",
"\"config\"",
"or",
"obj",
".",
"_is_config",
"elif",
"mode",
"==",
"\"state\"",
":",
"return",
"obj",
".",
"_yang_name",
"==",
"\"state\"",
"or",
"not",
"obj",
".",
"_is_config",
"else",
":",
"raise",
"ValueError",
"(",
"\"mode can only be config, state or ''. Passed: {}\"",
".",
"format",
"(",
"mode",
")",
")",
"def",
"get_key",
"(",
"key",
",",
"model",
",",
"parent_defining_module",
",",
"show_defaults",
")",
":",
"if",
"not",
"show_defaults",
":",
"# No need to display rw/ro when showing the defaults.",
"key",
"=",
"\"{} {}\"",
".",
"format",
"(",
"key",
",",
"\"[rw]\"",
"if",
"model",
".",
"_is_config",
"else",
"\"[ro]\"",
")",
"if",
"parent_defining_module",
"!=",
"model",
".",
"_defining_module",
":",
"key",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"model",
".",
"_defining_module",
",",
"key",
")",
"return",
"key",
"if",
"model",
".",
"_yang_type",
"in",
"(",
"\"container\"",
",",
"\"list\"",
")",
":",
"cls",
"=",
"model",
"if",
"model",
".",
"_yang_type",
"in",
"(",
"\"container\"",
",",
")",
"else",
"model",
".",
"_contained_class",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"cls",
":",
"r",
"=",
"model_to_dict",
"(",
"v",
",",
"mode",
"=",
"mode",
",",
"show_defaults",
"=",
"show_defaults",
")",
"if",
"r",
":",
"result",
"[",
"get_key",
"(",
"k",
",",
"v",
",",
"model",
".",
"_defining_module",
",",
"show_defaults",
")",
"]",
"=",
"r",
"return",
"result",
"else",
":",
"if",
"show_defaults",
":",
"if",
"model",
".",
"_default",
"is",
"False",
":",
"if",
"model",
".",
"_yang_type",
"!=",
"\"boolean\"",
":",
"# Unless the datatype is bool, when the _default attribute",
"# is False, it means there is not default value defined in",
"# the YANG model.",
"return",
"None",
"return",
"model",
".",
"_default",
"return",
"model",
".",
"_yang_type",
"if",
"is_mode",
"(",
"model",
",",
"mode",
")",
"else",
"None"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
diff
|
Given two models, return the difference between them.
Args:
f (Pybindbase): First element.
s (Pybindbase): Second element.
Returns:
dict: A dictionary highlighting the differences.
Examples:
>>> diff = napalm_yang.utils.diff(candidate, running)
>>> pretty_print(diff)
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "both": {
>>> "Port-Channel1": {
>>> "config": {
>>> "mtu": {
>>> "first": "0",
>>> "second": "9000"
>>> }
>>> }
>>> }
>>> },
>>> "first_only": [
>>> "Loopback0"
>>> ],
>>> "second_only": [
>>> "Loopback1"
>>> ]
>>> }
>>> }
>>> }
|
napalm_yang/utils.py
|
def diff(f, s):
"""
Given two models, return the difference between them.
Args:
f (Pybindbase): First element.
s (Pybindbase): Second element.
Returns:
dict: A dictionary highlighting the differences.
Examples:
>>> diff = napalm_yang.utils.diff(candidate, running)
>>> pretty_print(diff)
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "both": {
>>> "Port-Channel1": {
>>> "config": {
>>> "mtu": {
>>> "first": "0",
>>> "second": "9000"
>>> }
>>> }
>>> }
>>> },
>>> "first_only": [
>>> "Loopback0"
>>> ],
>>> "second_only": [
>>> "Loopback1"
>>> ]
>>> }
>>> }
>>> }
"""
if isinstance(f, base.Root) or f._yang_type in ("container", None):
result = _diff_root(f, s)
elif f._yang_type in ("list",):
result = _diff_list(f, s)
else:
result = {}
first = "{}".format(f)
second = "{}".format(s)
if first != second:
result = {"first": first, "second": second}
return result
|
def diff(f, s):
"""
Given two models, return the difference between them.
Args:
f (Pybindbase): First element.
s (Pybindbase): Second element.
Returns:
dict: A dictionary highlighting the differences.
Examples:
>>> diff = napalm_yang.utils.diff(candidate, running)
>>> pretty_print(diff)
>>> {
>>> "interfaces": {
>>> "interface": {
>>> "both": {
>>> "Port-Channel1": {
>>> "config": {
>>> "mtu": {
>>> "first": "0",
>>> "second": "9000"
>>> }
>>> }
>>> }
>>> },
>>> "first_only": [
>>> "Loopback0"
>>> ],
>>> "second_only": [
>>> "Loopback1"
>>> ]
>>> }
>>> }
>>> }
"""
if isinstance(f, base.Root) or f._yang_type in ("container", None):
result = _diff_root(f, s)
elif f._yang_type in ("list",):
result = _diff_list(f, s)
else:
result = {}
first = "{}".format(f)
second = "{}".format(s)
if first != second:
result = {"first": first, "second": second}
return result
|
[
"Given",
"two",
"models",
"return",
"the",
"difference",
"between",
"them",
"."
] |
napalm-automation/napalm-yang
|
python
|
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/napalm_yang/utils.py#L125-L176
|
[
"def",
"diff",
"(",
"f",
",",
"s",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"base",
".",
"Root",
")",
"or",
"f",
".",
"_yang_type",
"in",
"(",
"\"container\"",
",",
"None",
")",
":",
"result",
"=",
"_diff_root",
"(",
"f",
",",
"s",
")",
"elif",
"f",
".",
"_yang_type",
"in",
"(",
"\"list\"",
",",
")",
":",
"result",
"=",
"_diff_list",
"(",
"f",
",",
"s",
")",
"else",
":",
"result",
"=",
"{",
"}",
"first",
"=",
"\"{}\"",
".",
"format",
"(",
"f",
")",
"second",
"=",
"\"{}\"",
".",
"format",
"(",
"s",
")",
"if",
"first",
"!=",
"second",
":",
"result",
"=",
"{",
"\"first\"",
":",
"first",
",",
"\"second\"",
":",
"second",
"}",
"return",
"result"
] |
998e8a933171d010b8544bcc5dc448e2b68051e2
|
test
|
Client.http_post
|
POST to URL and get result as a response object.
:param url: URL to POST.
:type url: str
:param data: Data to send in the form body.
:type data: str
:rtype: requests.Response
|
oauth2lib/client.py
|
def http_post(self, url, data=None):
"""POST to URL and get result as a response object.
:param url: URL to POST.
:type url: str
:param data: Data to send in the form body.
:type data: str
:rtype: requests.Response
"""
if not url.startswith('https://'):
raise ValueError('Protocol must be HTTPS, invalid URL: %s' % url)
return requests.post(url, data, verify=True)
|
def http_post(self, url, data=None):
"""POST to URL and get result as a response object.
:param url: URL to POST.
:type url: str
:param data: Data to send in the form body.
:type data: str
:rtype: requests.Response
"""
if not url.startswith('https://'):
raise ValueError('Protocol must be HTTPS, invalid URL: %s' % url)
return requests.post(url, data, verify=True)
|
[
"POST",
"to",
"URL",
"and",
"get",
"result",
"as",
"a",
"response",
"object",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/client.py#L36-L47
|
[
"def",
"http_post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'https://'",
")",
":",
"raise",
"ValueError",
"(",
"'Protocol must be HTTPS, invalid URL: %s'",
"%",
"url",
")",
"return",
"requests",
".",
"post",
"(",
"url",
",",
"data",
",",
"verify",
"=",
"True",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Client.get_authorization_code_uri
|
Construct a full URL that can be used to obtain an authorization
code from the provider authorization_uri. Use this URI in a client
frame to cause the provider to generate an authorization code.
:rtype: str
|
oauth2lib/client.py
|
def get_authorization_code_uri(self, **params):
"""Construct a full URL that can be used to obtain an authorization
code from the provider authorization_uri. Use this URI in a client
frame to cause the provider to generate an authorization code.
:rtype: str
"""
if 'response_type' not in params:
params['response_type'] = self.default_response_type
params.update({'client_id': self.client_id,
'redirect_uri': self.redirect_uri})
return utils.build_url(self.authorization_uri, params)
|
def get_authorization_code_uri(self, **params):
"""Construct a full URL that can be used to obtain an authorization
code from the provider authorization_uri. Use this URI in a client
frame to cause the provider to generate an authorization code.
:rtype: str
"""
if 'response_type' not in params:
params['response_type'] = self.default_response_type
params.update({'client_id': self.client_id,
'redirect_uri': self.redirect_uri})
return utils.build_url(self.authorization_uri, params)
|
[
"Construct",
"a",
"full",
"URL",
"that",
"can",
"be",
"used",
"to",
"obtain",
"an",
"authorization",
"code",
"from",
"the",
"provider",
"authorization_uri",
".",
"Use",
"this",
"URI",
"in",
"a",
"client",
"frame",
"to",
"cause",
"the",
"provider",
"to",
"generate",
"an",
"authorization",
"code",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/client.py#L49-L60
|
[
"def",
"get_authorization_code_uri",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"'response_type'",
"not",
"in",
"params",
":",
"params",
"[",
"'response_type'",
"]",
"=",
"self",
".",
"default_response_type",
"params",
".",
"update",
"(",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_uri",
"}",
")",
"return",
"utils",
".",
"build_url",
"(",
"self",
".",
"authorization_uri",
",",
"params",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Client.get_token
|
Get an access token from the provider token URI.
:param code: Authorization code.
:type code: str
:return: Dict containing access token, refresh token, etc.
:rtype: dict
|
oauth2lib/client.py
|
def get_token(self, code, **params):
"""Get an access token from the provider token URI.
:param code: Authorization code.
:type code: str
:return: Dict containing access token, refresh token, etc.
:rtype: dict
"""
params['code'] = code
if 'grant_type' not in params:
params['grant_type'] = self.default_grant_type
params.update({'client_id': self.client_id,
'client_secret': self.client_secret,
'redirect_uri': self.redirect_uri})
response = self.http_post(self.token_uri, params)
try:
return response.json()
except TypeError:
return response.json
|
def get_token(self, code, **params):
"""Get an access token from the provider token URI.
:param code: Authorization code.
:type code: str
:return: Dict containing access token, refresh token, etc.
:rtype: dict
"""
params['code'] = code
if 'grant_type' not in params:
params['grant_type'] = self.default_grant_type
params.update({'client_id': self.client_id,
'client_secret': self.client_secret,
'redirect_uri': self.redirect_uri})
response = self.http_post(self.token_uri, params)
try:
return response.json()
except TypeError:
return response.json
|
[
"Get",
"an",
"access",
"token",
"from",
"the",
"provider",
"token",
"URI",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/client.py#L62-L80
|
[
"def",
"get_token",
"(",
"self",
",",
"code",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'code'",
"]",
"=",
"code",
"if",
"'grant_type'",
"not",
"in",
"params",
":",
"params",
"[",
"'grant_type'",
"]",
"=",
"self",
".",
"default_grant_type",
"params",
".",
"update",
"(",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'client_secret'",
":",
"self",
".",
"client_secret",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_uri",
"}",
")",
"response",
"=",
"self",
".",
"http_post",
"(",
"self",
".",
"token_uri",
",",
"params",
")",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
"except",
"TypeError",
":",
"return",
"response",
".",
"json"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
url_query_params
|
Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
|
oauth2lib/utils.py
|
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(urlparse.parse_qsl(urlparse.urlparse(url).query, True))
|
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(urlparse.parse_qsl(urlparse.urlparse(url).query, True))
|
[
"Return",
"query",
"parameters",
"as",
"a",
"dict",
"from",
"the",
"specified",
"URL",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/utils.py#L15-L22
|
[
"def",
"url_query_params",
"(",
"url",
")",
":",
"return",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
".",
"query",
",",
"True",
")",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
url_dequery
|
Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
|
oauth2lib/utils.py
|
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse.urlparse(url)
return urlparse.urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
|
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse.urlparse(url)
return urlparse.urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
|
[
"Return",
"a",
"URL",
"with",
"the",
"query",
"component",
"removed",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/utils.py#L25-L38
|
[
"def",
"url_dequery",
"(",
"url",
")",
":",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"return",
"urlparse",
".",
"urlunparse",
"(",
"(",
"url",
".",
"scheme",
",",
"url",
".",
"netloc",
",",
"url",
".",
"path",
",",
"url",
".",
"params",
",",
"''",
",",
"url",
".",
"fragment",
")",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
build_url
|
Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
|
oauth2lib/utils.py
|
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse.urlparse(base)
query_params = {}
query_params.update(urlparse.parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.iteritems():
if v is None:
query_params.pop(k)
return urlparse.urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urllib.urlencode(query_params),
url.fragment))
|
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse.urlparse(base)
query_params = {}
query_params.update(urlparse.parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.iteritems():
if v is None:
query_params.pop(k)
return urlparse.urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urllib.urlencode(query_params),
url.fragment))
|
[
"Construct",
"a",
"URL",
"based",
"off",
"of",
"base",
"containing",
"all",
"parameters",
"in",
"the",
"query",
"portion",
"of",
"base",
"plus",
"any",
"additional",
"parameters",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/utils.py#L41-L65
|
[
"def",
"build_url",
"(",
"base",
",",
"additional_params",
"=",
"None",
")",
":",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"base",
")",
"query_params",
"=",
"{",
"}",
"query_params",
".",
"update",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"url",
".",
"query",
",",
"True",
")",
")",
"if",
"additional_params",
"is",
"not",
"None",
":",
"query_params",
".",
"update",
"(",
"additional_params",
")",
"for",
"k",
",",
"v",
"in",
"additional_params",
".",
"iteritems",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"query_params",
".",
"pop",
"(",
"k",
")",
"return",
"urlparse",
".",
"urlunparse",
"(",
"(",
"url",
".",
"scheme",
",",
"url",
".",
"netloc",
",",
"url",
".",
"path",
",",
"url",
".",
"params",
",",
"urllib",
".",
"urlencode",
"(",
"query_params",
")",
",",
"url",
".",
"fragment",
")",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Provider._handle_exception
|
Handle an internal exception that was caught and suppressed.
:param exc: Exception to process.
:type exc: Exception
|
oauth2lib/provider.py
|
def _handle_exception(self, exc):
"""Handle an internal exception that was caught and suppressed.
:param exc: Exception to process.
:type exc: Exception
"""
logger = logging.getLogger(__name__)
logger.exception(exc)
|
def _handle_exception(self, exc):
"""Handle an internal exception that was caught and suppressed.
:param exc: Exception to process.
:type exc: Exception
"""
logger = logging.getLogger(__name__)
logger.exception(exc)
|
[
"Handle",
"an",
"internal",
"exception",
"that",
"was",
"caught",
"and",
"suppressed",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L15-L22
|
[
"def",
"_handle_exception",
"(",
"self",
",",
"exc",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"exception",
"(",
"exc",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Provider._make_response
|
Return a response object from the given parameters.
:param body: Buffer/string containing the response body.
:type body: str
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
|
oauth2lib/provider.py
|
def _make_response(self, body='', headers=None, status_code=200):
"""Return a response object from the given parameters.
:param body: Buffer/string containing the response body.
:type body: str
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
"""
res = Response()
res.status_code = status_code
if headers is not None:
res.headers.update(headers)
res.raw = StringIO(body)
return res
|
def _make_response(self, body='', headers=None, status_code=200):
"""Return a response object from the given parameters.
:param body: Buffer/string containing the response body.
:type body: str
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
"""
res = Response()
res.status_code = status_code
if headers is not None:
res.headers.update(headers)
res.raw = StringIO(body)
return res
|
[
"Return",
"a",
"response",
"object",
"from",
"the",
"given",
"parameters",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L24-L40
|
[
"def",
"_make_response",
"(",
"self",
",",
"body",
"=",
"''",
",",
"headers",
"=",
"None",
",",
"status_code",
"=",
"200",
")",
":",
"res",
"=",
"Response",
"(",
")",
"res",
".",
"status_code",
"=",
"status_code",
"if",
"headers",
"is",
"not",
"None",
":",
"res",
".",
"headers",
".",
"update",
"(",
"headers",
")",
"res",
".",
"raw",
"=",
"StringIO",
"(",
"body",
")",
"return",
"res"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Provider._make_redirect_error_response
|
Return a HTTP 302 redirect response object containing the error.
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param err: OAuth error message.
:type err: str
:rtype: requests.Response
|
oauth2lib/provider.py
|
def _make_redirect_error_response(self, redirect_uri, err):
"""Return a HTTP 302 redirect response object containing the error.
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param err: OAuth error message.
:type err: str
:rtype: requests.Response
"""
params = {
'error': err,
'response_type': None,
'client_id': None,
'redirect_uri': None
}
redirect = utils.build_url(redirect_uri, params)
return self._make_response(headers={'Location': redirect},
status_code=302)
|
def _make_redirect_error_response(self, redirect_uri, err):
"""Return a HTTP 302 redirect response object containing the error.
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param err: OAuth error message.
:type err: str
:rtype: requests.Response
"""
params = {
'error': err,
'response_type': None,
'client_id': None,
'redirect_uri': None
}
redirect = utils.build_url(redirect_uri, params)
return self._make_response(headers={'Location': redirect},
status_code=302)
|
[
"Return",
"a",
"HTTP",
"302",
"redirect",
"response",
"object",
"containing",
"the",
"error",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L42-L59
|
[
"def",
"_make_redirect_error_response",
"(",
"self",
",",
"redirect_uri",
",",
"err",
")",
":",
"params",
"=",
"{",
"'error'",
":",
"err",
",",
"'response_type'",
":",
"None",
",",
"'client_id'",
":",
"None",
",",
"'redirect_uri'",
":",
"None",
"}",
"redirect",
"=",
"utils",
".",
"build_url",
"(",
"redirect_uri",
",",
"params",
")",
"return",
"self",
".",
"_make_response",
"(",
"headers",
"=",
"{",
"'Location'",
":",
"redirect",
"}",
",",
"status_code",
"=",
"302",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
Provider._make_json_response
|
Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
|
oauth2lib/provider.py
|
def _make_json_response(self, data, headers=None, status_code=200):
"""Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
"""
response_headers = {}
if headers is not None:
response_headers.update(headers)
response_headers['Content-Type'] = 'application/json;charset=UTF-8'
response_headers['Cache-Control'] = 'no-store'
response_headers['Pragma'] = 'no-cache'
return self._make_response(json.dumps(data),
response_headers,
status_code)
|
def _make_json_response(self, data, headers=None, status_code=200):
"""Return a response object from the given JSON data.
:param data: Data to JSON-encode.
:type data: mixed
:param headers: Dict of headers to include in the requests.
:type headers: dict
:param status_code: HTTP status code.
:type status_code: int
:rtype: requests.Response
"""
response_headers = {}
if headers is not None:
response_headers.update(headers)
response_headers['Content-Type'] = 'application/json;charset=UTF-8'
response_headers['Cache-Control'] = 'no-store'
response_headers['Pragma'] = 'no-cache'
return self._make_response(json.dumps(data),
response_headers,
status_code)
|
[
"Return",
"a",
"response",
"object",
"from",
"the",
"given",
"JSON",
"data",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L61-L80
|
[
"def",
"_make_json_response",
"(",
"self",
",",
"data",
",",
"headers",
"=",
"None",
",",
"status_code",
"=",
"200",
")",
":",
"response_headers",
"=",
"{",
"}",
"if",
"headers",
"is",
"not",
"None",
":",
"response_headers",
".",
"update",
"(",
"headers",
")",
"response_headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json;charset=UTF-8'",
"response_headers",
"[",
"'Cache-Control'",
"]",
"=",
"'no-store'",
"response_headers",
"[",
"'Pragma'",
"]",
"=",
"'no-cache'",
"return",
"self",
".",
"_make_response",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"response_headers",
",",
"status_code",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
AuthorizationProvider.get_authorization_code
|
Generate authorization code HTTP response.
:param response_type: Desired response type. Must be exactly "code".
:type response_type: str
:param client_id: Client ID.
:type client_id: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:rtype: requests.Response
|
oauth2lib/provider.py
|
def get_authorization_code(self,
response_type,
client_id,
redirect_uri,
**params):
"""Generate authorization code HTTP response.
:param response_type: Desired response type. Must be exactly "code".
:type response_type: str
:param client_id: Client ID.
:type client_id: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:rtype: requests.Response
"""
# Ensure proper response_type
if response_type != 'code':
err = 'unsupported_response_type'
return self._make_redirect_error_response(redirect_uri, err)
# Check redirect URI
is_valid_redirect_uri = self.validate_redirect_uri(client_id,
redirect_uri)
if not is_valid_redirect_uri:
return self._invalid_redirect_uri_response()
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_access = self.validate_access()
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
# Return proper error responses on invalid conditions
if not is_valid_client_id:
err = 'unauthorized_client'
return self._make_redirect_error_response(redirect_uri, err)
if not is_valid_access:
err = 'access_denied'
return self._make_redirect_error_response(redirect_uri, err)
if not is_valid_scope:
err = 'invalid_scope'
return self._make_redirect_error_response(redirect_uri, err)
# Generate authorization code
code = self.generate_authorization_code()
# Save information to be used to validate later requests
self.persist_authorization_code(client_id=client_id,
code=code,
scope=scope)
# Return redirection response
params.update({
'code': code,
'response_type': None,
'client_id': None,
'redirect_uri': None
})
redirect = utils.build_url(redirect_uri, params)
return self._make_response(headers={'Location': redirect},
status_code=302)
|
def get_authorization_code(self,
response_type,
client_id,
redirect_uri,
**params):
"""Generate authorization code HTTP response.
:param response_type: Desired response type. Must be exactly "code".
:type response_type: str
:param client_id: Client ID.
:type client_id: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:rtype: requests.Response
"""
# Ensure proper response_type
if response_type != 'code':
err = 'unsupported_response_type'
return self._make_redirect_error_response(redirect_uri, err)
# Check redirect URI
is_valid_redirect_uri = self.validate_redirect_uri(client_id,
redirect_uri)
if not is_valid_redirect_uri:
return self._invalid_redirect_uri_response()
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_access = self.validate_access()
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
# Return proper error responses on invalid conditions
if not is_valid_client_id:
err = 'unauthorized_client'
return self._make_redirect_error_response(redirect_uri, err)
if not is_valid_access:
err = 'access_denied'
return self._make_redirect_error_response(redirect_uri, err)
if not is_valid_scope:
err = 'invalid_scope'
return self._make_redirect_error_response(redirect_uri, err)
# Generate authorization code
code = self.generate_authorization_code()
# Save information to be used to validate later requests
self.persist_authorization_code(client_id=client_id,
code=code,
scope=scope)
# Return redirection response
params.update({
'code': code,
'response_type': None,
'client_id': None,
'redirect_uri': None
})
redirect = utils.build_url(redirect_uri, params)
return self._make_response(headers={'Location': redirect},
status_code=302)
|
[
"Generate",
"authorization",
"code",
"HTTP",
"response",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L205-L268
|
[
"def",
"get_authorization_code",
"(",
"self",
",",
"response_type",
",",
"client_id",
",",
"redirect_uri",
",",
"*",
"*",
"params",
")",
":",
"# Ensure proper response_type",
"if",
"response_type",
"!=",
"'code'",
":",
"err",
"=",
"'unsupported_response_type'",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"redirect_uri",
",",
"err",
")",
"# Check redirect URI",
"is_valid_redirect_uri",
"=",
"self",
".",
"validate_redirect_uri",
"(",
"client_id",
",",
"redirect_uri",
")",
"if",
"not",
"is_valid_redirect_uri",
":",
"return",
"self",
".",
"_invalid_redirect_uri_response",
"(",
")",
"# Check conditions",
"is_valid_client_id",
"=",
"self",
".",
"validate_client_id",
"(",
"client_id",
")",
"is_valid_access",
"=",
"self",
".",
"validate_access",
"(",
")",
"scope",
"=",
"params",
".",
"get",
"(",
"'scope'",
",",
"''",
")",
"is_valid_scope",
"=",
"self",
".",
"validate_scope",
"(",
"client_id",
",",
"scope",
")",
"# Return proper error responses on invalid conditions",
"if",
"not",
"is_valid_client_id",
":",
"err",
"=",
"'unauthorized_client'",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"redirect_uri",
",",
"err",
")",
"if",
"not",
"is_valid_access",
":",
"err",
"=",
"'access_denied'",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"redirect_uri",
",",
"err",
")",
"if",
"not",
"is_valid_scope",
":",
"err",
"=",
"'invalid_scope'",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"redirect_uri",
",",
"err",
")",
"# Generate authorization code",
"code",
"=",
"self",
".",
"generate_authorization_code",
"(",
")",
"# Save information to be used to validate later requests",
"self",
".",
"persist_authorization_code",
"(",
"client_id",
"=",
"client_id",
",",
"code",
"=",
"code",
",",
"scope",
"=",
"scope",
")",
"# Return redirection response",
"params",
".",
"update",
"(",
"{",
"'code'",
":",
"code",
",",
"'response_type'",
":",
"None",
",",
"'client_id'",
":",
"None",
",",
"'redirect_uri'",
":",
"None",
"}",
")",
"redirect",
"=",
"utils",
".",
"build_url",
"(",
"redirect_uri",
",",
"params",
")",
"return",
"self",
".",
"_make_response",
"(",
"headers",
"=",
"{",
"'Location'",
":",
"redirect",
"}",
",",
"status_code",
"=",
"302",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
AuthorizationProvider.refresh_token
|
Generate access token HTTP response from a refresh token.
:param grant_type: Desired grant type. Must be "refresh_token".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param refresh_token: Refresh token.
:type refresh_token: str
:rtype: requests.Response
|
oauth2lib/provider.py
|
def refresh_token(self,
grant_type,
client_id,
client_secret,
refresh_token,
**params):
"""Generate access token HTTP response from a refresh token.
:param grant_type: Desired grant type. Must be "refresh_token".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param refresh_token: Refresh token.
:type refresh_token: str
:rtype: requests.Response
"""
# Ensure proper grant_type
if grant_type != 'refresh_token':
return self._make_json_error_response('unsupported_grant_type')
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_client_secret = self.validate_client_secret(client_id,
client_secret)
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
data = self.from_refresh_token(client_id, refresh_token, scope)
is_valid_refresh_token = data is not None
# Return proper error responses on invalid conditions
if not (is_valid_client_id and is_valid_client_secret):
return self._make_json_error_response('invalid_client')
if not is_valid_scope:
return self._make_json_error_response('invalid_scope')
if not is_valid_refresh_token:
return self._make_json_error_response('invalid_grant')
# Discard original refresh token
self.discard_refresh_token(client_id, refresh_token)
# Generate access tokens once all conditions have been met
access_token = self.generate_access_token()
token_type = self.token_type
expires_in = self.token_expires_in
refresh_token = self.generate_refresh_token()
# Save information to be used to validate later requests
self.persist_token_information(client_id=client_id,
scope=scope,
access_token=access_token,
token_type=token_type,
expires_in=expires_in,
refresh_token=refresh_token,
data=data)
# Return json response
return self._make_json_response({
'access_token': access_token,
'token_type': token_type,
'expires_in': expires_in,
'refresh_token': refresh_token
})
|
def refresh_token(self,
grant_type,
client_id,
client_secret,
refresh_token,
**params):
"""Generate access token HTTP response from a refresh token.
:param grant_type: Desired grant type. Must be "refresh_token".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param refresh_token: Refresh token.
:type refresh_token: str
:rtype: requests.Response
"""
# Ensure proper grant_type
if grant_type != 'refresh_token':
return self._make_json_error_response('unsupported_grant_type')
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_client_secret = self.validate_client_secret(client_id,
client_secret)
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
data = self.from_refresh_token(client_id, refresh_token, scope)
is_valid_refresh_token = data is not None
# Return proper error responses on invalid conditions
if not (is_valid_client_id and is_valid_client_secret):
return self._make_json_error_response('invalid_client')
if not is_valid_scope:
return self._make_json_error_response('invalid_scope')
if not is_valid_refresh_token:
return self._make_json_error_response('invalid_grant')
# Discard original refresh token
self.discard_refresh_token(client_id, refresh_token)
# Generate access tokens once all conditions have been met
access_token = self.generate_access_token()
token_type = self.token_type
expires_in = self.token_expires_in
refresh_token = self.generate_refresh_token()
# Save information to be used to validate later requests
self.persist_token_information(client_id=client_id,
scope=scope,
access_token=access_token,
token_type=token_type,
expires_in=expires_in,
refresh_token=refresh_token,
data=data)
# Return json response
return self._make_json_response({
'access_token': access_token,
'token_type': token_type,
'expires_in': expires_in,
'refresh_token': refresh_token
})
|
[
"Generate",
"access",
"token",
"HTTP",
"response",
"from",
"a",
"refresh",
"token",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L270-L336
|
[
"def",
"refresh_token",
"(",
"self",
",",
"grant_type",
",",
"client_id",
",",
"client_secret",
",",
"refresh_token",
",",
"*",
"*",
"params",
")",
":",
"# Ensure proper grant_type",
"if",
"grant_type",
"!=",
"'refresh_token'",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'unsupported_grant_type'",
")",
"# Check conditions",
"is_valid_client_id",
"=",
"self",
".",
"validate_client_id",
"(",
"client_id",
")",
"is_valid_client_secret",
"=",
"self",
".",
"validate_client_secret",
"(",
"client_id",
",",
"client_secret",
")",
"scope",
"=",
"params",
".",
"get",
"(",
"'scope'",
",",
"''",
")",
"is_valid_scope",
"=",
"self",
".",
"validate_scope",
"(",
"client_id",
",",
"scope",
")",
"data",
"=",
"self",
".",
"from_refresh_token",
"(",
"client_id",
",",
"refresh_token",
",",
"scope",
")",
"is_valid_refresh_token",
"=",
"data",
"is",
"not",
"None",
"# Return proper error responses on invalid conditions",
"if",
"not",
"(",
"is_valid_client_id",
"and",
"is_valid_client_secret",
")",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_client'",
")",
"if",
"not",
"is_valid_scope",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_scope'",
")",
"if",
"not",
"is_valid_refresh_token",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_grant'",
")",
"# Discard original refresh token",
"self",
".",
"discard_refresh_token",
"(",
"client_id",
",",
"refresh_token",
")",
"# Generate access tokens once all conditions have been met",
"access_token",
"=",
"self",
".",
"generate_access_token",
"(",
")",
"token_type",
"=",
"self",
".",
"token_type",
"expires_in",
"=",
"self",
".",
"token_expires_in",
"refresh_token",
"=",
"self",
".",
"generate_refresh_token",
"(",
")",
"# Save information to be used to validate later requests",
"self",
".",
"persist_token_information",
"(",
"client_id",
"=",
"client_id",
",",
"scope",
"=",
"scope",
",",
"access_token",
"=",
"access_token",
",",
"token_type",
"=",
"token_type",
",",
"expires_in",
"=",
"expires_in",
",",
"refresh_token",
"=",
"refresh_token",
",",
"data",
"=",
"data",
")",
"# Return json response",
"return",
"self",
".",
"_make_json_response",
"(",
"{",
"'access_token'",
":",
"access_token",
",",
"'token_type'",
":",
"token_type",
",",
"'expires_in'",
":",
"expires_in",
",",
"'refresh_token'",
":",
"refresh_token",
"}",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
AuthorizationProvider.get_token
|
Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param code: Authorization code.
:type code: str
:rtype: requests.Response
|
oauth2lib/provider.py
|
def get_token(self,
grant_type,
client_id,
client_secret,
redirect_uri,
code,
**params):
"""Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param code: Authorization code.
:type code: str
:rtype: requests.Response
"""
# Ensure proper grant_type
if grant_type != 'authorization_code':
return self._make_json_error_response('unsupported_grant_type')
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_client_secret = self.validate_client_secret(client_id,
client_secret)
is_valid_redirect_uri = self.validate_redirect_uri(client_id,
redirect_uri)
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
data = self.from_authorization_code(client_id, code, scope)
is_valid_grant = data is not None
# Return proper error responses on invalid conditions
if not (is_valid_client_id and is_valid_client_secret):
return self._make_json_error_response('invalid_client')
if not is_valid_grant or not is_valid_redirect_uri:
return self._make_json_error_response('invalid_grant')
if not is_valid_scope:
return self._make_json_error_response('invalid_scope')
# Discard original authorization code
self.discard_authorization_code(client_id, code)
# Generate access tokens once all conditions have been met
access_token = self.generate_access_token()
token_type = self.token_type
expires_in = self.token_expires_in
refresh_token = self.generate_refresh_token()
# Save information to be used to validate later requests
self.persist_token_information(client_id=client_id,
scope=scope,
access_token=access_token,
token_type=token_type,
expires_in=expires_in,
refresh_token=refresh_token,
data=data)
# Return json response
return self._make_json_response({
'access_token': access_token,
'token_type': token_type,
'expires_in': expires_in,
'refresh_token': refresh_token
})
|
def get_token(self,
grant_type,
client_id,
client_secret,
redirect_uri,
code,
**params):
"""Generate access token HTTP response.
:param grant_type: Desired grant type. Must be "authorization_code".
:type grant_type: str
:param client_id: Client ID.
:type client_id: str
:param client_secret: Client secret.
:type client_secret: str
:param redirect_uri: Client redirect URI.
:type redirect_uri: str
:param code: Authorization code.
:type code: str
:rtype: requests.Response
"""
# Ensure proper grant_type
if grant_type != 'authorization_code':
return self._make_json_error_response('unsupported_grant_type')
# Check conditions
is_valid_client_id = self.validate_client_id(client_id)
is_valid_client_secret = self.validate_client_secret(client_id,
client_secret)
is_valid_redirect_uri = self.validate_redirect_uri(client_id,
redirect_uri)
scope = params.get('scope', '')
is_valid_scope = self.validate_scope(client_id, scope)
data = self.from_authorization_code(client_id, code, scope)
is_valid_grant = data is not None
# Return proper error responses on invalid conditions
if not (is_valid_client_id and is_valid_client_secret):
return self._make_json_error_response('invalid_client')
if not is_valid_grant or not is_valid_redirect_uri:
return self._make_json_error_response('invalid_grant')
if not is_valid_scope:
return self._make_json_error_response('invalid_scope')
# Discard original authorization code
self.discard_authorization_code(client_id, code)
# Generate access tokens once all conditions have been met
access_token = self.generate_access_token()
token_type = self.token_type
expires_in = self.token_expires_in
refresh_token = self.generate_refresh_token()
# Save information to be used to validate later requests
self.persist_token_information(client_id=client_id,
scope=scope,
access_token=access_token,
token_type=token_type,
expires_in=expires_in,
refresh_token=refresh_token,
data=data)
# Return json response
return self._make_json_response({
'access_token': access_token,
'token_type': token_type,
'expires_in': expires_in,
'refresh_token': refresh_token
})
|
[
"Generate",
"access",
"token",
"HTTP",
"response",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L338-L410
|
[
"def",
"get_token",
"(",
"self",
",",
"grant_type",
",",
"client_id",
",",
"client_secret",
",",
"redirect_uri",
",",
"code",
",",
"*",
"*",
"params",
")",
":",
"# Ensure proper grant_type",
"if",
"grant_type",
"!=",
"'authorization_code'",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'unsupported_grant_type'",
")",
"# Check conditions",
"is_valid_client_id",
"=",
"self",
".",
"validate_client_id",
"(",
"client_id",
")",
"is_valid_client_secret",
"=",
"self",
".",
"validate_client_secret",
"(",
"client_id",
",",
"client_secret",
")",
"is_valid_redirect_uri",
"=",
"self",
".",
"validate_redirect_uri",
"(",
"client_id",
",",
"redirect_uri",
")",
"scope",
"=",
"params",
".",
"get",
"(",
"'scope'",
",",
"''",
")",
"is_valid_scope",
"=",
"self",
".",
"validate_scope",
"(",
"client_id",
",",
"scope",
")",
"data",
"=",
"self",
".",
"from_authorization_code",
"(",
"client_id",
",",
"code",
",",
"scope",
")",
"is_valid_grant",
"=",
"data",
"is",
"not",
"None",
"# Return proper error responses on invalid conditions",
"if",
"not",
"(",
"is_valid_client_id",
"and",
"is_valid_client_secret",
")",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_client'",
")",
"if",
"not",
"is_valid_grant",
"or",
"not",
"is_valid_redirect_uri",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_grant'",
")",
"if",
"not",
"is_valid_scope",
":",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_scope'",
")",
"# Discard original authorization code",
"self",
".",
"discard_authorization_code",
"(",
"client_id",
",",
"code",
")",
"# Generate access tokens once all conditions have been met",
"access_token",
"=",
"self",
".",
"generate_access_token",
"(",
")",
"token_type",
"=",
"self",
".",
"token_type",
"expires_in",
"=",
"self",
".",
"token_expires_in",
"refresh_token",
"=",
"self",
".",
"generate_refresh_token",
"(",
")",
"# Save information to be used to validate later requests",
"self",
".",
"persist_token_information",
"(",
"client_id",
"=",
"client_id",
",",
"scope",
"=",
"scope",
",",
"access_token",
"=",
"access_token",
",",
"token_type",
"=",
"token_type",
",",
"expires_in",
"=",
"expires_in",
",",
"refresh_token",
"=",
"refresh_token",
",",
"data",
"=",
"data",
")",
"# Return json response",
"return",
"self",
".",
"_make_json_response",
"(",
"{",
"'access_token'",
":",
"access_token",
",",
"'token_type'",
":",
"token_type",
",",
"'expires_in'",
":",
"expires_in",
",",
"'refresh_token'",
":",
"refresh_token",
"}",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
AuthorizationProvider.get_authorization_code_from_uri
|
Get authorization code response from a URI. This method will
ignore the domain and path of the request, instead
automatically parsing the query string parameters.
:param uri: URI to parse for authorization information.
:type uri: str
:rtype: requests.Response
|
oauth2lib/provider.py
|
def get_authorization_code_from_uri(self, uri):
"""Get authorization code response from a URI. This method will
ignore the domain and path of the request, instead
automatically parsing the query string parameters.
:param uri: URI to parse for authorization information.
:type uri: str
:rtype: requests.Response
"""
params = utils.url_query_params(uri)
try:
if 'response_type' not in params:
raise TypeError('Missing parameter response_type in URL query')
if 'client_id' not in params:
raise TypeError('Missing parameter client_id in URL query')
if 'redirect_uri' not in params:
raise TypeError('Missing parameter redirect_uri in URL query')
return self.get_authorization_code(**params)
except TypeError as exc:
self._handle_exception(exc)
# Catch missing parameters in request
err = 'invalid_request'
if 'redirect_uri' in params:
u = params['redirect_uri']
return self._make_redirect_error_response(u, err)
else:
return self._invalid_redirect_uri_response()
except StandardError as exc:
self._handle_exception(exc)
# Catch all other server errors
err = 'server_error'
u = params['redirect_uri']
return self._make_redirect_error_response(u, err)
|
def get_authorization_code_from_uri(self, uri):
"""Get authorization code response from a URI. This method will
ignore the domain and path of the request, instead
automatically parsing the query string parameters.
:param uri: URI to parse for authorization information.
:type uri: str
:rtype: requests.Response
"""
params = utils.url_query_params(uri)
try:
if 'response_type' not in params:
raise TypeError('Missing parameter response_type in URL query')
if 'client_id' not in params:
raise TypeError('Missing parameter client_id in URL query')
if 'redirect_uri' not in params:
raise TypeError('Missing parameter redirect_uri in URL query')
return self.get_authorization_code(**params)
except TypeError as exc:
self._handle_exception(exc)
# Catch missing parameters in request
err = 'invalid_request'
if 'redirect_uri' in params:
u = params['redirect_uri']
return self._make_redirect_error_response(u, err)
else:
return self._invalid_redirect_uri_response()
except StandardError as exc:
self._handle_exception(exc)
# Catch all other server errors
err = 'server_error'
u = params['redirect_uri']
return self._make_redirect_error_response(u, err)
|
[
"Get",
"authorization",
"code",
"response",
"from",
"a",
"URI",
".",
"This",
"method",
"will",
"ignore",
"the",
"domain",
"and",
"path",
"of",
"the",
"request",
"instead",
"automatically",
"parsing",
"the",
"query",
"string",
"parameters",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L412-L449
|
[
"def",
"get_authorization_code_from_uri",
"(",
"self",
",",
"uri",
")",
":",
"params",
"=",
"utils",
".",
"url_query_params",
"(",
"uri",
")",
"try",
":",
"if",
"'response_type'",
"not",
"in",
"params",
":",
"raise",
"TypeError",
"(",
"'Missing parameter response_type in URL query'",
")",
"if",
"'client_id'",
"not",
"in",
"params",
":",
"raise",
"TypeError",
"(",
"'Missing parameter client_id in URL query'",
")",
"if",
"'redirect_uri'",
"not",
"in",
"params",
":",
"raise",
"TypeError",
"(",
"'Missing parameter redirect_uri in URL query'",
")",
"return",
"self",
".",
"get_authorization_code",
"(",
"*",
"*",
"params",
")",
"except",
"TypeError",
"as",
"exc",
":",
"self",
".",
"_handle_exception",
"(",
"exc",
")",
"# Catch missing parameters in request",
"err",
"=",
"'invalid_request'",
"if",
"'redirect_uri'",
"in",
"params",
":",
"u",
"=",
"params",
"[",
"'redirect_uri'",
"]",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"u",
",",
"err",
")",
"else",
":",
"return",
"self",
".",
"_invalid_redirect_uri_response",
"(",
")",
"except",
"StandardError",
"as",
"exc",
":",
"self",
".",
"_handle_exception",
"(",
"exc",
")",
"# Catch all other server errors",
"err",
"=",
"'server_error'",
"u",
"=",
"params",
"[",
"'redirect_uri'",
"]",
"return",
"self",
".",
"_make_redirect_error_response",
"(",
"u",
",",
"err",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
AuthorizationProvider.get_token_from_post_data
|
Get a token response from POST data.
:param data: POST data containing authorization information.
:type data: dict
:rtype: requests.Response
|
oauth2lib/provider.py
|
def get_token_from_post_data(self, data):
"""Get a token response from POST data.
:param data: POST data containing authorization information.
:type data: dict
:rtype: requests.Response
"""
try:
# Verify OAuth 2.0 Parameters
for x in ['grant_type', 'client_id', 'client_secret']:
if not data.get(x):
raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
# Handle get token from refresh_token
if 'refresh_token' in data:
return self.refresh_token(**data)
# Handle get token from authorization code
for x in ['redirect_uri', 'code']:
if not data.get(x):
raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
return self.get_token(**data)
except TypeError as exc:
self._handle_exception(exc)
# Catch missing parameters in request
return self._make_json_error_response('invalid_request')
except StandardError as exc:
self._handle_exception(exc)
# Catch all other server errors
return self._make_json_error_response('server_error')
|
def get_token_from_post_data(self, data):
"""Get a token response from POST data.
:param data: POST data containing authorization information.
:type data: dict
:rtype: requests.Response
"""
try:
# Verify OAuth 2.0 Parameters
for x in ['grant_type', 'client_id', 'client_secret']:
if not data.get(x):
raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
# Handle get token from refresh_token
if 'refresh_token' in data:
return self.refresh_token(**data)
# Handle get token from authorization code
for x in ['redirect_uri', 'code']:
if not data.get(x):
raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
return self.get_token(**data)
except TypeError as exc:
self._handle_exception(exc)
# Catch missing parameters in request
return self._make_json_error_response('invalid_request')
except StandardError as exc:
self._handle_exception(exc)
# Catch all other server errors
return self._make_json_error_response('server_error')
|
[
"Get",
"a",
"token",
"response",
"from",
"POST",
"data",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L451-L482
|
[
"def",
"get_token_from_post_data",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"# Verify OAuth 2.0 Parameters",
"for",
"x",
"in",
"[",
"'grant_type'",
",",
"'client_id'",
",",
"'client_secret'",
"]",
":",
"if",
"not",
"data",
".",
"get",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"Missing required OAuth 2.0 POST param: {0}\"",
".",
"format",
"(",
"x",
")",
")",
"# Handle get token from refresh_token",
"if",
"'refresh_token'",
"in",
"data",
":",
"return",
"self",
".",
"refresh_token",
"(",
"*",
"*",
"data",
")",
"# Handle get token from authorization code",
"for",
"x",
"in",
"[",
"'redirect_uri'",
",",
"'code'",
"]",
":",
"if",
"not",
"data",
".",
"get",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"Missing required OAuth 2.0 POST param: {0}\"",
".",
"format",
"(",
"x",
")",
")",
"return",
"self",
".",
"get_token",
"(",
"*",
"*",
"data",
")",
"except",
"TypeError",
"as",
"exc",
":",
"self",
".",
"_handle_exception",
"(",
"exc",
")",
"# Catch missing parameters in request",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'invalid_request'",
")",
"except",
"StandardError",
"as",
"exc",
":",
"self",
".",
"_handle_exception",
"(",
"exc",
")",
"# Catch all other server errors",
"return",
"self",
".",
"_make_json_error_response",
"(",
"'server_error'",
")"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
ResourceProvider.get_authorization
|
Get authorization object representing status of authentication.
|
oauth2lib/provider.py
|
def get_authorization(self):
"""Get authorization object representing status of authentication."""
auth = self.authorization_class()
header = self.get_authorization_header()
if not header or not header.split:
return auth
header = header.split()
if len(header) > 1 and header[0] == 'Bearer':
auth.is_oauth = True
access_token = header[1]
self.validate_access_token(access_token, auth)
if not auth.is_valid:
auth.error = 'access_denied'
return auth
|
def get_authorization(self):
"""Get authorization object representing status of authentication."""
auth = self.authorization_class()
header = self.get_authorization_header()
if not header or not header.split:
return auth
header = header.split()
if len(header) > 1 and header[0] == 'Bearer':
auth.is_oauth = True
access_token = header[1]
self.validate_access_token(access_token, auth)
if not auth.is_valid:
auth.error = 'access_denied'
return auth
|
[
"Get",
"authorization",
"object",
"representing",
"status",
"of",
"authentication",
"."
] |
NateFerrero/oauth2lib
|
python
|
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L573-L586
|
[
"def",
"get_authorization",
"(",
"self",
")",
":",
"auth",
"=",
"self",
".",
"authorization_class",
"(",
")",
"header",
"=",
"self",
".",
"get_authorization_header",
"(",
")",
"if",
"not",
"header",
"or",
"not",
"header",
".",
"split",
":",
"return",
"auth",
"header",
"=",
"header",
".",
"split",
"(",
")",
"if",
"len",
"(",
"header",
")",
">",
"1",
"and",
"header",
"[",
"0",
"]",
"==",
"'Bearer'",
":",
"auth",
".",
"is_oauth",
"=",
"True",
"access_token",
"=",
"header",
"[",
"1",
"]",
"self",
".",
"validate_access_token",
"(",
"access_token",
",",
"auth",
")",
"if",
"not",
"auth",
".",
"is_valid",
":",
"auth",
".",
"error",
"=",
"'access_denied'",
"return",
"auth"
] |
d161b010f8a596826050a09e5e94d59443cc12d9
|
test
|
make_i2c_rdwr_data
|
Utility function to create and return an i2c_rdwr_ioctl_data structure
populated with a list of specified I2C messages. The messages parameter
should be a list of tuples which represent the individual I2C messages to
send in this transaction. Tuples should contain 4 elements: address value,
flags value, buffer length, ctypes c_uint8 pointer to buffer.
|
Adafruit_PureIO/smbus.py
|
def make_i2c_rdwr_data(messages):
"""Utility function to create and return an i2c_rdwr_ioctl_data structure
populated with a list of specified I2C messages. The messages parameter
should be a list of tuples which represent the individual I2C messages to
send in this transaction. Tuples should contain 4 elements: address value,
flags value, buffer length, ctypes c_uint8 pointer to buffer.
"""
# Create message array and populate with provided data.
msg_data_type = i2c_msg*len(messages)
msg_data = msg_data_type()
for i, message in enumerate(messages):
msg_data[i].addr = message[0] & 0x7F
msg_data[i].flags = message[1]
msg_data[i].len = message[2]
msg_data[i].buf = message[3]
# Now build the data structure.
data = i2c_rdwr_ioctl_data()
data.msgs = msg_data
data.nmsgs = len(messages)
return data
|
def make_i2c_rdwr_data(messages):
"""Utility function to create and return an i2c_rdwr_ioctl_data structure
populated with a list of specified I2C messages. The messages parameter
should be a list of tuples which represent the individual I2C messages to
send in this transaction. Tuples should contain 4 elements: address value,
flags value, buffer length, ctypes c_uint8 pointer to buffer.
"""
# Create message array and populate with provided data.
msg_data_type = i2c_msg*len(messages)
msg_data = msg_data_type()
for i, message in enumerate(messages):
msg_data[i].addr = message[0] & 0x7F
msg_data[i].flags = message[1]
msg_data[i].len = message[2]
msg_data[i].buf = message[3]
# Now build the data structure.
data = i2c_rdwr_ioctl_data()
data.msgs = msg_data
data.nmsgs = len(messages)
return data
|
[
"Utility",
"function",
"to",
"create",
"and",
"return",
"an",
"i2c_rdwr_ioctl_data",
"structure",
"populated",
"with",
"a",
"list",
"of",
"specified",
"I2C",
"messages",
".",
"The",
"messages",
"parameter",
"should",
"be",
"a",
"list",
"of",
"tuples",
"which",
"represent",
"the",
"individual",
"I2C",
"messages",
"to",
"send",
"in",
"this",
"transaction",
".",
"Tuples",
"should",
"contain",
"4",
"elements",
":",
"address",
"value",
"flags",
"value",
"buffer",
"length",
"ctypes",
"c_uint8",
"pointer",
"to",
"buffer",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L70-L89
|
[
"def",
"make_i2c_rdwr_data",
"(",
"messages",
")",
":",
"# Create message array and populate with provided data.",
"msg_data_type",
"=",
"i2c_msg",
"*",
"len",
"(",
"messages",
")",
"msg_data",
"=",
"msg_data_type",
"(",
")",
"for",
"i",
",",
"message",
"in",
"enumerate",
"(",
"messages",
")",
":",
"msg_data",
"[",
"i",
"]",
".",
"addr",
"=",
"message",
"[",
"0",
"]",
"&",
"0x7F",
"msg_data",
"[",
"i",
"]",
".",
"flags",
"=",
"message",
"[",
"1",
"]",
"msg_data",
"[",
"i",
"]",
".",
"len",
"=",
"message",
"[",
"2",
"]",
"msg_data",
"[",
"i",
"]",
".",
"buf",
"=",
"message",
"[",
"3",
"]",
"# Now build the data structure.",
"data",
"=",
"i2c_rdwr_ioctl_data",
"(",
")",
"data",
".",
"msgs",
"=",
"msg_data",
"data",
".",
"nmsgs",
"=",
"len",
"(",
"messages",
")",
"return",
"data"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.open
|
Open the smbus interface on the specified bus.
|
Adafruit_PureIO/smbus.py
|
def open(self, bus):
"""Open the smbus interface on the specified bus."""
# Close the device if it's already open.
if self._device is not None:
self.close()
# Try to open the file for the specified bus. Must turn off buffering
# or else Python 3 fails (see: https://bugs.python.org/issue20074)
self._device = open('/dev/i2c-{0}'.format(bus), 'r+b', buffering=0)
|
def open(self, bus):
"""Open the smbus interface on the specified bus."""
# Close the device if it's already open.
if self._device is not None:
self.close()
# Try to open the file for the specified bus. Must turn off buffering
# or else Python 3 fails (see: https://bugs.python.org/issue20074)
self._device = open('/dev/i2c-{0}'.format(bus), 'r+b', buffering=0)
|
[
"Open",
"the",
"smbus",
"interface",
"on",
"the",
"specified",
"bus",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L123-L130
|
[
"def",
"open",
"(",
"self",
",",
"bus",
")",
":",
"# Close the device if it's already open.",
"if",
"self",
".",
"_device",
"is",
"not",
"None",
":",
"self",
".",
"close",
"(",
")",
"# Try to open the file for the specified bus. Must turn off buffering",
"# or else Python 3 fails (see: https://bugs.python.org/issue20074)",
"self",
".",
"_device",
"=",
"open",
"(",
"'/dev/i2c-{0}'",
".",
"format",
"(",
"bus",
")",
",",
"'r+b'",
",",
"buffering",
"=",
"0",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.read_byte
|
Read a single byte from the specified device.
|
Adafruit_PureIO/smbus.py
|
def read_byte(self, addr):
"""Read a single byte from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return ord(self._device.read(1))
|
def read_byte(self, addr):
"""Read a single byte from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return ord(self._device.read(1))
|
[
"Read",
"a",
"single",
"byte",
"from",
"the",
"specified",
"device",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L145-L149
|
[
"def",
"read_byte",
"(",
"self",
",",
"addr",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"self",
".",
"_select_device",
"(",
"addr",
")",
"return",
"ord",
"(",
"self",
".",
"_device",
".",
"read",
"(",
"1",
")",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.read_bytes
|
Read many bytes from the specified device.
|
Adafruit_PureIO/smbus.py
|
def read_bytes(self, addr, number):
"""Read many bytes from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return self._device.read(number)
|
def read_bytes(self, addr, number):
"""Read many bytes from the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
return self._device.read(number)
|
[
"Read",
"many",
"bytes",
"from",
"the",
"specified",
"device",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L151-L155
|
[
"def",
"read_bytes",
"(",
"self",
",",
"addr",
",",
"number",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"self",
".",
"_select_device",
"(",
"addr",
")",
"return",
"self",
".",
"_device",
".",
"read",
"(",
"number",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.read_byte_data
|
Read a single byte from the specified cmd register of the device.
|
Adafruit_PureIO/smbus.py
|
def read_byte_data(self, addr, cmd):
"""Read a single byte from the specified cmd register of the device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = c_uint8()
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, 1, pointer(result)) # Read 1 byte as result.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return result.value
|
def read_byte_data(self, addr, cmd):
"""Read a single byte from the specified cmd register of the device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = c_uint8()
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, 1, pointer(result)) # Read 1 byte as result.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return result.value
|
[
"Read",
"a",
"single",
"byte",
"from",
"the",
"specified",
"cmd",
"register",
"of",
"the",
"device",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L157-L170
|
[
"def",
"read_byte_data",
"(",
"self",
",",
"addr",
",",
"cmd",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"# Build ctypes values to marshall between ioctl and Python.",
"reg",
"=",
"c_uint8",
"(",
"cmd",
")",
"result",
"=",
"c_uint8",
"(",
")",
"# Build ioctl request.",
"request",
"=",
"make_i2c_rdwr_data",
"(",
"[",
"(",
"addr",
",",
"0",
",",
"1",
",",
"pointer",
"(",
"reg",
")",
")",
",",
"# Write cmd register.",
"(",
"addr",
",",
"I2C_M_RD",
",",
"1",
",",
"pointer",
"(",
"result",
")",
")",
"# Read 1 byte as result.",
"]",
")",
"# Make ioctl call and return result data.",
"ioctl",
"(",
"self",
".",
"_device",
".",
"fileno",
"(",
")",
",",
"I2C_RDWR",
",",
"request",
")",
"return",
"result",
".",
"value"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.read_word_data
|
Read a word (2 bytes) from the specified cmd register of the device.
Note that this will interpret data using the endianness of the processor
running Python (typically little endian)!
|
Adafruit_PureIO/smbus.py
|
def read_word_data(self, addr, cmd):
"""Read a word (2 bytes) from the specified cmd register of the device.
Note that this will interpret data using the endianness of the processor
running Python (typically little endian)!
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = c_uint16()
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, 2, cast(pointer(result), POINTER(c_uint8))) # Read word (2 bytes).
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return result.value
|
def read_word_data(self, addr, cmd):
"""Read a word (2 bytes) from the specified cmd register of the device.
Note that this will interpret data using the endianness of the processor
running Python (typically little endian)!
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = c_uint16()
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, 2, cast(pointer(result), POINTER(c_uint8))) # Read word (2 bytes).
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return result.value
|
[
"Read",
"a",
"word",
"(",
"2",
"bytes",
")",
"from",
"the",
"specified",
"cmd",
"register",
"of",
"the",
"device",
".",
"Note",
"that",
"this",
"will",
"interpret",
"data",
"using",
"the",
"endianness",
"of",
"the",
"processor",
"running",
"Python",
"(",
"typically",
"little",
"endian",
")",
"!"
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L172-L188
|
[
"def",
"read_word_data",
"(",
"self",
",",
"addr",
",",
"cmd",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"# Build ctypes values to marshall between ioctl and Python.",
"reg",
"=",
"c_uint8",
"(",
"cmd",
")",
"result",
"=",
"c_uint16",
"(",
")",
"# Build ioctl request.",
"request",
"=",
"make_i2c_rdwr_data",
"(",
"[",
"(",
"addr",
",",
"0",
",",
"1",
",",
"pointer",
"(",
"reg",
")",
")",
",",
"# Write cmd register.",
"(",
"addr",
",",
"I2C_M_RD",
",",
"2",
",",
"cast",
"(",
"pointer",
"(",
"result",
")",
",",
"POINTER",
"(",
"c_uint8",
")",
")",
")",
"# Read word (2 bytes).",
"]",
")",
"# Make ioctl call and return result data.",
"ioctl",
"(",
"self",
".",
"_device",
".",
"fileno",
"(",
")",
",",
"I2C_RDWR",
",",
"request",
")",
"return",
"result",
".",
"value"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.read_i2c_block_data
|
Perform a read from the specified cmd register of device. Length number
of bytes (default of 32) will be read and returned as a bytearray.
|
Adafruit_PureIO/smbus.py
|
def read_i2c_block_data(self, addr, cmd, length=32):
"""Perform a read from the specified cmd register of device. Length number
of bytes (default of 32) will be read and returned as a bytearray.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = create_string_buffer(length)
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, length, cast(result, POINTER(c_uint8))) # Read data.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return bytearray(result.raw)
|
def read_i2c_block_data(self, addr, cmd, length=32):
"""Perform a read from the specified cmd register of device. Length number
of bytes (default of 32) will be read and returned as a bytearray.
"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ctypes values to marshall between ioctl and Python.
reg = c_uint8(cmd)
result = create_string_buffer(length)
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 1, pointer(reg)), # Write cmd register.
(addr, I2C_M_RD, length, cast(result, POINTER(c_uint8))) # Read data.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
return bytearray(result.raw)
|
[
"Perform",
"a",
"read",
"from",
"the",
"specified",
"cmd",
"register",
"of",
"device",
".",
"Length",
"number",
"of",
"bytes",
"(",
"default",
"of",
"32",
")",
"will",
"be",
"read",
"and",
"returned",
"as",
"a",
"bytearray",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L201-L216
|
[
"def",
"read_i2c_block_data",
"(",
"self",
",",
"addr",
",",
"cmd",
",",
"length",
"=",
"32",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"# Build ctypes values to marshall between ioctl and Python.",
"reg",
"=",
"c_uint8",
"(",
"cmd",
")",
"result",
"=",
"create_string_buffer",
"(",
"length",
")",
"# Build ioctl request.",
"request",
"=",
"make_i2c_rdwr_data",
"(",
"[",
"(",
"addr",
",",
"0",
",",
"1",
",",
"pointer",
"(",
"reg",
")",
")",
",",
"# Write cmd register.",
"(",
"addr",
",",
"I2C_M_RD",
",",
"length",
",",
"cast",
"(",
"result",
",",
"POINTER",
"(",
"c_uint8",
")",
")",
")",
"# Read data.",
"]",
")",
"# Make ioctl call and return result data.",
"ioctl",
"(",
"self",
".",
"_device",
".",
"fileno",
"(",
")",
",",
"I2C_RDWR",
",",
"request",
")",
"return",
"bytearray",
"(",
"result",
".",
"raw",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.write_quick
|
Write a single byte to the specified device.
|
Adafruit_PureIO/smbus.py
|
def write_quick(self, addr):
"""Write a single byte to the specified device."""
# What a strange function, from the python-smbus source this appears to
# just write a single byte that initiates a write to the specified device
# address (but writes no data!). The functionality is duplicated below
# but the actual use case for this is unknown.
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 0, None), # Write with no data.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
|
def write_quick(self, addr):
"""Write a single byte to the specified device."""
# What a strange function, from the python-smbus source this appears to
# just write a single byte that initiates a write to the specified device
# address (but writes no data!). The functionality is duplicated below
# but the actual use case for this is unknown.
assert self._device is not None, 'Bus must be opened before operations are made against it!'
# Build ioctl request.
request = make_i2c_rdwr_data([
(addr, 0, 0, None), # Write with no data.
])
# Make ioctl call and return result data.
ioctl(self._device.fileno(), I2C_RDWR, request)
|
[
"Write",
"a",
"single",
"byte",
"to",
"the",
"specified",
"device",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L218-L230
|
[
"def",
"write_quick",
"(",
"self",
",",
"addr",
")",
":",
"# What a strange function, from the python-smbus source this appears to",
"# just write a single byte that initiates a write to the specified device",
"# address (but writes no data!). The functionality is duplicated below",
"# but the actual use case for this is unknown.",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"# Build ioctl request.",
"request",
"=",
"make_i2c_rdwr_data",
"(",
"[",
"(",
"addr",
",",
"0",
",",
"0",
",",
"None",
")",
",",
"# Write with no data.",
"]",
")",
"# Make ioctl call and return result data.",
"ioctl",
"(",
"self",
".",
"_device",
".",
"fileno",
"(",
")",
",",
"I2C_RDWR",
",",
"request",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.write_byte
|
Write a single byte to the specified device.
|
Adafruit_PureIO/smbus.py
|
def write_byte(self, addr, val):
"""Write a single byte to the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
data = bytearray(1)
data[0] = val & 0xFF
self._device.write(data)
|
def write_byte(self, addr, val):
"""Write a single byte to the specified device."""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
data = bytearray(1)
data[0] = val & 0xFF
self._device.write(data)
|
[
"Write",
"a",
"single",
"byte",
"to",
"the",
"specified",
"device",
"."
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L232-L238
|
[
"def",
"write_byte",
"(",
"self",
",",
"addr",
",",
"val",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"self",
".",
"_select_device",
"(",
"addr",
")",
"data",
"=",
"bytearray",
"(",
"1",
")",
"data",
"[",
"0",
"]",
"=",
"val",
"&",
"0xFF",
"self",
".",
"_device",
".",
"write",
"(",
"data",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
test
|
SMBus.write_bytes
|
Write many bytes to the specified device. buf is a bytearray
|
Adafruit_PureIO/smbus.py
|
def write_bytes(self, addr, buf):
"""Write many bytes to the specified device. buf is a bytearray"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
self._device.write(buf)
|
def write_bytes(self, addr, buf):
"""Write many bytes to the specified device. buf is a bytearray"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
self._device.write(buf)
|
[
"Write",
"many",
"bytes",
"to",
"the",
"specified",
"device",
".",
"buf",
"is",
"a",
"bytearray"
] |
adafruit/Adafruit_Python_PureIO
|
python
|
https://github.com/adafruit/Adafruit_Python_PureIO/blob/6f4976d91c52d70b67b28bba75a429b5328a52c1/Adafruit_PureIO/smbus.py#L240-L244
|
[
"def",
"write_bytes",
"(",
"self",
",",
"addr",
",",
"buf",
")",
":",
"assert",
"self",
".",
"_device",
"is",
"not",
"None",
",",
"'Bus must be opened before operations are made against it!'",
"self",
".",
"_select_device",
"(",
"addr",
")",
"self",
".",
"_device",
".",
"write",
"(",
"buf",
")"
] |
6f4976d91c52d70b67b28bba75a429b5328a52c1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.