repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ethereum/eth-abi | eth_abi/decoding.py | ContextFramesBytesIO.seek_in_frame | def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) | python | def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) | [
"def",
"seek_in_frame",
"(",
"self",
",",
"pos",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"seek",
"(",
"self",
".",
"_total_offset",
"+",
"pos",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Seeks relative to the total offset of the current contextual frames. | [
"Seeks",
"relative",
"to",
"the",
"total",
"offset",
"of",
"the",
"current",
"contextual",
"frames",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/decoding.py#L80-L84 | train | 235,100 |
ethereum/eth-abi | eth_abi/decoding.py | ContextFramesBytesIO.push_frame | def push_frame(self, offset):
"""
Pushes a new contextual frame onto the stack with the given offset and a
return position at the current cursor position then seeks to the new
total offset.
"""
self._frames.append((offset, self.tell()))
self._total_offset += offset
self.seek_in_frame(0) | python | def push_frame(self, offset):
"""
Pushes a new contextual frame onto the stack with the given offset and a
return position at the current cursor position then seeks to the new
total offset.
"""
self._frames.append((offset, self.tell()))
self._total_offset += offset
self.seek_in_frame(0) | [
"def",
"push_frame",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"_frames",
".",
"append",
"(",
"(",
"offset",
",",
"self",
".",
"tell",
"(",
")",
")",
")",
"self",
".",
"_total_offset",
"+=",
"offset",
"self",
".",
"seek_in_frame",
"(",
"0",
")"
] | Pushes a new contextual frame onto the stack with the given offset and a
return position at the current cursor position then seeks to the new
total offset. | [
"Pushes",
"a",
"new",
"contextual",
"frame",
"onto",
"the",
"stack",
"with",
"the",
"given",
"offset",
"and",
"a",
"return",
"position",
"at",
"the",
"current",
"cursor",
"position",
"then",
"seeks",
"to",
"the",
"new",
"total",
"offset",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/decoding.py#L86-L95 | train | 235,101 |
ethereum/eth-abi | eth_abi/decoding.py | ContextFramesBytesIO.pop_frame | def pop_frame(self):
"""
Pops the current contextual frame off of the stack and returns the
cursor to the frame's return position.
"""
try:
offset, return_pos = self._frames.pop()
except IndexError:
raise IndexError('no frames to pop')
self._total_offset -= offset
self.seek(return_pos) | python | def pop_frame(self):
"""
Pops the current contextual frame off of the stack and returns the
cursor to the frame's return position.
"""
try:
offset, return_pos = self._frames.pop()
except IndexError:
raise IndexError('no frames to pop')
self._total_offset -= offset
self.seek(return_pos) | [
"def",
"pop_frame",
"(",
"self",
")",
":",
"try",
":",
"offset",
",",
"return_pos",
"=",
"self",
".",
"_frames",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"raise",
"IndexError",
"(",
"'no frames to pop'",
")",
"self",
".",
"_total_offset",
"-=",
"offset",
"self",
".",
"seek",
"(",
"return_pos",
")"
] | Pops the current contextual frame off of the stack and returns the
cursor to the frame's return position. | [
"Pops",
"the",
"current",
"contextual",
"frame",
"off",
"of",
"the",
"stack",
"and",
"returns",
"the",
"cursor",
"to",
"the",
"frame",
"s",
"return",
"position",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/decoding.py#L97-L108 | train | 235,102 |
ethereum/eth-abi | eth_abi/registry.py | has_arrlist | def has_arrlist(type_str):
"""
A predicate that matches a type string with an array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return abi_type.arrlist is not None | python | def has_arrlist(type_str):
"""
A predicate that matches a type string with an array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return abi_type.arrlist is not None | [
"def",
"has_arrlist",
"(",
"type_str",
")",
":",
"try",
":",
"abi_type",
"=",
"grammar",
".",
"parse",
"(",
"type_str",
")",
"except",
"exceptions",
".",
"ParseError",
":",
"return",
"False",
"return",
"abi_type",
".",
"arrlist",
"is",
"not",
"None"
] | A predicate that matches a type string with an array dimension list. | [
"A",
"predicate",
"that",
"matches",
"a",
"type",
"string",
"with",
"an",
"array",
"dimension",
"list",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L258-L267 | train | 235,103 |
ethereum/eth-abi | eth_abi/registry.py | is_base_tuple | def is_base_tuple(type_str):
"""
A predicate that matches a tuple type with no array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return isinstance(abi_type, grammar.TupleType) and abi_type.arrlist is None | python | def is_base_tuple(type_str):
"""
A predicate that matches a tuple type with no array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return isinstance(abi_type, grammar.TupleType) and abi_type.arrlist is None | [
"def",
"is_base_tuple",
"(",
"type_str",
")",
":",
"try",
":",
"abi_type",
"=",
"grammar",
".",
"parse",
"(",
"type_str",
")",
"except",
"exceptions",
".",
"ParseError",
":",
"return",
"False",
"return",
"isinstance",
"(",
"abi_type",
",",
"grammar",
".",
"TupleType",
")",
"and",
"abi_type",
".",
"arrlist",
"is",
"None"
] | A predicate that matches a tuple type with no array dimension list. | [
"A",
"predicate",
"that",
"matches",
"a",
"tuple",
"type",
"with",
"no",
"array",
"dimension",
"list",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L270-L279 | train | 235,104 |
ethereum/eth-abi | eth_abi/registry.py | ABIRegistry.register | def register(self, lookup: Lookup, encoder: Encoder, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
:param lookup: A type string or type string matcher function
(predicate). When the registry is queried with a type string
``query`` to determine which encoder or decoder to use, ``query``
will be checked against every registration in the registry. If a
registration was created with a type string for ``lookup``, it will
be considered a match if ``lookup == query``. If a registration
was created with a matcher function for ``lookup``, it will be
considered a match if ``lookup(query) is True``. If more than one
registration is found to be a match, then an exception is raised.
:param encoder: An encoder callable or class to use if ``lookup``
matches a query. If ``encoder`` is a callable, it must accept a
python value and return a ``bytes`` value. If ``encoder`` is a
class, it must be a valid subclass of :any:`encoding.BaseEncoder`
and must also implement the :any:`from_type_str` method on
:any:`base.BaseCoder`.
:param decoder: A decoder callable or class to use if ``lookup``
matches a query. If ``decoder`` is a callable, it must accept a
stream-like object of bytes and return a python value. If
``decoder`` is a class, it must be a valid subclass of
:any:`decoding.BaseDecoder` and must also implement the
:any:`from_type_str` method on :any:`base.BaseCoder`.
:param label: An optional label that can be used to refer to this
registration by name. This label can be used to unregister an
entry in the registry via the :any:`unregister` method and its
variants.
"""
self.register_encoder(lookup, encoder, label=label)
self.register_decoder(lookup, decoder, label=label) | python | def register(self, lookup: Lookup, encoder: Encoder, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
:param lookup: A type string or type string matcher function
(predicate). When the registry is queried with a type string
``query`` to determine which encoder or decoder to use, ``query``
will be checked against every registration in the registry. If a
registration was created with a type string for ``lookup``, it will
be considered a match if ``lookup == query``. If a registration
was created with a matcher function for ``lookup``, it will be
considered a match if ``lookup(query) is True``. If more than one
registration is found to be a match, then an exception is raised.
:param encoder: An encoder callable or class to use if ``lookup``
matches a query. If ``encoder`` is a callable, it must accept a
python value and return a ``bytes`` value. If ``encoder`` is a
class, it must be a valid subclass of :any:`encoding.BaseEncoder`
and must also implement the :any:`from_type_str` method on
:any:`base.BaseCoder`.
:param decoder: A decoder callable or class to use if ``lookup``
matches a query. If ``decoder`` is a callable, it must accept a
stream-like object of bytes and return a python value. If
``decoder`` is a class, it must be a valid subclass of
:any:`decoding.BaseDecoder` and must also implement the
:any:`from_type_str` method on :any:`base.BaseCoder`.
:param label: An optional label that can be used to refer to this
registration by name. This label can be used to unregister an
entry in the registry via the :any:`unregister` method and its
variants.
"""
self.register_encoder(lookup, encoder, label=label)
self.register_decoder(lookup, decoder, label=label) | [
"def",
"register",
"(",
"self",
",",
"lookup",
":",
"Lookup",
",",
"encoder",
":",
"Encoder",
",",
"decoder",
":",
"Decoder",
",",
"label",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"register_encoder",
"(",
"lookup",
",",
"encoder",
",",
"label",
"=",
"label",
")",
"self",
".",
"register_decoder",
"(",
"lookup",
",",
"decoder",
",",
"label",
"=",
"label",
")"
] | Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
:param lookup: A type string or type string matcher function
(predicate). When the registry is queried with a type string
``query`` to determine which encoder or decoder to use, ``query``
will be checked against every registration in the registry. If a
registration was created with a type string for ``lookup``, it will
be considered a match if ``lookup == query``. If a registration
was created with a matcher function for ``lookup``, it will be
considered a match if ``lookup(query) is True``. If more than one
registration is found to be a match, then an exception is raised.
:param encoder: An encoder callable or class to use if ``lookup``
matches a query. If ``encoder`` is a callable, it must accept a
python value and return a ``bytes`` value. If ``encoder`` is a
class, it must be a valid subclass of :any:`encoding.BaseEncoder`
and must also implement the :any:`from_type_str` method on
:any:`base.BaseCoder`.
:param decoder: A decoder callable or class to use if ``lookup``
matches a query. If ``decoder`` is a callable, it must accept a
stream-like object of bytes and return a python value. If
``decoder`` is a class, it must be a valid subclass of
:any:`decoding.BaseDecoder` and must also implement the
:any:`from_type_str` method on :any:`base.BaseCoder`.
:param label: An optional label that can be used to refer to this
registration by name. This label can be used to unregister an
entry in the registry via the :any:`unregister` method and its
variants. | [
"Registers",
"the",
"given",
"encoder",
"and",
"decoder",
"under",
"the",
"given",
"lookup",
".",
"A",
"unique",
"string",
"label",
"may",
"be",
"optionally",
"provided",
"that",
"can",
"be",
"used",
"to",
"refer",
"to",
"the",
"registration",
"by",
"name",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L395-L431 | train | 235,105 |
ethereum/eth-abi | eth_abi/registry.py | ABIRegistry.unregister | def unregister(self, label: str) -> None:
"""
Unregisters the entries in the encoder and decoder registries which
have the label ``label``.
"""
self.unregister_encoder(label)
self.unregister_decoder(label) | python | def unregister(self, label: str) -> None:
"""
Unregisters the entries in the encoder and decoder registries which
have the label ``label``.
"""
self.unregister_encoder(label)
self.unregister_decoder(label) | [
"def",
"unregister",
"(",
"self",
",",
"label",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"unregister_encoder",
"(",
"label",
")",
"self",
".",
"unregister_decoder",
"(",
"label",
")"
] | Unregisters the entries in the encoder and decoder registries which
have the label ``label``. | [
"Unregisters",
"the",
"entries",
"in",
"the",
"encoder",
"and",
"decoder",
"registries",
"which",
"have",
"the",
"label",
"label",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L433-L439 | train | 235,106 |
ethereum/eth-abi | eth_abi/registry.py | ABIRegistry.copy | def copy(self):
"""
Copies a registry such that new registrations can be made or existing
registrations can be unregistered without affecting any instance from
which a copy was obtained. This is useful if an existing registry
fulfills most of a user's needs but requires one or two modifications.
In that case, a copy of that registry can be obtained and the necessary
changes made without affecting the original registry.
"""
cpy = type(self)()
cpy._encoders = copy.copy(self._encoders)
cpy._decoders = copy.copy(self._decoders)
return cpy | python | def copy(self):
"""
Copies a registry such that new registrations can be made or existing
registrations can be unregistered without affecting any instance from
which a copy was obtained. This is useful if an existing registry
fulfills most of a user's needs but requires one or two modifications.
In that case, a copy of that registry can be obtained and the necessary
changes made without affecting the original registry.
"""
cpy = type(self)()
cpy._encoders = copy.copy(self._encoders)
cpy._decoders = copy.copy(self._decoders)
return cpy | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"type",
"(",
"self",
")",
"(",
")",
"cpy",
".",
"_encoders",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_encoders",
")",
"cpy",
".",
"_decoders",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_decoders",
")",
"return",
"cpy"
] | Copies a registry such that new registrations can be made or existing
registrations can be unregistered without affecting any instance from
which a copy was obtained. This is useful if an existing registry
fulfills most of a user's needs but requires one or two modifications.
In that case, a copy of that registry can be obtained and the necessary
changes made without affecting the original registry. | [
"Copies",
"a",
"registry",
"such",
"that",
"new",
"registrations",
"can",
"be",
"made",
"or",
"existing",
"registrations",
"can",
"be",
"unregistered",
"without",
"affecting",
"any",
"instance",
"from",
"which",
"a",
"copy",
"was",
"obtained",
".",
"This",
"is",
"useful",
"if",
"an",
"existing",
"registry",
"fulfills",
"most",
"of",
"a",
"user",
"s",
"needs",
"but",
"requires",
"one",
"or",
"two",
"modifications",
".",
"In",
"that",
"case",
"a",
"copy",
"of",
"that",
"registry",
"can",
"be",
"obtained",
"and",
"the",
"necessary",
"changes",
"made",
"without",
"affecting",
"the",
"original",
"registry",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L463-L477 | train | 235,107 |
ethereum/eth-abi | eth_abi/codec.py | ABIEncoder.encode_single | def encode_single(self, typ: TypeStr, arg: Any) -> bytes:
"""
Encodes the python value ``arg`` as a binary value of the ABI type
``typ``.
:param typ: The string representation of the ABI type that will be used
for encoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``,
etc.
:param arg: The python value to be encoded.
:returns: The binary representation of the python value ``arg`` as a
value of the ABI type ``typ``.
"""
encoder = self._registry.get_encoder(typ)
return encoder(arg) | python | def encode_single(self, typ: TypeStr, arg: Any) -> bytes:
"""
Encodes the python value ``arg`` as a binary value of the ABI type
``typ``.
:param typ: The string representation of the ABI type that will be used
for encoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``,
etc.
:param arg: The python value to be encoded.
:returns: The binary representation of the python value ``arg`` as a
value of the ABI type ``typ``.
"""
encoder = self._registry.get_encoder(typ)
return encoder(arg) | [
"def",
"encode_single",
"(",
"self",
",",
"typ",
":",
"TypeStr",
",",
"arg",
":",
"Any",
")",
"->",
"bytes",
":",
"encoder",
"=",
"self",
".",
"_registry",
".",
"get_encoder",
"(",
"typ",
")",
"return",
"encoder",
"(",
"arg",
")"
] | Encodes the python value ``arg`` as a binary value of the ABI type
``typ``.
:param typ: The string representation of the ABI type that will be used
for encoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``,
etc.
:param arg: The python value to be encoded.
:returns: The binary representation of the python value ``arg`` as a
value of the ABI type ``typ``. | [
"Encodes",
"the",
"python",
"value",
"arg",
"as",
"a",
"binary",
"value",
"of",
"the",
"ABI",
"type",
"typ",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L50-L65 | train | 235,108 |
ethereum/eth-abi | eth_abi/codec.py | ABIEncoder.encode_abi | def encode_abi(self, types: Iterable[TypeStr], args: Iterable[Any]) -> bytes:
"""
Encodes the python values in ``args`` as a sequence of binary values of
the ABI types in ``types`` via the head-tail mechanism.
:param types: An iterable of string representations of the ABI types
that will be used for encoding e.g. ``('uint256', 'bytes[]',
'(int,int)')``
:param args: An iterable of python values to be encoded.
:returns: The head-tail encoded binary representation of the python
values in ``args`` as values of the ABI types in ``types``.
"""
encoders = [
self._registry.get_encoder(type_str)
for type_str in types
]
encoder = TupleEncoder(encoders=encoders)
return encoder(args) | python | def encode_abi(self, types: Iterable[TypeStr], args: Iterable[Any]) -> bytes:
"""
Encodes the python values in ``args`` as a sequence of binary values of
the ABI types in ``types`` via the head-tail mechanism.
:param types: An iterable of string representations of the ABI types
that will be used for encoding e.g. ``('uint256', 'bytes[]',
'(int,int)')``
:param args: An iterable of python values to be encoded.
:returns: The head-tail encoded binary representation of the python
values in ``args`` as values of the ABI types in ``types``.
"""
encoders = [
self._registry.get_encoder(type_str)
for type_str in types
]
encoder = TupleEncoder(encoders=encoders)
return encoder(args) | [
"def",
"encode_abi",
"(",
"self",
",",
"types",
":",
"Iterable",
"[",
"TypeStr",
"]",
",",
"args",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"bytes",
":",
"encoders",
"=",
"[",
"self",
".",
"_registry",
".",
"get_encoder",
"(",
"type_str",
")",
"for",
"type_str",
"in",
"types",
"]",
"encoder",
"=",
"TupleEncoder",
"(",
"encoders",
"=",
"encoders",
")",
"return",
"encoder",
"(",
"args",
")"
] | Encodes the python values in ``args`` as a sequence of binary values of
the ABI types in ``types`` via the head-tail mechanism.
:param types: An iterable of string representations of the ABI types
that will be used for encoding e.g. ``('uint256', 'bytes[]',
'(int,int)')``
:param args: An iterable of python values to be encoded.
:returns: The head-tail encoded binary representation of the python
values in ``args`` as values of the ABI types in ``types``. | [
"Encodes",
"the",
"python",
"values",
"in",
"args",
"as",
"a",
"sequence",
"of",
"binary",
"values",
"of",
"the",
"ABI",
"types",
"in",
"types",
"via",
"the",
"head",
"-",
"tail",
"mechanism",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L67-L87 | train | 235,109 |
ethereum/eth-abi | eth_abi/codec.py | ABIEncoder.is_encodable | def is_encodable(self, typ: TypeStr, arg: Any) -> bool:
"""
Determines if the python value ``arg`` is encodable as a value of the
ABI type ``typ``.
:param typ: A string representation for the ABI type against which the
python value ``arg`` will be checked e.g. ``'uint256'``,
``'bytes[]'``, ``'(int,int)'``, etc.
:param arg: The python value whose encodability should be checked.
:returns: ``True`` if ``arg`` is encodable as a value of the ABI type
``typ``. Otherwise, ``False``.
"""
encoder = self._registry.get_encoder(typ)
try:
encoder.validate_value(arg)
except EncodingError:
return False
except AttributeError:
try:
encoder(arg)
except EncodingError:
return False
return True | python | def is_encodable(self, typ: TypeStr, arg: Any) -> bool:
"""
Determines if the python value ``arg`` is encodable as a value of the
ABI type ``typ``.
:param typ: A string representation for the ABI type against which the
python value ``arg`` will be checked e.g. ``'uint256'``,
``'bytes[]'``, ``'(int,int)'``, etc.
:param arg: The python value whose encodability should be checked.
:returns: ``True`` if ``arg`` is encodable as a value of the ABI type
``typ``. Otherwise, ``False``.
"""
encoder = self._registry.get_encoder(typ)
try:
encoder.validate_value(arg)
except EncodingError:
return False
except AttributeError:
try:
encoder(arg)
except EncodingError:
return False
return True | [
"def",
"is_encodable",
"(",
"self",
",",
"typ",
":",
"TypeStr",
",",
"arg",
":",
"Any",
")",
"->",
"bool",
":",
"encoder",
"=",
"self",
".",
"_registry",
".",
"get_encoder",
"(",
"typ",
")",
"try",
":",
"encoder",
".",
"validate_value",
"(",
"arg",
")",
"except",
"EncodingError",
":",
"return",
"False",
"except",
"AttributeError",
":",
"try",
":",
"encoder",
"(",
"arg",
")",
"except",
"EncodingError",
":",
"return",
"False",
"return",
"True"
] | Determines if the python value ``arg`` is encodable as a value of the
ABI type ``typ``.
:param typ: A string representation for the ABI type against which the
python value ``arg`` will be checked e.g. ``'uint256'``,
``'bytes[]'``, ``'(int,int)'``, etc.
:param arg: The python value whose encodability should be checked.
:returns: ``True`` if ``arg`` is encodable as a value of the ABI type
``typ``. Otherwise, ``False``. | [
"Determines",
"if",
"the",
"python",
"value",
"arg",
"is",
"encodable",
"as",
"a",
"value",
"of",
"the",
"ABI",
"type",
"typ",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L89-L114 | train | 235,110 |
ethereum/eth-abi | eth_abi/codec.py | ABIDecoder.decode_single | def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""
Decodes the binary value ``data`` of the ABI type ``typ`` into its
equivalent python value.
:param typ: The string representation of the ABI type that will be used for
decoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``, etc.
:param data: The binary value to be decoded.
:returns: The equivalent python value of the ABI value represented in
``data``.
"""
if not is_bytes(data):
raise TypeError("The `data` value must be of bytes type. Got {0}".format(type(data)))
decoder = self._registry.get_decoder(typ)
stream = ContextFramesBytesIO(data)
return decoder(stream) | python | def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""
Decodes the binary value ``data`` of the ABI type ``typ`` into its
equivalent python value.
:param typ: The string representation of the ABI type that will be used for
decoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``, etc.
:param data: The binary value to be decoded.
:returns: The equivalent python value of the ABI value represented in
``data``.
"""
if not is_bytes(data):
raise TypeError("The `data` value must be of bytes type. Got {0}".format(type(data)))
decoder = self._registry.get_decoder(typ)
stream = ContextFramesBytesIO(data)
return decoder(stream) | [
"def",
"decode_single",
"(",
"self",
",",
"typ",
":",
"TypeStr",
",",
"data",
":",
"Decodable",
")",
"->",
"Any",
":",
"if",
"not",
"is_bytes",
"(",
"data",
")",
":",
"raise",
"TypeError",
"(",
"\"The `data` value must be of bytes type. Got {0}\"",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
")",
"decoder",
"=",
"self",
".",
"_registry",
".",
"get_decoder",
"(",
"typ",
")",
"stream",
"=",
"ContextFramesBytesIO",
"(",
"data",
")",
"return",
"decoder",
"(",
"stream",
")"
] | Decodes the binary value ``data`` of the ABI type ``typ`` into its
equivalent python value.
:param typ: The string representation of the ABI type that will be used for
decoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``, etc.
:param data: The binary value to be decoded.
:returns: The equivalent python value of the ABI value represented in
``data``. | [
"Decodes",
"the",
"binary",
"value",
"data",
"of",
"the",
"ABI",
"type",
"typ",
"into",
"its",
"equivalent",
"python",
"value",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L135-L153 | train | 235,111 |
ethereum/eth-abi | eth_abi/codec.py | ABIDecoder.decode_abi | def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of the ABI types that
will be used for decoding e.g. ``('uint256', 'bytes[]', '(int,int)')``
:param data: The binary value to be decoded.
:returns: A tuple of equivalent python values for the ABI values
represented in ``data``.
"""
if not is_bytes(data):
raise TypeError("The `data` value must be of bytes type. Got {0}".format(type(data)))
decoders = [
self._registry.get_decoder(type_str)
for type_str in types
]
decoder = TupleDecoder(decoders=decoders)
stream = ContextFramesBytesIO(data)
return decoder(stream) | python | def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of the ABI types that
will be used for decoding e.g. ``('uint256', 'bytes[]', '(int,int)')``
:param data: The binary value to be decoded.
:returns: A tuple of equivalent python values for the ABI values
represented in ``data``.
"""
if not is_bytes(data):
raise TypeError("The `data` value must be of bytes type. Got {0}".format(type(data)))
decoders = [
self._registry.get_decoder(type_str)
for type_str in types
]
decoder = TupleDecoder(decoders=decoders)
stream = ContextFramesBytesIO(data)
return decoder(stream) | [
"def",
"decode_abi",
"(",
"self",
",",
"types",
":",
"Iterable",
"[",
"TypeStr",
"]",
",",
"data",
":",
"Decodable",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"if",
"not",
"is_bytes",
"(",
"data",
")",
":",
"raise",
"TypeError",
"(",
"\"The `data` value must be of bytes type. Got {0}\"",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
")",
"decoders",
"=",
"[",
"self",
".",
"_registry",
".",
"get_decoder",
"(",
"type_str",
")",
"for",
"type_str",
"in",
"types",
"]",
"decoder",
"=",
"TupleDecoder",
"(",
"decoders",
"=",
"decoders",
")",
"stream",
"=",
"ContextFramesBytesIO",
"(",
"data",
")",
"return",
"decoder",
"(",
"stream",
")"
] | Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of the ABI types that
will be used for decoding e.g. ``('uint256', 'bytes[]', '(int,int)')``
:param data: The binary value to be decoded.
:returns: A tuple of equivalent python values for the ABI values
represented in ``data``. | [
"Decodes",
"the",
"binary",
"value",
"data",
"as",
"a",
"sequence",
"of",
"values",
"of",
"the",
"ABI",
"types",
"in",
"types",
"via",
"the",
"head",
"-",
"tail",
"mechanism",
"into",
"a",
"tuple",
"of",
"equivalent",
"python",
"values",
"."
] | 0a5cab0bdeae30b77efa667379427581784f1707 | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/codec.py#L155-L179 | train | 235,112 |
aiortc/aioice | aioice/turn.py | create_turn_endpoint | async def create_turn_endpoint(protocol_factory, server_addr, username, password,
lifetime=600, ssl=False, transport='udp'):
"""
Create datagram connection relayed over TURN.
"""
loop = asyncio.get_event_loop()
if transport == 'tcp':
_, inner_protocol = await loop.create_connection(
lambda: TurnClientTcpProtocol(server_addr,
username=username,
password=password,
lifetime=lifetime),
host=server_addr[0],
port=server_addr[1],
ssl=ssl)
else:
_, inner_protocol = await loop.create_datagram_endpoint(
lambda: TurnClientUdpProtocol(server_addr,
username=username,
password=password,
lifetime=lifetime),
remote_addr=server_addr)
protocol = protocol_factory()
transport = TurnTransport(protocol, inner_protocol)
await transport._connect()
return transport, protocol | python | async def create_turn_endpoint(protocol_factory, server_addr, username, password,
lifetime=600, ssl=False, transport='udp'):
"""
Create datagram connection relayed over TURN.
"""
loop = asyncio.get_event_loop()
if transport == 'tcp':
_, inner_protocol = await loop.create_connection(
lambda: TurnClientTcpProtocol(server_addr,
username=username,
password=password,
lifetime=lifetime),
host=server_addr[0],
port=server_addr[1],
ssl=ssl)
else:
_, inner_protocol = await loop.create_datagram_endpoint(
lambda: TurnClientUdpProtocol(server_addr,
username=username,
password=password,
lifetime=lifetime),
remote_addr=server_addr)
protocol = protocol_factory()
transport = TurnTransport(protocol, inner_protocol)
await transport._connect()
return transport, protocol | [
"async",
"def",
"create_turn_endpoint",
"(",
"protocol_factory",
",",
"server_addr",
",",
"username",
",",
"password",
",",
"lifetime",
"=",
"600",
",",
"ssl",
"=",
"False",
",",
"transport",
"=",
"'udp'",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"if",
"transport",
"==",
"'tcp'",
":",
"_",
",",
"inner_protocol",
"=",
"await",
"loop",
".",
"create_connection",
"(",
"lambda",
":",
"TurnClientTcpProtocol",
"(",
"server_addr",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"lifetime",
"=",
"lifetime",
")",
",",
"host",
"=",
"server_addr",
"[",
"0",
"]",
",",
"port",
"=",
"server_addr",
"[",
"1",
"]",
",",
"ssl",
"=",
"ssl",
")",
"else",
":",
"_",
",",
"inner_protocol",
"=",
"await",
"loop",
".",
"create_datagram_endpoint",
"(",
"lambda",
":",
"TurnClientUdpProtocol",
"(",
"server_addr",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"lifetime",
"=",
"lifetime",
")",
",",
"remote_addr",
"=",
"server_addr",
")",
"protocol",
"=",
"protocol_factory",
"(",
")",
"transport",
"=",
"TurnTransport",
"(",
"protocol",
",",
"inner_protocol",
")",
"await",
"transport",
".",
"_connect",
"(",
")",
"return",
"transport",
",",
"protocol"
] | Create datagram connection relayed over TURN. | [
"Create",
"datagram",
"connection",
"relayed",
"over",
"TURN",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L276-L303 | train | 235,113 |
aiortc/aioice | aioice/turn.py | TurnClientMixin.connect | async def connect(self):
"""
Create a TURN allocation.
"""
request = stun.Message(message_method=stun.Method.ALLOCATE,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
request.attributes['REQUESTED-TRANSPORT'] = UDP_TRANSPORT
try:
response, _ = await self.request(request)
except exceptions.TransactionFailed as e:
response = e.response
if response.attributes['ERROR-CODE'][0] == 401:
# update long-term credentials
self.nonce = response.attributes['NONCE']
self.realm = response.attributes['REALM']
self.integrity_key = make_integrity_key(self.username, self.realm, self.password)
# retry request with authentication
request.transaction_id = random_transaction_id()
response, _ = await self.request(request)
self.relayed_address = response.attributes['XOR-RELAYED-ADDRESS']
logger.info('TURN allocation created %s', self.relayed_address)
# periodically refresh allocation
self.refresh_handle = asyncio.ensure_future(self.refresh())
return self.relayed_address | python | async def connect(self):
"""
Create a TURN allocation.
"""
request = stun.Message(message_method=stun.Method.ALLOCATE,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
request.attributes['REQUESTED-TRANSPORT'] = UDP_TRANSPORT
try:
response, _ = await self.request(request)
except exceptions.TransactionFailed as e:
response = e.response
if response.attributes['ERROR-CODE'][0] == 401:
# update long-term credentials
self.nonce = response.attributes['NONCE']
self.realm = response.attributes['REALM']
self.integrity_key = make_integrity_key(self.username, self.realm, self.password)
# retry request with authentication
request.transaction_id = random_transaction_id()
response, _ = await self.request(request)
self.relayed_address = response.attributes['XOR-RELAYED-ADDRESS']
logger.info('TURN allocation created %s', self.relayed_address)
# periodically refresh allocation
self.refresh_handle = asyncio.ensure_future(self.refresh())
return self.relayed_address | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"request",
"=",
"stun",
".",
"Message",
"(",
"message_method",
"=",
"stun",
".",
"Method",
".",
"ALLOCATE",
",",
"message_class",
"=",
"stun",
".",
"Class",
".",
"REQUEST",
")",
"request",
".",
"attributes",
"[",
"'LIFETIME'",
"]",
"=",
"self",
".",
"lifetime",
"request",
".",
"attributes",
"[",
"'REQUESTED-TRANSPORT'",
"]",
"=",
"UDP_TRANSPORT",
"try",
":",
"response",
",",
"_",
"=",
"await",
"self",
".",
"request",
"(",
"request",
")",
"except",
"exceptions",
".",
"TransactionFailed",
"as",
"e",
":",
"response",
"=",
"e",
".",
"response",
"if",
"response",
".",
"attributes",
"[",
"'ERROR-CODE'",
"]",
"[",
"0",
"]",
"==",
"401",
":",
"# update long-term credentials",
"self",
".",
"nonce",
"=",
"response",
".",
"attributes",
"[",
"'NONCE'",
"]",
"self",
".",
"realm",
"=",
"response",
".",
"attributes",
"[",
"'REALM'",
"]",
"self",
".",
"integrity_key",
"=",
"make_integrity_key",
"(",
"self",
".",
"username",
",",
"self",
".",
"realm",
",",
"self",
".",
"password",
")",
"# retry request with authentication",
"request",
".",
"transaction_id",
"=",
"random_transaction_id",
"(",
")",
"response",
",",
"_",
"=",
"await",
"self",
".",
"request",
"(",
"request",
")",
"self",
".",
"relayed_address",
"=",
"response",
".",
"attributes",
"[",
"'XOR-RELAYED-ADDRESS'",
"]",
"logger",
".",
"info",
"(",
"'TURN allocation created %s'",
",",
"self",
".",
"relayed_address",
")",
"# periodically refresh allocation",
"self",
".",
"refresh_handle",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"refresh",
"(",
")",
")",
"return",
"self",
".",
"relayed_address"
] | Create a TURN allocation. | [
"Create",
"a",
"TURN",
"allocation",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L70-L99 | train | 235,114 |
aiortc/aioice | aioice/turn.py | TurnClientMixin.delete | async def delete(self):
"""
Delete the TURN allocation.
"""
if self.refresh_handle:
self.refresh_handle.cancel()
self.refresh_handle = None
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = 0
await self.request(request)
logger.info('TURN allocation deleted %s', self.relayed_address)
if self.receiver:
self.receiver.connection_lost(None) | python | async def delete(self):
"""
Delete the TURN allocation.
"""
if self.refresh_handle:
self.refresh_handle.cancel()
self.refresh_handle = None
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = 0
await self.request(request)
logger.info('TURN allocation deleted %s', self.relayed_address)
if self.receiver:
self.receiver.connection_lost(None) | [
"async",
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"refresh_handle",
":",
"self",
".",
"refresh_handle",
".",
"cancel",
"(",
")",
"self",
".",
"refresh_handle",
"=",
"None",
"request",
"=",
"stun",
".",
"Message",
"(",
"message_method",
"=",
"stun",
".",
"Method",
".",
"REFRESH",
",",
"message_class",
"=",
"stun",
".",
"Class",
".",
"REQUEST",
")",
"request",
".",
"attributes",
"[",
"'LIFETIME'",
"]",
"=",
"0",
"await",
"self",
".",
"request",
"(",
"request",
")",
"logger",
".",
"info",
"(",
"'TURN allocation deleted %s'",
",",
"self",
".",
"relayed_address",
")",
"if",
"self",
".",
"receiver",
":",
"self",
".",
"receiver",
".",
"connection_lost",
"(",
"None",
")"
] | Delete the TURN allocation. | [
"Delete",
"the",
"TURN",
"allocation",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L130-L145 | train | 235,115 |
aiortc/aioice | aioice/turn.py | TurnClientMixin.refresh | async def refresh(self):
"""
Periodically refresh the TURN allocation.
"""
while True:
await asyncio.sleep(5/6 * self.lifetime)
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
await self.request(request)
logger.info('TURN allocation refreshed %s', self.relayed_address) | python | async def refresh(self):
"""
Periodically refresh the TURN allocation.
"""
while True:
await asyncio.sleep(5/6 * self.lifetime)
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
await self.request(request)
logger.info('TURN allocation refreshed %s', self.relayed_address) | [
"async",
"def",
"refresh",
"(",
"self",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"5",
"/",
"6",
"*",
"self",
".",
"lifetime",
")",
"request",
"=",
"stun",
".",
"Message",
"(",
"message_method",
"=",
"stun",
".",
"Method",
".",
"REFRESH",
",",
"message_class",
"=",
"stun",
".",
"Class",
".",
"REQUEST",
")",
"request",
".",
"attributes",
"[",
"'LIFETIME'",
"]",
"=",
"self",
".",
"lifetime",
"await",
"self",
".",
"request",
"(",
"request",
")",
"logger",
".",
"info",
"(",
"'TURN allocation refreshed %s'",
",",
"self",
".",
"relayed_address",
")"
] | Periodically refresh the TURN allocation. | [
"Periodically",
"refresh",
"the",
"TURN",
"allocation",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L147-L159 | train | 235,116 |
aiortc/aioice | aioice/turn.py | TurnClientMixin.send_data | async def send_data(self, data, addr):
"""
Send data to a remote host via the TURN server.
"""
channel = self.peer_to_channel.get(addr)
if channel is None:
channel = self.channel_number
self.channel_number += 1
self.channel_to_peer[channel] = addr
self.peer_to_channel[addr] = channel
# bind channel
await self.channel_bind(channel, addr)
header = struct.pack('!HH', channel, len(data))
self._send(header + data) | python | async def send_data(self, data, addr):
"""
Send data to a remote host via the TURN server.
"""
channel = self.peer_to_channel.get(addr)
if channel is None:
channel = self.channel_number
self.channel_number += 1
self.channel_to_peer[channel] = addr
self.peer_to_channel[addr] = channel
# bind channel
await self.channel_bind(channel, addr)
header = struct.pack('!HH', channel, len(data))
self._send(header + data) | [
"async",
"def",
"send_data",
"(",
"self",
",",
"data",
",",
"addr",
")",
":",
"channel",
"=",
"self",
".",
"peer_to_channel",
".",
"get",
"(",
"addr",
")",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"self",
".",
"channel_number",
"self",
".",
"channel_number",
"+=",
"1",
"self",
".",
"channel_to_peer",
"[",
"channel",
"]",
"=",
"addr",
"self",
".",
"peer_to_channel",
"[",
"addr",
"]",
"=",
"channel",
"# bind channel",
"await",
"self",
".",
"channel_bind",
"(",
"channel",
",",
"addr",
")",
"header",
"=",
"struct",
".",
"pack",
"(",
"'!HH'",
",",
"channel",
",",
"len",
"(",
"data",
")",
")",
"self",
".",
"_send",
"(",
"header",
"+",
"data",
")"
] | Send data to a remote host via the TURN server. | [
"Send",
"data",
"to",
"a",
"remote",
"host",
"via",
"the",
"TURN",
"server",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L177-L192 | train | 235,117 |
aiortc/aioice | aioice/turn.py | TurnClientMixin.send_stun | def send_stun(self, message, addr):
"""
Send a STUN message to the TURN server.
"""
logger.debug('%s > %s %s', self, addr, message)
self._send(bytes(message)) | python | def send_stun(self, message, addr):
"""
Send a STUN message to the TURN server.
"""
logger.debug('%s > %s %s', self, addr, message)
self._send(bytes(message)) | [
"def",
"send_stun",
"(",
"self",
",",
"message",
",",
"addr",
")",
":",
"logger",
".",
"debug",
"(",
"'%s > %s %s'",
",",
"self",
",",
"addr",
",",
"message",
")",
"self",
".",
"_send",
"(",
"bytes",
"(",
"message",
")",
")"
] | Send a STUN message to the TURN server. | [
"Send",
"a",
"STUN",
"message",
"to",
"the",
"TURN",
"server",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L194-L199 | train | 235,118 |
aiortc/aioice | aioice/turn.py | TurnTransport.get_extra_info | def get_extra_info(self, name, default=None):
"""
Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address
"""
if name == 'related_address':
return self.__inner_protocol.transport.get_extra_info('sockname')
elif name == 'sockname':
return self.__relayed_address
return default | python | def get_extra_info(self, name, default=None):
"""
Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address
"""
if name == 'related_address':
return self.__inner_protocol.transport.get_extra_info('sockname')
elif name == 'sockname':
return self.__relayed_address
return default | [
"def",
"get_extra_info",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"==",
"'related_address'",
":",
"return",
"self",
".",
"__inner_protocol",
".",
"transport",
".",
"get_extra_info",
"(",
"'sockname'",
")",
"elif",
"name",
"==",
"'sockname'",
":",
"return",
"self",
".",
"__relayed_address",
"return",
"default"
] | Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address | [
"Return",
"optional",
"transport",
"information",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L250-L261 | train | 235,119 |
aiortc/aioice | aioice/turn.py | TurnTransport.sendto | def sendto(self, data, addr):
"""
Sends the `data` bytes to the remote peer given `addr`.
This will bind a TURN channel as necessary.
"""
asyncio.ensure_future(self.__inner_protocol.send_data(data, addr)) | python | def sendto(self, data, addr):
"""
Sends the `data` bytes to the remote peer given `addr`.
This will bind a TURN channel as necessary.
"""
asyncio.ensure_future(self.__inner_protocol.send_data(data, addr)) | [
"def",
"sendto",
"(",
"self",
",",
"data",
",",
"addr",
")",
":",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"__inner_protocol",
".",
"send_data",
"(",
"data",
",",
"addr",
")",
")"
] | Sends the `data` bytes to the remote peer given `addr`.
This will bind a TURN channel as necessary. | [
"Sends",
"the",
"data",
"bytes",
"to",
"the",
"remote",
"peer",
"given",
"addr",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/turn.py#L263-L269 | train | 235,120 |
aiortc/aioice | aioice/candidate.py | candidate_foundation | def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest() | python | def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest() | [
"def",
"candidate_foundation",
"(",
"candidate_type",
",",
"candidate_transport",
",",
"base_address",
")",
":",
"key",
"=",
"'%s|%s|%s'",
"%",
"(",
"candidate_type",
",",
"candidate_transport",
",",
"base_address",
")",
"return",
"hashlib",
".",
"md5",
"(",
"key",
".",
"encode",
"(",
"'ascii'",
")",
")",
".",
"hexdigest",
"(",
")"
] | See RFC 5245 - 4.1.1.3. Computing Foundations | [
"See",
"RFC",
"5245",
"-",
"4",
".",
"1",
".",
"1",
".",
"3",
".",
"Computing",
"Foundations"
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/candidate.py#L5-L10 | train | 235,121 |
aiortc/aioice | aioice/candidate.py | candidate_priority | def candidate_priority(candidate_component, candidate_type, local_pref=65535):
"""
See RFC 5245 - 4.1.2.1. Recommended Formula
"""
if candidate_type == 'host':
type_pref = 126
elif candidate_type == 'prflx':
type_pref = 110
elif candidate_type == 'srflx':
type_pref = 100
else:
type_pref = 0
return (1 << 24) * type_pref + \
(1 << 8) * local_pref + \
(256 - candidate_component) | python | def candidate_priority(candidate_component, candidate_type, local_pref=65535):
"""
See RFC 5245 - 4.1.2.1. Recommended Formula
"""
if candidate_type == 'host':
type_pref = 126
elif candidate_type == 'prflx':
type_pref = 110
elif candidate_type == 'srflx':
type_pref = 100
else:
type_pref = 0
return (1 << 24) * type_pref + \
(1 << 8) * local_pref + \
(256 - candidate_component) | [
"def",
"candidate_priority",
"(",
"candidate_component",
",",
"candidate_type",
",",
"local_pref",
"=",
"65535",
")",
":",
"if",
"candidate_type",
"==",
"'host'",
":",
"type_pref",
"=",
"126",
"elif",
"candidate_type",
"==",
"'prflx'",
":",
"type_pref",
"=",
"110",
"elif",
"candidate_type",
"==",
"'srflx'",
":",
"type_pref",
"=",
"100",
"else",
":",
"type_pref",
"=",
"0",
"return",
"(",
"1",
"<<",
"24",
")",
"*",
"type_pref",
"+",
"(",
"1",
"<<",
"8",
")",
"*",
"local_pref",
"+",
"(",
"256",
"-",
"candidate_component",
")"
] | See RFC 5245 - 4.1.2.1. Recommended Formula | [
"See",
"RFC",
"5245",
"-",
"4",
".",
"1",
".",
"2",
".",
"1",
".",
"Recommended",
"Formula"
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/candidate.py#L13-L28 | train | 235,122 |
aiortc/aioice | aioice/candidate.py | Candidate.to_sdp | def to_sdp(self):
"""
Return a string representation suitable for SDP.
"""
sdp = '%s %d %s %d %s %d typ %s' % (
self.foundation,
self.component,
self.transport,
self.priority,
self.host,
self.port,
self.type)
if self.related_address is not None:
sdp += ' raddr %s' % self.related_address
if self.related_port is not None:
sdp += ' rport %s' % self.related_port
if self.tcptype is not None:
sdp += ' tcptype %s' % self.tcptype
if self.generation is not None:
sdp += ' generation %d' % self.generation
return sdp | python | def to_sdp(self):
"""
Return a string representation suitable for SDP.
"""
sdp = '%s %d %s %d %s %d typ %s' % (
self.foundation,
self.component,
self.transport,
self.priority,
self.host,
self.port,
self.type)
if self.related_address is not None:
sdp += ' raddr %s' % self.related_address
if self.related_port is not None:
sdp += ' rport %s' % self.related_port
if self.tcptype is not None:
sdp += ' tcptype %s' % self.tcptype
if self.generation is not None:
sdp += ' generation %d' % self.generation
return sdp | [
"def",
"to_sdp",
"(",
"self",
")",
":",
"sdp",
"=",
"'%s %d %s %d %s %d typ %s'",
"%",
"(",
"self",
".",
"foundation",
",",
"self",
".",
"component",
",",
"self",
".",
"transport",
",",
"self",
".",
"priority",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"self",
".",
"type",
")",
"if",
"self",
".",
"related_address",
"is",
"not",
"None",
":",
"sdp",
"+=",
"' raddr %s'",
"%",
"self",
".",
"related_address",
"if",
"self",
".",
"related_port",
"is",
"not",
"None",
":",
"sdp",
"+=",
"' rport %s'",
"%",
"self",
".",
"related_port",
"if",
"self",
".",
"tcptype",
"is",
"not",
"None",
":",
"sdp",
"+=",
"' tcptype %s'",
"%",
"self",
".",
"tcptype",
"if",
"self",
".",
"generation",
"is",
"not",
"None",
":",
"sdp",
"+=",
"' generation %d'",
"%",
"self",
".",
"generation",
"return",
"sdp"
] | Return a string representation suitable for SDP. | [
"Return",
"a",
"string",
"representation",
"suitable",
"for",
"SDP",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/candidate.py#L85-L105 | train | 235,123 |
aiortc/aioice | aioice/candidate.py | Candidate.can_pair_with | def can_pair_with(self, other):
"""
A local candidate is paired with a remote candidate if and only if
the two candidates have the same component ID and have the same IP
address version.
"""
a = ipaddress.ip_address(self.host)
b = ipaddress.ip_address(other.host)
return (
self.component == other.component and
self.transport.lower() == other.transport.lower() and
a.version == b.version
) | python | def can_pair_with(self, other):
"""
A local candidate is paired with a remote candidate if and only if
the two candidates have the same component ID and have the same IP
address version.
"""
a = ipaddress.ip_address(self.host)
b = ipaddress.ip_address(other.host)
return (
self.component == other.component and
self.transport.lower() == other.transport.lower() and
a.version == b.version
) | [
"def",
"can_pair_with",
"(",
"self",
",",
"other",
")",
":",
"a",
"=",
"ipaddress",
".",
"ip_address",
"(",
"self",
".",
"host",
")",
"b",
"=",
"ipaddress",
".",
"ip_address",
"(",
"other",
".",
"host",
")",
"return",
"(",
"self",
".",
"component",
"==",
"other",
".",
"component",
"and",
"self",
".",
"transport",
".",
"lower",
"(",
")",
"==",
"other",
".",
"transport",
".",
"lower",
"(",
")",
"and",
"a",
".",
"version",
"==",
"b",
".",
"version",
")"
] | A local candidate is paired with a remote candidate if and only if
the two candidates have the same component ID and have the same IP
address version. | [
"A",
"local",
"candidate",
"is",
"paired",
"with",
"a",
"remote",
"candidate",
"if",
"and",
"only",
"if",
"the",
"two",
"candidates",
"have",
"the",
"same",
"component",
"ID",
"and",
"have",
"the",
"same",
"IP",
"address",
"version",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/candidate.py#L107-L119 | train | 235,124 |
aiortc/aioice | aioice/ice.py | candidate_pair_priority | def candidate_pair_priority(local, remote, ice_controlling):
"""
See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
"""
G = ice_controlling and local.priority or remote.priority
D = ice_controlling and remote.priority or local.priority
return (1 << 32) * min(G, D) + 2 * max(G, D) + (G > D and 1 or 0) | python | def candidate_pair_priority(local, remote, ice_controlling):
"""
See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
"""
G = ice_controlling and local.priority or remote.priority
D = ice_controlling and remote.priority or local.priority
return (1 << 32) * min(G, D) + 2 * max(G, D) + (G > D and 1 or 0) | [
"def",
"candidate_pair_priority",
"(",
"local",
",",
"remote",
",",
"ice_controlling",
")",
":",
"G",
"=",
"ice_controlling",
"and",
"local",
".",
"priority",
"or",
"remote",
".",
"priority",
"D",
"=",
"ice_controlling",
"and",
"remote",
".",
"priority",
"or",
"local",
".",
"priority",
"return",
"(",
"1",
"<<",
"32",
")",
"*",
"min",
"(",
"G",
",",
"D",
")",
"+",
"2",
"*",
"max",
"(",
"G",
",",
"D",
")",
"+",
"(",
"G",
">",
"D",
"and",
"1",
"or",
"0",
")"
] | See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs | [
"See",
"RFC",
"5245",
"-",
"5",
".",
"7",
".",
"2",
".",
"Computing",
"Pair",
"Priority",
"and",
"Ordering",
"Pairs"
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L24-L30 | train | 235,125 |
aiortc/aioice | aioice/ice.py | get_host_addresses | def get_host_addresses(use_ipv4, use_ipv6):
"""
Get local IP addresses.
"""
addresses = []
for interface in netifaces.interfaces():
ifaddresses = netifaces.ifaddresses(interface)
for address in ifaddresses.get(socket.AF_INET, []):
if use_ipv4 and address['addr'] != '127.0.0.1':
addresses.append(address['addr'])
for address in ifaddresses.get(socket.AF_INET6, []):
if use_ipv6 and address['addr'] != '::1' and '%' not in address['addr']:
addresses.append(address['addr'])
return addresses | python | def get_host_addresses(use_ipv4, use_ipv6):
"""
Get local IP addresses.
"""
addresses = []
for interface in netifaces.interfaces():
ifaddresses = netifaces.ifaddresses(interface)
for address in ifaddresses.get(socket.AF_INET, []):
if use_ipv4 and address['addr'] != '127.0.0.1':
addresses.append(address['addr'])
for address in ifaddresses.get(socket.AF_INET6, []):
if use_ipv6 and address['addr'] != '::1' and '%' not in address['addr']:
addresses.append(address['addr'])
return addresses | [
"def",
"get_host_addresses",
"(",
"use_ipv4",
",",
"use_ipv6",
")",
":",
"addresses",
"=",
"[",
"]",
"for",
"interface",
"in",
"netifaces",
".",
"interfaces",
"(",
")",
":",
"ifaddresses",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"interface",
")",
"for",
"address",
"in",
"ifaddresses",
".",
"get",
"(",
"socket",
".",
"AF_INET",
",",
"[",
"]",
")",
":",
"if",
"use_ipv4",
"and",
"address",
"[",
"'addr'",
"]",
"!=",
"'127.0.0.1'",
":",
"addresses",
".",
"append",
"(",
"address",
"[",
"'addr'",
"]",
")",
"for",
"address",
"in",
"ifaddresses",
".",
"get",
"(",
"socket",
".",
"AF_INET6",
",",
"[",
"]",
")",
":",
"if",
"use_ipv6",
"and",
"address",
"[",
"'addr'",
"]",
"!=",
"'::1'",
"and",
"'%'",
"not",
"in",
"address",
"[",
"'addr'",
"]",
":",
"addresses",
".",
"append",
"(",
"address",
"[",
"'addr'",
"]",
")",
"return",
"addresses"
] | Get local IP addresses. | [
"Get",
"local",
"IP",
"addresses",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L33-L46 | train | 235,126 |
aiortc/aioice | aioice/ice.py | server_reflexive_candidate | async def server_reflexive_candidate(protocol, stun_server):
"""
Query STUN server to obtain a server-reflexive candidate.
"""
# lookup address
loop = asyncio.get_event_loop()
stun_server = (
await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]),
stun_server[1])
# perform STUN query
request = stun.Message(message_method=stun.Method.BINDING,
message_class=stun.Class.REQUEST)
response, _ = await protocol.request(request, stun_server)
local_candidate = protocol.local_candidate
return Candidate(
foundation=candidate_foundation('srflx', 'udp', local_candidate.host),
component=local_candidate.component,
transport=local_candidate.transport,
priority=candidate_priority(local_candidate.component, 'srflx'),
host=response.attributes['XOR-MAPPED-ADDRESS'][0],
port=response.attributes['XOR-MAPPED-ADDRESS'][1],
type='srflx',
related_address=local_candidate.host,
related_port=local_candidate.port) | python | async def server_reflexive_candidate(protocol, stun_server):
"""
Query STUN server to obtain a server-reflexive candidate.
"""
# lookup address
loop = asyncio.get_event_loop()
stun_server = (
await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]),
stun_server[1])
# perform STUN query
request = stun.Message(message_method=stun.Method.BINDING,
message_class=stun.Class.REQUEST)
response, _ = await protocol.request(request, stun_server)
local_candidate = protocol.local_candidate
return Candidate(
foundation=candidate_foundation('srflx', 'udp', local_candidate.host),
component=local_candidate.component,
transport=local_candidate.transport,
priority=candidate_priority(local_candidate.component, 'srflx'),
host=response.attributes['XOR-MAPPED-ADDRESS'][0],
port=response.attributes['XOR-MAPPED-ADDRESS'][1],
type='srflx',
related_address=local_candidate.host,
related_port=local_candidate.port) | [
"async",
"def",
"server_reflexive_candidate",
"(",
"protocol",
",",
"stun_server",
")",
":",
"# lookup address",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"stun_server",
"=",
"(",
"await",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"socket",
".",
"gethostbyname",
",",
"stun_server",
"[",
"0",
"]",
")",
",",
"stun_server",
"[",
"1",
"]",
")",
"# perform STUN query",
"request",
"=",
"stun",
".",
"Message",
"(",
"message_method",
"=",
"stun",
".",
"Method",
".",
"BINDING",
",",
"message_class",
"=",
"stun",
".",
"Class",
".",
"REQUEST",
")",
"response",
",",
"_",
"=",
"await",
"protocol",
".",
"request",
"(",
"request",
",",
"stun_server",
")",
"local_candidate",
"=",
"protocol",
".",
"local_candidate",
"return",
"Candidate",
"(",
"foundation",
"=",
"candidate_foundation",
"(",
"'srflx'",
",",
"'udp'",
",",
"local_candidate",
".",
"host",
")",
",",
"component",
"=",
"local_candidate",
".",
"component",
",",
"transport",
"=",
"local_candidate",
".",
"transport",
",",
"priority",
"=",
"candidate_priority",
"(",
"local_candidate",
".",
"component",
",",
"'srflx'",
")",
",",
"host",
"=",
"response",
".",
"attributes",
"[",
"'XOR-MAPPED-ADDRESS'",
"]",
"[",
"0",
"]",
",",
"port",
"=",
"response",
".",
"attributes",
"[",
"'XOR-MAPPED-ADDRESS'",
"]",
"[",
"1",
"]",
",",
"type",
"=",
"'srflx'",
",",
"related_address",
"=",
"local_candidate",
".",
"host",
",",
"related_port",
"=",
"local_candidate",
".",
"port",
")"
] | Query STUN server to obtain a server-reflexive candidate. | [
"Query",
"STUN",
"server",
"to",
"obtain",
"a",
"server",
"-",
"reflexive",
"candidate",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L49-L74 | train | 235,127 |
aiortc/aioice | aioice/ice.py | sort_candidate_pairs | def sort_candidate_pairs(pairs, ice_controlling):
"""
Sort a list of candidate pairs.
"""
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
pair.remote_candidate,
ice_controlling)
pairs.sort(key=pair_priority) | python | def sort_candidate_pairs(pairs, ice_controlling):
"""
Sort a list of candidate pairs.
"""
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
pair.remote_candidate,
ice_controlling)
pairs.sort(key=pair_priority) | [
"def",
"sort_candidate_pairs",
"(",
"pairs",
",",
"ice_controlling",
")",
":",
"def",
"pair_priority",
"(",
"pair",
")",
":",
"return",
"-",
"candidate_pair_priority",
"(",
"pair",
".",
"local_candidate",
",",
"pair",
".",
"remote_candidate",
",",
"ice_controlling",
")",
"pairs",
".",
"sort",
"(",
"key",
"=",
"pair_priority",
")"
] | Sort a list of candidate pairs. | [
"Sort",
"a",
"list",
"of",
"candidate",
"pairs",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L77-L86 | train | 235,128 |
aiortc/aioice | aioice/ice.py | StunProtocol.send_stun | def send_stun(self, message, addr):
"""
Send a STUN message.
"""
self.__log_debug('> %s %s', addr, message)
self.transport.sendto(bytes(message), addr) | python | def send_stun(self, message, addr):
"""
Send a STUN message.
"""
self.__log_debug('> %s %s', addr, message)
self.transport.sendto(bytes(message), addr) | [
"def",
"send_stun",
"(",
"self",
",",
"message",
",",
"addr",
")",
":",
"self",
".",
"__log_debug",
"(",
"'> %s %s'",
",",
"addr",
",",
"message",
")",
"self",
".",
"transport",
".",
"sendto",
"(",
"bytes",
"(",
"message",
")",
",",
"addr",
")"
] | Send a STUN message. | [
"Send",
"a",
"STUN",
"message",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L200-L205 | train | 235,129 |
aiortc/aioice | aioice/ice.py | Connection.add_remote_candidate | def add_remote_candidate(self, remote_candidate):
"""
Add a remote candidate or signal end-of-candidates.
To signal end-of-candidates, pass `None`.
"""
if self._remote_candidates_end:
raise ValueError('Cannot add remote candidate after end-of-candidates.')
if remote_candidate is None:
self._prune_components()
self._remote_candidates_end = True
return
self._remote_candidates.append(remote_candidate)
for protocol in self._protocols:
if (protocol.local_candidate.can_pair_with(remote_candidate) and
not self._find_pair(protocol, remote_candidate)):
pair = CandidatePair(protocol, remote_candidate)
self._check_list.append(pair)
self.sort_check_list() | python | def add_remote_candidate(self, remote_candidate):
"""
Add a remote candidate or signal end-of-candidates.
To signal end-of-candidates, pass `None`.
"""
if self._remote_candidates_end:
raise ValueError('Cannot add remote candidate after end-of-candidates.')
if remote_candidate is None:
self._prune_components()
self._remote_candidates_end = True
return
self._remote_candidates.append(remote_candidate)
for protocol in self._protocols:
if (protocol.local_candidate.can_pair_with(remote_candidate) and
not self._find_pair(protocol, remote_candidate)):
pair = CandidatePair(protocol, remote_candidate)
self._check_list.append(pair)
self.sort_check_list() | [
"def",
"add_remote_candidate",
"(",
"self",
",",
"remote_candidate",
")",
":",
"if",
"self",
".",
"_remote_candidates_end",
":",
"raise",
"ValueError",
"(",
"'Cannot add remote candidate after end-of-candidates.'",
")",
"if",
"remote_candidate",
"is",
"None",
":",
"self",
".",
"_prune_components",
"(",
")",
"self",
".",
"_remote_candidates_end",
"=",
"True",
"return",
"self",
".",
"_remote_candidates",
".",
"append",
"(",
"remote_candidate",
")",
"for",
"protocol",
"in",
"self",
".",
"_protocols",
":",
"if",
"(",
"protocol",
".",
"local_candidate",
".",
"can_pair_with",
"(",
"remote_candidate",
")",
"and",
"not",
"self",
".",
"_find_pair",
"(",
"protocol",
",",
"remote_candidate",
")",
")",
":",
"pair",
"=",
"CandidatePair",
"(",
"protocol",
",",
"remote_candidate",
")",
"self",
".",
"_check_list",
".",
"append",
"(",
"pair",
")",
"self",
".",
"sort_check_list",
"(",
")"
] | Add a remote candidate or signal end-of-candidates.
To signal end-of-candidates, pass `None`. | [
"Add",
"a",
"remote",
"candidate",
"or",
"signal",
"end",
"-",
"of",
"-",
"candidates",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L299-L319 | train | 235,130 |
aiortc/aioice | aioice/ice.py | Connection.gather_candidates | async def gather_candidates(self):
"""
Gather local candidates.
You **must** call this coroutine before calling :meth:`connect`.
"""
if not self._local_candidates_start:
self._local_candidates_start = True
addresses = get_host_addresses(use_ipv4=self._use_ipv4, use_ipv6=self._use_ipv6)
for component in self._components:
self._local_candidates += await self.get_component_candidates(
component=component,
addresses=addresses)
self._local_candidates_end = True | python | async def gather_candidates(self):
"""
Gather local candidates.
You **must** call this coroutine before calling :meth:`connect`.
"""
if not self._local_candidates_start:
self._local_candidates_start = True
addresses = get_host_addresses(use_ipv4=self._use_ipv4, use_ipv6=self._use_ipv6)
for component in self._components:
self._local_candidates += await self.get_component_candidates(
component=component,
addresses=addresses)
self._local_candidates_end = True | [
"async",
"def",
"gather_candidates",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_local_candidates_start",
":",
"self",
".",
"_local_candidates_start",
"=",
"True",
"addresses",
"=",
"get_host_addresses",
"(",
"use_ipv4",
"=",
"self",
".",
"_use_ipv4",
",",
"use_ipv6",
"=",
"self",
".",
"_use_ipv6",
")",
"for",
"component",
"in",
"self",
".",
"_components",
":",
"self",
".",
"_local_candidates",
"+=",
"await",
"self",
".",
"get_component_candidates",
"(",
"component",
"=",
"component",
",",
"addresses",
"=",
"addresses",
")",
"self",
".",
"_local_candidates_end",
"=",
"True"
] | Gather local candidates.
You **must** call this coroutine before calling :meth:`connect`. | [
"Gather",
"local",
"candidates",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L321-L334 | train | 235,131 |
aiortc/aioice | aioice/ice.py | Connection.get_default_candidate | def get_default_candidate(self, component):
"""
Gets the default local candidate for the specified component.
"""
for candidate in sorted(self._local_candidates, key=lambda x: x.priority):
if candidate.component == component:
return candidate | python | def get_default_candidate(self, component):
"""
Gets the default local candidate for the specified component.
"""
for candidate in sorted(self._local_candidates, key=lambda x: x.priority):
if candidate.component == component:
return candidate | [
"def",
"get_default_candidate",
"(",
"self",
",",
"component",
")",
":",
"for",
"candidate",
"in",
"sorted",
"(",
"self",
".",
"_local_candidates",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"priority",
")",
":",
"if",
"candidate",
".",
"component",
"==",
"component",
":",
"return",
"candidate"
] | Gets the default local candidate for the specified component. | [
"Gets",
"the",
"default",
"local",
"candidate",
"for",
"the",
"specified",
"component",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L336-L342 | train | 235,132 |
aiortc/aioice | aioice/ice.py | Connection.connect | async def connect(self):
"""
Perform ICE handshake.
This coroutine returns if a candidate pair was successfuly nominated
and raises an exception otherwise.
"""
if not self._local_candidates_end:
raise ConnectionError('Local candidates gathering was not performed')
if (self.remote_username is None or
self.remote_password is None):
raise ConnectionError('Remote username or password is missing')
# 5.7.1. Forming Candidate Pairs
for remote_candidate in self._remote_candidates:
for protocol in self._protocols:
if (protocol.local_candidate.can_pair_with(remote_candidate) and
not self._find_pair(protocol, remote_candidate)):
pair = CandidatePair(protocol, remote_candidate)
self._check_list.append(pair)
self.sort_check_list()
self._unfreeze_initial()
# handle early checks
for check in self._early_checks:
self.check_incoming(*check)
self._early_checks = []
# perform checks
while True:
if not self.check_periodic():
break
await asyncio.sleep(0.02)
# wait for completion
if self._check_list:
res = await self._check_list_state.get()
else:
res = ICE_FAILED
# cancel remaining checks
for check in self._check_list:
if check.handle:
check.handle.cancel()
if res != ICE_COMPLETED:
raise ConnectionError('ICE negotiation failed')
# start consent freshness tests
self._query_consent_handle = asyncio.ensure_future(self.query_consent()) | python | async def connect(self):
"""
Perform ICE handshake.
This coroutine returns if a candidate pair was successfuly nominated
and raises an exception otherwise.
"""
if not self._local_candidates_end:
raise ConnectionError('Local candidates gathering was not performed')
if (self.remote_username is None or
self.remote_password is None):
raise ConnectionError('Remote username or password is missing')
# 5.7.1. Forming Candidate Pairs
for remote_candidate in self._remote_candidates:
for protocol in self._protocols:
if (protocol.local_candidate.can_pair_with(remote_candidate) and
not self._find_pair(protocol, remote_candidate)):
pair = CandidatePair(protocol, remote_candidate)
self._check_list.append(pair)
self.sort_check_list()
self._unfreeze_initial()
# handle early checks
for check in self._early_checks:
self.check_incoming(*check)
self._early_checks = []
# perform checks
while True:
if not self.check_periodic():
break
await asyncio.sleep(0.02)
# wait for completion
if self._check_list:
res = await self._check_list_state.get()
else:
res = ICE_FAILED
# cancel remaining checks
for check in self._check_list:
if check.handle:
check.handle.cancel()
if res != ICE_COMPLETED:
raise ConnectionError('ICE negotiation failed')
# start consent freshness tests
self._query_consent_handle = asyncio.ensure_future(self.query_consent()) | [
"async",
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_local_candidates_end",
":",
"raise",
"ConnectionError",
"(",
"'Local candidates gathering was not performed'",
")",
"if",
"(",
"self",
".",
"remote_username",
"is",
"None",
"or",
"self",
".",
"remote_password",
"is",
"None",
")",
":",
"raise",
"ConnectionError",
"(",
"'Remote username or password is missing'",
")",
"# 5.7.1. Forming Candidate Pairs",
"for",
"remote_candidate",
"in",
"self",
".",
"_remote_candidates",
":",
"for",
"protocol",
"in",
"self",
".",
"_protocols",
":",
"if",
"(",
"protocol",
".",
"local_candidate",
".",
"can_pair_with",
"(",
"remote_candidate",
")",
"and",
"not",
"self",
".",
"_find_pair",
"(",
"protocol",
",",
"remote_candidate",
")",
")",
":",
"pair",
"=",
"CandidatePair",
"(",
"protocol",
",",
"remote_candidate",
")",
"self",
".",
"_check_list",
".",
"append",
"(",
"pair",
")",
"self",
".",
"sort_check_list",
"(",
")",
"self",
".",
"_unfreeze_initial",
"(",
")",
"# handle early checks",
"for",
"check",
"in",
"self",
".",
"_early_checks",
":",
"self",
".",
"check_incoming",
"(",
"*",
"check",
")",
"self",
".",
"_early_checks",
"=",
"[",
"]",
"# perform checks",
"while",
"True",
":",
"if",
"not",
"self",
".",
"check_periodic",
"(",
")",
":",
"break",
"await",
"asyncio",
".",
"sleep",
"(",
"0.02",
")",
"# wait for completion",
"if",
"self",
".",
"_check_list",
":",
"res",
"=",
"await",
"self",
".",
"_check_list_state",
".",
"get",
"(",
")",
"else",
":",
"res",
"=",
"ICE_FAILED",
"# cancel remaining checks",
"for",
"check",
"in",
"self",
".",
"_check_list",
":",
"if",
"check",
".",
"handle",
":",
"check",
".",
"handle",
".",
"cancel",
"(",
")",
"if",
"res",
"!=",
"ICE_COMPLETED",
":",
"raise",
"ConnectionError",
"(",
"'ICE negotiation failed'",
")",
"# start consent freshness tests",
"self",
".",
"_query_consent_handle",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"query_consent",
"(",
")",
")"
] | Perform ICE handshake.
This coroutine returns if a candidate pair was successfuly nominated
and raises an exception otherwise. | [
"Perform",
"ICE",
"handshake",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L344-L395 | train | 235,133 |
aiortc/aioice | aioice/ice.py | Connection.recvfrom | async def recvfrom(self):
"""
Receive the next datagram.
The return value is a `(bytes, component)` tuple where `bytes` is a
bytes object representing the data received and `component` is the
component on which the data was received.
If the connection is not established, a `ConnectionError` is raised.
"""
if not len(self._nominated):
raise ConnectionError('Cannot receive data, not connected')
result = await self._queue.get()
if result[0] is None:
raise ConnectionError('Connection lost while receiving data')
return result | python | async def recvfrom(self):
"""
Receive the next datagram.
The return value is a `(bytes, component)` tuple where `bytes` is a
bytes object representing the data received and `component` is the
component on which the data was received.
If the connection is not established, a `ConnectionError` is raised.
"""
if not len(self._nominated):
raise ConnectionError('Cannot receive data, not connected')
result = await self._queue.get()
if result[0] is None:
raise ConnectionError('Connection lost while receiving data')
return result | [
"async",
"def",
"recvfrom",
"(",
"self",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"_nominated",
")",
":",
"raise",
"ConnectionError",
"(",
"'Cannot receive data, not connected'",
")",
"result",
"=",
"await",
"self",
".",
"_queue",
".",
"get",
"(",
")",
"if",
"result",
"[",
"0",
"]",
"is",
"None",
":",
"raise",
"ConnectionError",
"(",
"'Connection lost while receiving data'",
")",
"return",
"result"
] | Receive the next datagram.
The return value is a `(bytes, component)` tuple where `bytes` is a
bytes object representing the data received and `component` is the
component on which the data was received.
If the connection is not established, a `ConnectionError` is raised. | [
"Receive",
"the",
"next",
"datagram",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L430-L446 | train | 235,134 |
aiortc/aioice | aioice/ice.py | Connection.sendto | async def sendto(self, data, component):
"""
Send a datagram on the specified component.
If the connection is not established, a `ConnectionError` is raised.
"""
active_pair = self._nominated.get(component)
if active_pair:
await active_pair.protocol.send_data(data, active_pair.remote_addr)
else:
raise ConnectionError('Cannot send data, not connected') | python | async def sendto(self, data, component):
"""
Send a datagram on the specified component.
If the connection is not established, a `ConnectionError` is raised.
"""
active_pair = self._nominated.get(component)
if active_pair:
await active_pair.protocol.send_data(data, active_pair.remote_addr)
else:
raise ConnectionError('Cannot send data, not connected') | [
"async",
"def",
"sendto",
"(",
"self",
",",
"data",
",",
"component",
")",
":",
"active_pair",
"=",
"self",
".",
"_nominated",
".",
"get",
"(",
"component",
")",
"if",
"active_pair",
":",
"await",
"active_pair",
".",
"protocol",
".",
"send_data",
"(",
"data",
",",
"active_pair",
".",
"remote_addr",
")",
"else",
":",
"raise",
"ConnectionError",
"(",
"'Cannot send data, not connected'",
")"
] | Send a datagram on the specified component.
If the connection is not established, a `ConnectionError` is raised. | [
"Send",
"a",
"datagram",
"on",
"the",
"specified",
"component",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L456-L466 | train | 235,135 |
aiortc/aioice | aioice/ice.py | Connection.set_selected_pair | def set_selected_pair(self, component, local_foundation, remote_foundation):
"""
Force the selected candidate pair.
If the remote party does not support ICE, you should using this
instead of calling :meth:`connect`.
"""
# find local candidate
protocol = None
for p in self._protocols:
if (p.local_candidate.component == component and
p.local_candidate.foundation == local_foundation):
protocol = p
break
# find remote candidate
remote_candidate = None
for c in self._remote_candidates:
if c.component == component and c.foundation == remote_foundation:
remote_candidate = c
assert (protocol and remote_candidate)
self._nominated[component] = CandidatePair(protocol, remote_candidate) | python | def set_selected_pair(self, component, local_foundation, remote_foundation):
"""
Force the selected candidate pair.
If the remote party does not support ICE, you should using this
instead of calling :meth:`connect`.
"""
# find local candidate
protocol = None
for p in self._protocols:
if (p.local_candidate.component == component and
p.local_candidate.foundation == local_foundation):
protocol = p
break
# find remote candidate
remote_candidate = None
for c in self._remote_candidates:
if c.component == component and c.foundation == remote_foundation:
remote_candidate = c
assert (protocol and remote_candidate)
self._nominated[component] = CandidatePair(protocol, remote_candidate) | [
"def",
"set_selected_pair",
"(",
"self",
",",
"component",
",",
"local_foundation",
",",
"remote_foundation",
")",
":",
"# find local candidate",
"protocol",
"=",
"None",
"for",
"p",
"in",
"self",
".",
"_protocols",
":",
"if",
"(",
"p",
".",
"local_candidate",
".",
"component",
"==",
"component",
"and",
"p",
".",
"local_candidate",
".",
"foundation",
"==",
"local_foundation",
")",
":",
"protocol",
"=",
"p",
"break",
"# find remote candidate",
"remote_candidate",
"=",
"None",
"for",
"c",
"in",
"self",
".",
"_remote_candidates",
":",
"if",
"c",
".",
"component",
"==",
"component",
"and",
"c",
".",
"foundation",
"==",
"remote_foundation",
":",
"remote_candidate",
"=",
"c",
"assert",
"(",
"protocol",
"and",
"remote_candidate",
")",
"self",
".",
"_nominated",
"[",
"component",
"]",
"=",
"CandidatePair",
"(",
"protocol",
",",
"remote_candidate",
")"
] | Force the selected candidate pair.
If the remote party does not support ICE, you should using this
instead of calling :meth:`connect`. | [
"Force",
"the",
"selected",
"candidate",
"pair",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L468-L490 | train | 235,136 |
aiortc/aioice | aioice/ice.py | Connection.check_incoming | def check_incoming(self, message, addr, protocol):
"""
Handle a succesful incoming check.
"""
component = protocol.local_candidate.component
# find remote candidate
remote_candidate = None
for c in self._remote_candidates:
if c.host == addr[0] and c.port == addr[1]:
remote_candidate = c
assert remote_candidate.component == component
break
if remote_candidate is None:
# 7.2.1.3. Learning Peer Reflexive Candidates
remote_candidate = Candidate(
foundation=random_string(10),
component=component,
transport='udp',
priority=message.attributes['PRIORITY'],
host=addr[0],
port=addr[1],
type='prflx')
self._remote_candidates.append(remote_candidate)
self.__log_info('Discovered peer reflexive candidate %s', remote_candidate)
# find pair
pair = self._find_pair(protocol, remote_candidate)
if pair is None:
pair = CandidatePair(protocol, remote_candidate)
pair.state = CandidatePair.State.WAITING
self._check_list.append(pair)
self.sort_check_list()
# triggered check
if pair.state in [CandidatePair.State.WAITING, CandidatePair.State.FAILED]:
pair.handle = asyncio.ensure_future(self.check_start(pair))
# 7.2.1.5. Updating the Nominated Flag
if 'USE-CANDIDATE' in message.attributes and not self.ice_controlling:
pair.remote_nominated = True
if pair.state == CandidatePair.State.SUCCEEDED:
pair.nominated = True
self.check_complete(pair) | python | def check_incoming(self, message, addr, protocol):
"""
Handle a succesful incoming check.
"""
component = protocol.local_candidate.component
# find remote candidate
remote_candidate = None
for c in self._remote_candidates:
if c.host == addr[0] and c.port == addr[1]:
remote_candidate = c
assert remote_candidate.component == component
break
if remote_candidate is None:
# 7.2.1.3. Learning Peer Reflexive Candidates
remote_candidate = Candidate(
foundation=random_string(10),
component=component,
transport='udp',
priority=message.attributes['PRIORITY'],
host=addr[0],
port=addr[1],
type='prflx')
self._remote_candidates.append(remote_candidate)
self.__log_info('Discovered peer reflexive candidate %s', remote_candidate)
# find pair
pair = self._find_pair(protocol, remote_candidate)
if pair is None:
pair = CandidatePair(protocol, remote_candidate)
pair.state = CandidatePair.State.WAITING
self._check_list.append(pair)
self.sort_check_list()
# triggered check
if pair.state in [CandidatePair.State.WAITING, CandidatePair.State.FAILED]:
pair.handle = asyncio.ensure_future(self.check_start(pair))
# 7.2.1.5. Updating the Nominated Flag
if 'USE-CANDIDATE' in message.attributes and not self.ice_controlling:
pair.remote_nominated = True
if pair.state == CandidatePair.State.SUCCEEDED:
pair.nominated = True
self.check_complete(pair) | [
"def",
"check_incoming",
"(",
"self",
",",
"message",
",",
"addr",
",",
"protocol",
")",
":",
"component",
"=",
"protocol",
".",
"local_candidate",
".",
"component",
"# find remote candidate",
"remote_candidate",
"=",
"None",
"for",
"c",
"in",
"self",
".",
"_remote_candidates",
":",
"if",
"c",
".",
"host",
"==",
"addr",
"[",
"0",
"]",
"and",
"c",
".",
"port",
"==",
"addr",
"[",
"1",
"]",
":",
"remote_candidate",
"=",
"c",
"assert",
"remote_candidate",
".",
"component",
"==",
"component",
"break",
"if",
"remote_candidate",
"is",
"None",
":",
"# 7.2.1.3. Learning Peer Reflexive Candidates",
"remote_candidate",
"=",
"Candidate",
"(",
"foundation",
"=",
"random_string",
"(",
"10",
")",
",",
"component",
"=",
"component",
",",
"transport",
"=",
"'udp'",
",",
"priority",
"=",
"message",
".",
"attributes",
"[",
"'PRIORITY'",
"]",
",",
"host",
"=",
"addr",
"[",
"0",
"]",
",",
"port",
"=",
"addr",
"[",
"1",
"]",
",",
"type",
"=",
"'prflx'",
")",
"self",
".",
"_remote_candidates",
".",
"append",
"(",
"remote_candidate",
")",
"self",
".",
"__log_info",
"(",
"'Discovered peer reflexive candidate %s'",
",",
"remote_candidate",
")",
"# find pair",
"pair",
"=",
"self",
".",
"_find_pair",
"(",
"protocol",
",",
"remote_candidate",
")",
"if",
"pair",
"is",
"None",
":",
"pair",
"=",
"CandidatePair",
"(",
"protocol",
",",
"remote_candidate",
")",
"pair",
".",
"state",
"=",
"CandidatePair",
".",
"State",
".",
"WAITING",
"self",
".",
"_check_list",
".",
"append",
"(",
"pair",
")",
"self",
".",
"sort_check_list",
"(",
")",
"# triggered check",
"if",
"pair",
".",
"state",
"in",
"[",
"CandidatePair",
".",
"State",
".",
"WAITING",
",",
"CandidatePair",
".",
"State",
".",
"FAILED",
"]",
":",
"pair",
".",
"handle",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"check_start",
"(",
"pair",
")",
")",
"# 7.2.1.5. Updating the Nominated Flag",
"if",
"'USE-CANDIDATE'",
"in",
"message",
".",
"attributes",
"and",
"not",
"self",
".",
"ice_controlling",
":",
"pair",
".",
"remote_nominated",
"=",
"True",
"if",
"pair",
".",
"state",
"==",
"CandidatePair",
".",
"State",
".",
"SUCCEEDED",
":",
"pair",
".",
"nominated",
"=",
"True",
"self",
".",
"check_complete",
"(",
"pair",
")"
] | Handle a succesful incoming check. | [
"Handle",
"a",
"succesful",
"incoming",
"check",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L554-L598 | train | 235,137 |
aiortc/aioice | aioice/ice.py | Connection.check_start | async def check_start(self, pair):
"""
Starts a check.
"""
self.check_state(pair, CandidatePair.State.IN_PROGRESS)
request = self.build_request(pair)
try:
response, addr = await pair.protocol.request(
request, pair.remote_addr,
integrity_key=self.remote_password.encode('utf8'))
except exceptions.TransactionError as exc:
# 7.1.3.1. Failure Cases
if exc.response and exc.response.attributes.get('ERROR-CODE', (None, None))[0] == 487:
if 'ICE-CONTROLLING' in request.attributes:
self.switch_role(ice_controlling=False)
elif 'ICE-CONTROLLED' in request.attributes:
self.switch_role(ice_controlling=True)
return await self.check_start(pair)
else:
self.check_state(pair, CandidatePair.State.FAILED)
self.check_complete(pair)
return
# check remote address matches
if addr != pair.remote_addr:
self.__log_info('Check %s failed : source address mismatch', pair)
self.check_state(pair, CandidatePair.State.FAILED)
self.check_complete(pair)
return
# success
self.check_state(pair, CandidatePair.State.SUCCEEDED)
if self.ice_controlling or pair.remote_nominated:
pair.nominated = True
self.check_complete(pair) | python | async def check_start(self, pair):
"""
Starts a check.
"""
self.check_state(pair, CandidatePair.State.IN_PROGRESS)
request = self.build_request(pair)
try:
response, addr = await pair.protocol.request(
request, pair.remote_addr,
integrity_key=self.remote_password.encode('utf8'))
except exceptions.TransactionError as exc:
# 7.1.3.1. Failure Cases
if exc.response and exc.response.attributes.get('ERROR-CODE', (None, None))[0] == 487:
if 'ICE-CONTROLLING' in request.attributes:
self.switch_role(ice_controlling=False)
elif 'ICE-CONTROLLED' in request.attributes:
self.switch_role(ice_controlling=True)
return await self.check_start(pair)
else:
self.check_state(pair, CandidatePair.State.FAILED)
self.check_complete(pair)
return
# check remote address matches
if addr != pair.remote_addr:
self.__log_info('Check %s failed : source address mismatch', pair)
self.check_state(pair, CandidatePair.State.FAILED)
self.check_complete(pair)
return
# success
self.check_state(pair, CandidatePair.State.SUCCEEDED)
if self.ice_controlling or pair.remote_nominated:
pair.nominated = True
self.check_complete(pair) | [
"async",
"def",
"check_start",
"(",
"self",
",",
"pair",
")",
":",
"self",
".",
"check_state",
"(",
"pair",
",",
"CandidatePair",
".",
"State",
".",
"IN_PROGRESS",
")",
"request",
"=",
"self",
".",
"build_request",
"(",
"pair",
")",
"try",
":",
"response",
",",
"addr",
"=",
"await",
"pair",
".",
"protocol",
".",
"request",
"(",
"request",
",",
"pair",
".",
"remote_addr",
",",
"integrity_key",
"=",
"self",
".",
"remote_password",
".",
"encode",
"(",
"'utf8'",
")",
")",
"except",
"exceptions",
".",
"TransactionError",
"as",
"exc",
":",
"# 7.1.3.1. Failure Cases",
"if",
"exc",
".",
"response",
"and",
"exc",
".",
"response",
".",
"attributes",
".",
"get",
"(",
"'ERROR-CODE'",
",",
"(",
"None",
",",
"None",
")",
")",
"[",
"0",
"]",
"==",
"487",
":",
"if",
"'ICE-CONTROLLING'",
"in",
"request",
".",
"attributes",
":",
"self",
".",
"switch_role",
"(",
"ice_controlling",
"=",
"False",
")",
"elif",
"'ICE-CONTROLLED'",
"in",
"request",
".",
"attributes",
":",
"self",
".",
"switch_role",
"(",
"ice_controlling",
"=",
"True",
")",
"return",
"await",
"self",
".",
"check_start",
"(",
"pair",
")",
"else",
":",
"self",
".",
"check_state",
"(",
"pair",
",",
"CandidatePair",
".",
"State",
".",
"FAILED",
")",
"self",
".",
"check_complete",
"(",
"pair",
")",
"return",
"# check remote address matches",
"if",
"addr",
"!=",
"pair",
".",
"remote_addr",
":",
"self",
".",
"__log_info",
"(",
"'Check %s failed : source address mismatch'",
",",
"pair",
")",
"self",
".",
"check_state",
"(",
"pair",
",",
"CandidatePair",
".",
"State",
".",
"FAILED",
")",
"self",
".",
"check_complete",
"(",
"pair",
")",
"return",
"# success",
"self",
".",
"check_state",
"(",
"pair",
",",
"CandidatePair",
".",
"State",
".",
"SUCCEEDED",
")",
"if",
"self",
".",
"ice_controlling",
"or",
"pair",
".",
"remote_nominated",
":",
"pair",
".",
"nominated",
"=",
"True",
"self",
".",
"check_complete",
"(",
"pair",
")"
] | Starts a check. | [
"Starts",
"a",
"check",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L619-L654 | train | 235,138 |
aiortc/aioice | aioice/ice.py | Connection.check_state | def check_state(self, pair, state):
"""
Updates the state of a check.
"""
self.__log_info('Check %s %s -> %s', pair, pair.state, state)
pair.state = state | python | def check_state(self, pair, state):
"""
Updates the state of a check.
"""
self.__log_info('Check %s %s -> %s', pair, pair.state, state)
pair.state = state | [
"def",
"check_state",
"(",
"self",
",",
"pair",
",",
"state",
")",
":",
"self",
".",
"__log_info",
"(",
"'Check %s %s -> %s'",
",",
"pair",
",",
"pair",
".",
"state",
",",
"state",
")",
"pair",
".",
"state",
"=",
"state"
] | Updates the state of a check. | [
"Updates",
"the",
"state",
"of",
"a",
"check",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L656-L661 | train | 235,139 |
aiortc/aioice | aioice/ice.py | Connection._find_pair | def _find_pair(self, protocol, remote_candidate):
"""
Find a candidate pair in the check list.
"""
for pair in self._check_list:
if (pair.protocol == protocol and pair.remote_candidate == remote_candidate):
return pair
return None | python | def _find_pair(self, protocol, remote_candidate):
"""
Find a candidate pair in the check list.
"""
for pair in self._check_list:
if (pair.protocol == protocol and pair.remote_candidate == remote_candidate):
return pair
return None | [
"def",
"_find_pair",
"(",
"self",
",",
"protocol",
",",
"remote_candidate",
")",
":",
"for",
"pair",
"in",
"self",
".",
"_check_list",
":",
"if",
"(",
"pair",
".",
"protocol",
"==",
"protocol",
"and",
"pair",
".",
"remote_candidate",
"==",
"remote_candidate",
")",
":",
"return",
"pair",
"return",
"None"
] | Find a candidate pair in the check list. | [
"Find",
"a",
"candidate",
"pair",
"in",
"the",
"check",
"list",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L663-L670 | train | 235,140 |
aiortc/aioice | aioice/ice.py | Connection._prune_components | def _prune_components(self):
"""
Remove components for which the remote party did not provide any candidates.
This can only be determined after end-of-candidates.
"""
seen_components = set(map(lambda x: x.component, self._remote_candidates))
missing_components = self._components - seen_components
if missing_components:
self.__log_info('Components %s have no candidate pairs' % missing_components)
self._components = seen_components | python | def _prune_components(self):
"""
Remove components for which the remote party did not provide any candidates.
This can only be determined after end-of-candidates.
"""
seen_components = set(map(lambda x: x.component, self._remote_candidates))
missing_components = self._components - seen_components
if missing_components:
self.__log_info('Components %s have no candidate pairs' % missing_components)
self._components = seen_components | [
"def",
"_prune_components",
"(",
"self",
")",
":",
"seen_components",
"=",
"set",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"component",
",",
"self",
".",
"_remote_candidates",
")",
")",
"missing_components",
"=",
"self",
".",
"_components",
"-",
"seen_components",
"if",
"missing_components",
":",
"self",
".",
"__log_info",
"(",
"'Components %s have no candidate pairs'",
"%",
"missing_components",
")",
"self",
".",
"_components",
"=",
"seen_components"
] | Remove components for which the remote party did not provide any candidates.
This can only be determined after end-of-candidates. | [
"Remove",
"components",
"for",
"which",
"the",
"remote",
"party",
"did",
"not",
"provide",
"any",
"candidates",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L740-L750 | train | 235,141 |
aiortc/aioice | aioice/stun.py | parse_message | def parse_message(data, integrity_key=None):
"""
Parses a STUN message.
If the ``integrity_key`` parameter is given, the message's HMAC will be verified.
"""
if len(data) < HEADER_LENGTH:
raise ValueError('STUN message length is less than 20 bytes')
message_type, length, cookie, transaction_id = unpack('!HHI12s', data[0:HEADER_LENGTH])
if len(data) != HEADER_LENGTH + length:
raise ValueError('STUN message length does not match')
attributes = OrderedDict()
pos = HEADER_LENGTH
while pos <= len(data) - 4:
attr_type, attr_len = unpack('!HH', data[pos:pos + 4])
v = data[pos + 4:pos + 4 + attr_len]
pad_len = 4 * ((attr_len + 3) // 4) - attr_len
if attr_type in ATTRIBUTES_BY_TYPE:
_, attr_name, attr_pack, attr_unpack = ATTRIBUTES_BY_TYPE[attr_type]
if attr_unpack == unpack_xor_address:
attributes[attr_name] = attr_unpack(v, transaction_id=transaction_id)
else:
attributes[attr_name] = attr_unpack(v)
if attr_name == 'FINGERPRINT':
if attributes[attr_name] != message_fingerprint(data[0:pos]):
raise ValueError('STUN message fingerprint does not match')
elif attr_name == 'MESSAGE-INTEGRITY':
if (integrity_key is not None and
attributes[attr_name] != message_integrity(data[0:pos], integrity_key)):
raise ValueError('STUN message integrity does not match')
pos += 4 + attr_len + pad_len
return Message(
message_method=message_type & 0x3eef,
message_class=message_type & 0x0110,
transaction_id=transaction_id,
attributes=attributes) | python | def parse_message(data, integrity_key=None):
"""
Parses a STUN message.
If the ``integrity_key`` parameter is given, the message's HMAC will be verified.
"""
if len(data) < HEADER_LENGTH:
raise ValueError('STUN message length is less than 20 bytes')
message_type, length, cookie, transaction_id = unpack('!HHI12s', data[0:HEADER_LENGTH])
if len(data) != HEADER_LENGTH + length:
raise ValueError('STUN message length does not match')
attributes = OrderedDict()
pos = HEADER_LENGTH
while pos <= len(data) - 4:
attr_type, attr_len = unpack('!HH', data[pos:pos + 4])
v = data[pos + 4:pos + 4 + attr_len]
pad_len = 4 * ((attr_len + 3) // 4) - attr_len
if attr_type in ATTRIBUTES_BY_TYPE:
_, attr_name, attr_pack, attr_unpack = ATTRIBUTES_BY_TYPE[attr_type]
if attr_unpack == unpack_xor_address:
attributes[attr_name] = attr_unpack(v, transaction_id=transaction_id)
else:
attributes[attr_name] = attr_unpack(v)
if attr_name == 'FINGERPRINT':
if attributes[attr_name] != message_fingerprint(data[0:pos]):
raise ValueError('STUN message fingerprint does not match')
elif attr_name == 'MESSAGE-INTEGRITY':
if (integrity_key is not None and
attributes[attr_name] != message_integrity(data[0:pos], integrity_key)):
raise ValueError('STUN message integrity does not match')
pos += 4 + attr_len + pad_len
return Message(
message_method=message_type & 0x3eef,
message_class=message_type & 0x0110,
transaction_id=transaction_id,
attributes=attributes) | [
"def",
"parse_message",
"(",
"data",
",",
"integrity_key",
"=",
"None",
")",
":",
"if",
"len",
"(",
"data",
")",
"<",
"HEADER_LENGTH",
":",
"raise",
"ValueError",
"(",
"'STUN message length is less than 20 bytes'",
")",
"message_type",
",",
"length",
",",
"cookie",
",",
"transaction_id",
"=",
"unpack",
"(",
"'!HHI12s'",
",",
"data",
"[",
"0",
":",
"HEADER_LENGTH",
"]",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"HEADER_LENGTH",
"+",
"length",
":",
"raise",
"ValueError",
"(",
"'STUN message length does not match'",
")",
"attributes",
"=",
"OrderedDict",
"(",
")",
"pos",
"=",
"HEADER_LENGTH",
"while",
"pos",
"<=",
"len",
"(",
"data",
")",
"-",
"4",
":",
"attr_type",
",",
"attr_len",
"=",
"unpack",
"(",
"'!HH'",
",",
"data",
"[",
"pos",
":",
"pos",
"+",
"4",
"]",
")",
"v",
"=",
"data",
"[",
"pos",
"+",
"4",
":",
"pos",
"+",
"4",
"+",
"attr_len",
"]",
"pad_len",
"=",
"4",
"*",
"(",
"(",
"attr_len",
"+",
"3",
")",
"//",
"4",
")",
"-",
"attr_len",
"if",
"attr_type",
"in",
"ATTRIBUTES_BY_TYPE",
":",
"_",
",",
"attr_name",
",",
"attr_pack",
",",
"attr_unpack",
"=",
"ATTRIBUTES_BY_TYPE",
"[",
"attr_type",
"]",
"if",
"attr_unpack",
"==",
"unpack_xor_address",
":",
"attributes",
"[",
"attr_name",
"]",
"=",
"attr_unpack",
"(",
"v",
",",
"transaction_id",
"=",
"transaction_id",
")",
"else",
":",
"attributes",
"[",
"attr_name",
"]",
"=",
"attr_unpack",
"(",
"v",
")",
"if",
"attr_name",
"==",
"'FINGERPRINT'",
":",
"if",
"attributes",
"[",
"attr_name",
"]",
"!=",
"message_fingerprint",
"(",
"data",
"[",
"0",
":",
"pos",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'STUN message fingerprint does not match'",
")",
"elif",
"attr_name",
"==",
"'MESSAGE-INTEGRITY'",
":",
"if",
"(",
"integrity_key",
"is",
"not",
"None",
"and",
"attributes",
"[",
"attr_name",
"]",
"!=",
"message_integrity",
"(",
"data",
"[",
"0",
":",
"pos",
"]",
",",
"integrity_key",
")",
")",
":",
"raise",
"ValueError",
"(",
"'STUN message integrity does not match'",
")",
"pos",
"+=",
"4",
"+",
"attr_len",
"+",
"pad_len",
"return",
"Message",
"(",
"message_method",
"=",
"message_type",
"&",
"0x3eef",
",",
"message_class",
"=",
"message_type",
"&",
"0x0110",
",",
"transaction_id",
"=",
"transaction_id",
",",
"attributes",
"=",
"attributes",
")"
] | Parses a STUN message.
If the ``integrity_key`` parameter is given, the message's HMAC will be verified. | [
"Parses",
"a",
"STUN",
"message",
"."
] | a04d810d94ec2d00eca9ce01eacca74b3b086616 | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/stun.py#L268-L306 | train | 235,142 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.connection_made | def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""
Modified ``connection_made`` that supports upgrading our transport in
place using STARTTLS.
We set the _transport directly on the StreamReader, rather than calling
set_transport (which will raise an AssertionError on upgrade).
"""
if self._stream_reader is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_reader._transport = transport # type: ignore
self._over_ssl = transport.get_extra_info("sslcontext") is not None
self._stream_writer = asyncio.StreamWriter(
transport, self, self._stream_reader, self._loop
)
self._client_connected_cb( # type: ignore
self._stream_reader, self._stream_writer
) | python | def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""
Modified ``connection_made`` that supports upgrading our transport in
place using STARTTLS.
We set the _transport directly on the StreamReader, rather than calling
set_transport (which will raise an AssertionError on upgrade).
"""
if self._stream_reader is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_reader._transport = transport # type: ignore
self._over_ssl = transport.get_extra_info("sslcontext") is not None
self._stream_writer = asyncio.StreamWriter(
transport, self, self._stream_reader, self._loop
)
self._client_connected_cb( # type: ignore
self._stream_reader, self._stream_writer
) | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
":",
"asyncio",
".",
"BaseTransport",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stream_reader",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"self",
".",
"_stream_reader",
".",
"_transport",
"=",
"transport",
"# type: ignore",
"self",
".",
"_over_ssl",
"=",
"transport",
".",
"get_extra_info",
"(",
"\"sslcontext\"",
")",
"is",
"not",
"None",
"self",
".",
"_stream_writer",
"=",
"asyncio",
".",
"StreamWriter",
"(",
"transport",
",",
"self",
",",
"self",
".",
"_stream_reader",
",",
"self",
".",
"_loop",
")",
"self",
".",
"_client_connected_cb",
"(",
"# type: ignore",
"self",
".",
"_stream_reader",
",",
"self",
".",
"_stream_writer",
")"
] | Modified ``connection_made`` that supports upgrading our transport in
place using STARTTLS.
We set the _transport directly on the StreamReader, rather than calling
set_transport (which will raise an AssertionError on upgrade). | [
"Modified",
"connection_made",
"that",
"supports",
"upgrading",
"our",
"transport",
"in",
"place",
"using",
"STARTTLS",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L50-L68 | train | 235,143 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.upgrade_transport | def upgrade_transport(
self,
context: ssl.SSLContext,
server_hostname: str = None,
waiter: Awaitable = None,
) -> SSLProtocol:
"""
Upgrade our transport to TLS in place.
"""
if self._over_ssl:
raise RuntimeError("Already using TLS.")
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
transport = self._stream_reader._transport # type: ignore
tls_protocol = SSLProtocol(
self._loop,
self,
context,
waiter,
server_side=False,
server_hostname=server_hostname,
)
app_transport = tls_protocol._app_transport
# Use set_protocol if we can
if hasattr(transport, "set_protocol"):
transport.set_protocol(tls_protocol)
else:
transport._protocol = tls_protocol
self._stream_reader._transport = app_transport # type: ignore
self._stream_writer._transport = app_transport # type: ignore
tls_protocol.connection_made(transport)
self._over_ssl = True # type: bool
return tls_protocol | python | def upgrade_transport(
self,
context: ssl.SSLContext,
server_hostname: str = None,
waiter: Awaitable = None,
) -> SSLProtocol:
"""
Upgrade our transport to TLS in place.
"""
if self._over_ssl:
raise RuntimeError("Already using TLS.")
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
transport = self._stream_reader._transport # type: ignore
tls_protocol = SSLProtocol(
self._loop,
self,
context,
waiter,
server_side=False,
server_hostname=server_hostname,
)
app_transport = tls_protocol._app_transport
# Use set_protocol if we can
if hasattr(transport, "set_protocol"):
transport.set_protocol(tls_protocol)
else:
transport._protocol = tls_protocol
self._stream_reader._transport = app_transport # type: ignore
self._stream_writer._transport = app_transport # type: ignore
tls_protocol.connection_made(transport)
self._over_ssl = True # type: bool
return tls_protocol | [
"def",
"upgrade_transport",
"(",
"self",
",",
"context",
":",
"ssl",
".",
"SSLContext",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
"waiter",
":",
"Awaitable",
"=",
"None",
",",
")",
"->",
"SSLProtocol",
":",
"if",
"self",
".",
"_over_ssl",
":",
"raise",
"RuntimeError",
"(",
"\"Already using TLS.\"",
")",
"if",
"self",
".",
"_stream_reader",
"is",
"None",
"or",
"self",
".",
"_stream_writer",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"transport",
"=",
"self",
".",
"_stream_reader",
".",
"_transport",
"# type: ignore",
"tls_protocol",
"=",
"SSLProtocol",
"(",
"self",
".",
"_loop",
",",
"self",
",",
"context",
",",
"waiter",
",",
"server_side",
"=",
"False",
",",
"server_hostname",
"=",
"server_hostname",
",",
")",
"app_transport",
"=",
"tls_protocol",
".",
"_app_transport",
"# Use set_protocol if we can",
"if",
"hasattr",
"(",
"transport",
",",
"\"set_protocol\"",
")",
":",
"transport",
".",
"set_protocol",
"(",
"tls_protocol",
")",
"else",
":",
"transport",
".",
"_protocol",
"=",
"tls_protocol",
"self",
".",
"_stream_reader",
".",
"_transport",
"=",
"app_transport",
"# type: ignore",
"self",
".",
"_stream_writer",
".",
"_transport",
"=",
"app_transport",
"# type: ignore",
"tls_protocol",
".",
"connection_made",
"(",
"transport",
")",
"self",
".",
"_over_ssl",
"=",
"True",
"# type: bool",
"return",
"tls_protocol"
] | Upgrade our transport to TLS in place. | [
"Upgrade",
"our",
"transport",
"to",
"TLS",
"in",
"place",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L70-L109 | train | 235,144 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.read_response | async def read_response(self, timeout: NumType = None) -> SMTPResponse:
"""
Get a status reponse from the server.
Returns an SMTPResponse namedtuple consisting of:
- server response code (e.g. 250, or such, if all goes well)
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
"""
if self._stream_reader is None:
raise SMTPServerDisconnected("Client not connected")
code = None
response_lines = []
while True:
async with self._io_lock:
line = await self._readline(timeout=timeout)
try:
code = int(line[:3])
except ValueError:
pass
message = line[4:].strip(b" \t\r\n").decode("utf-8", "surrogateescape")
response_lines.append(message)
if line[3:4] != b"-":
break
full_message = "\n".join(response_lines)
if code is None:
raise SMTPResponseException(
SMTPStatus.invalid_response.value,
"Malformed SMTP response: {}".format(full_message),
)
return SMTPResponse(code, full_message) | python | async def read_response(self, timeout: NumType = None) -> SMTPResponse:
"""
Get a status reponse from the server.
Returns an SMTPResponse namedtuple consisting of:
- server response code (e.g. 250, or such, if all goes well)
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
"""
if self._stream_reader is None:
raise SMTPServerDisconnected("Client not connected")
code = None
response_lines = []
while True:
async with self._io_lock:
line = await self._readline(timeout=timeout)
try:
code = int(line[:3])
except ValueError:
pass
message = line[4:].strip(b" \t\r\n").decode("utf-8", "surrogateescape")
response_lines.append(message)
if line[3:4] != b"-":
break
full_message = "\n".join(response_lines)
if code is None:
raise SMTPResponseException(
SMTPStatus.invalid_response.value,
"Malformed SMTP response: {}".format(full_message),
)
return SMTPResponse(code, full_message) | [
"async",
"def",
"read_response",
"(",
"self",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
"->",
"SMTPResponse",
":",
"if",
"self",
".",
"_stream_reader",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"code",
"=",
"None",
"response_lines",
"=",
"[",
"]",
"while",
"True",
":",
"async",
"with",
"self",
".",
"_io_lock",
":",
"line",
"=",
"await",
"self",
".",
"_readline",
"(",
"timeout",
"=",
"timeout",
")",
"try",
":",
"code",
"=",
"int",
"(",
"line",
"[",
":",
"3",
"]",
")",
"except",
"ValueError",
":",
"pass",
"message",
"=",
"line",
"[",
"4",
":",
"]",
".",
"strip",
"(",
"b\" \\t\\r\\n\"",
")",
".",
"decode",
"(",
"\"utf-8\"",
",",
"\"surrogateescape\"",
")",
"response_lines",
".",
"append",
"(",
"message",
")",
"if",
"line",
"[",
"3",
":",
"4",
"]",
"!=",
"b\"-\"",
":",
"break",
"full_message",
"=",
"\"\\n\"",
".",
"join",
"(",
"response_lines",
")",
"if",
"code",
"is",
"None",
":",
"raise",
"SMTPResponseException",
"(",
"SMTPStatus",
".",
"invalid_response",
".",
"value",
",",
"\"Malformed SMTP response: {}\"",
".",
"format",
"(",
"full_message",
")",
",",
")",
"return",
"SMTPResponse",
"(",
"code",
",",
"full_message",
")"
] | Get a status reponse from the server.
Returns an SMTPResponse namedtuple consisting of:
- server response code (e.g. 250, or such, if all goes well)
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string). | [
"Get",
"a",
"status",
"reponse",
"from",
"the",
"server",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L111-L148 | train | 235,145 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.write_and_drain | async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None:
"""
Format a command and send it to the server.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_writer.write(data)
async with self._io_lock:
await self._drain_writer(timeout) | python | async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None:
"""
Format a command and send it to the server.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_writer.write(data)
async with self._io_lock:
await self._drain_writer(timeout) | [
"async",
"def",
"write_and_drain",
"(",
"self",
",",
"data",
":",
"bytes",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stream_writer",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"self",
".",
"_stream_writer",
".",
"write",
"(",
"data",
")",
"async",
"with",
"self",
".",
"_io_lock",
":",
"await",
"self",
".",
"_drain_writer",
"(",
"timeout",
")"
] | Format a command and send it to the server. | [
"Format",
"a",
"command",
"and",
"send",
"it",
"to",
"the",
"server",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L150-L160 | train | 235,146 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.write_message_data | async def write_message_data(self, data: bytes, timeout: NumType = None) -> None:
"""
Encode and write email message data.
Automatically quotes lines beginning with a period per RFC821.
Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n
characters.
"""
data = LINE_ENDINGS_REGEX.sub(b"\r\n", data)
data = PERIOD_REGEX.sub(b"..", data)
if not data.endswith(b"\r\n"):
data += b"\r\n"
data += b".\r\n"
await self.write_and_drain(data, timeout=timeout) | python | async def write_message_data(self, data: bytes, timeout: NumType = None) -> None:
"""
Encode and write email message data.
Automatically quotes lines beginning with a period per RFC821.
Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n
characters.
"""
data = LINE_ENDINGS_REGEX.sub(b"\r\n", data)
data = PERIOD_REGEX.sub(b"..", data)
if not data.endswith(b"\r\n"):
data += b"\r\n"
data += b".\r\n"
await self.write_and_drain(data, timeout=timeout) | [
"async",
"def",
"write_message_data",
"(",
"self",
",",
"data",
":",
"bytes",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
"->",
"None",
":",
"data",
"=",
"LINE_ENDINGS_REGEX",
".",
"sub",
"(",
"b\"\\r\\n\"",
",",
"data",
")",
"data",
"=",
"PERIOD_REGEX",
".",
"sub",
"(",
"b\"..\"",
",",
"data",
")",
"if",
"not",
"data",
".",
"endswith",
"(",
"b\"\\r\\n\"",
")",
":",
"data",
"+=",
"b\"\\r\\n\"",
"data",
"+=",
"b\".\\r\\n\"",
"await",
"self",
".",
"write_and_drain",
"(",
"data",
",",
"timeout",
"=",
"timeout",
")"
] | Encode and write email message data.
Automatically quotes lines beginning with a period per RFC821.
Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n
characters. | [
"Encode",
"and",
"write",
"email",
"message",
"data",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L162-L176 | train | 235,147 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.execute_command | async def execute_command(
self, *args: bytes, timeout: NumType = None
) -> SMTPResponse:
"""
Sends an SMTP command along with any args to the server, and returns
a response.
"""
command = b" ".join(args) + b"\r\n"
await self.write_and_drain(command, timeout=timeout)
response = await self.read_response(timeout=timeout)
return response | python | async def execute_command(
self, *args: bytes, timeout: NumType = None
) -> SMTPResponse:
"""
Sends an SMTP command along with any args to the server, and returns
a response.
"""
command = b" ".join(args) + b"\r\n"
await self.write_and_drain(command, timeout=timeout)
response = await self.read_response(timeout=timeout)
return response | [
"async",
"def",
"execute_command",
"(",
"self",
",",
"*",
"args",
":",
"bytes",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
"->",
"SMTPResponse",
":",
"command",
"=",
"b\" \"",
".",
"join",
"(",
"args",
")",
"+",
"b\"\\r\\n\"",
"await",
"self",
".",
"write_and_drain",
"(",
"command",
",",
"timeout",
"=",
"timeout",
")",
"response",
"=",
"await",
"self",
".",
"read_response",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"response"
] | Sends an SMTP command along with any args to the server, and returns
a response. | [
"Sends",
"an",
"SMTP",
"command",
"along",
"with",
"any",
"args",
"to",
"the",
"server",
"and",
"returns",
"a",
"response",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L178-L190 | train | 235,148 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.last_ehlo_response | def last_ehlo_response(self, response: SMTPResponse) -> None:
"""
When setting the last EHLO response, parse the message for supported
extensions and auth methods.
"""
extensions, auth_methods = parse_esmtp_extensions(response.message)
self._last_ehlo_response = response
self.esmtp_extensions = extensions
self.server_auth_methods = auth_methods
self.supports_esmtp = True | python | def last_ehlo_response(self, response: SMTPResponse) -> None:
"""
When setting the last EHLO response, parse the message for supported
extensions and auth methods.
"""
extensions, auth_methods = parse_esmtp_extensions(response.message)
self._last_ehlo_response = response
self.esmtp_extensions = extensions
self.server_auth_methods = auth_methods
self.supports_esmtp = True | [
"def",
"last_ehlo_response",
"(",
"self",
",",
"response",
":",
"SMTPResponse",
")",
"->",
"None",
":",
"extensions",
",",
"auth_methods",
"=",
"parse_esmtp_extensions",
"(",
"response",
".",
"message",
")",
"self",
".",
"_last_ehlo_response",
"=",
"response",
"self",
".",
"esmtp_extensions",
"=",
"extensions",
"self",
".",
"server_auth_methods",
"=",
"auth_methods",
"self",
".",
"supports_esmtp",
"=",
"True"
] | When setting the last EHLO response, parse the message for supported
extensions and auth methods. | [
"When",
"setting",
"the",
"last",
"EHLO",
"response",
"parse",
"the",
"message",
"for",
"supported",
"extensions",
"and",
"auth",
"methods",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L59-L68 | train | 235,149 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.helo | async def helo(
self, hostname: str = None, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send the SMTP HELO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
if hostname is None:
hostname = self.source_address
async with self._command_lock:
response = await self.execute_command(
b"HELO", hostname.encode("ascii"), timeout=timeout
)
self.last_helo_response = response
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response | python | async def helo(
self, hostname: str = None, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send the SMTP HELO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
if hostname is None:
hostname = self.source_address
async with self._command_lock:
response = await self.execute_command(
b"HELO", hostname.encode("ascii"), timeout=timeout
)
self.last_helo_response = response
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response | [
"async",
"def",
"helo",
"(",
"self",
",",
"hostname",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"self",
".",
"source_address",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"HELO\"",
",",
"hostname",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"timeout",
"=",
"timeout",
")",
"self",
".",
"last_helo_response",
"=",
"response",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPHeloError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send the SMTP HELO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code | [
"Send",
"the",
"SMTP",
"HELO",
"command",
".",
"Hostname",
"to",
"send",
"for",
"this",
"command",
"defaults",
"to",
"the",
"FQDN",
"of",
"the",
"local",
"host",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L86-L107 | train | 235,150 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.help | async def help(self, timeout: DefaultNumType = _default) -> str:
"""
Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"HELP", timeout=timeout)
success_codes = (
SMTPStatus.system_status_ok,
SMTPStatus.help_message,
SMTPStatus.completed,
)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message)
return response.message | python | async def help(self, timeout: DefaultNumType = _default) -> str:
"""
Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"HELP", timeout=timeout)
success_codes = (
SMTPStatus.system_status_ok,
SMTPStatus.help_message,
SMTPStatus.completed,
)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message)
return response.message | [
"async",
"def",
"help",
"(",
"self",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"str",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"HELP\"",
",",
"timeout",
"=",
"timeout",
")",
"success_codes",
"=",
"(",
"SMTPStatus",
".",
"system_status_ok",
",",
"SMTPStatus",
".",
"help_message",
",",
"SMTPStatus",
".",
"completed",
",",
")",
"if",
"response",
".",
"code",
"not",
"in",
"success_codes",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response",
".",
"message"
] | Send the SMTP HELP command, which responds with help text.
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"the",
"SMTP",
"HELP",
"command",
"which",
"responds",
"with",
"help",
"text",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L109-L127 | train | 235,151 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.noop | async def noop(self, timeout: DefaultNumType = _default) -> SMTPResponse:
"""
Send an SMTP NOOP command, which does nothing.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"NOOP", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | python | async def noop(self, timeout: DefaultNumType = _default) -> SMTPResponse:
"""
Send an SMTP NOOP command, which does nothing.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"NOOP", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | [
"async",
"def",
"noop",
"(",
"self",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"NOOP\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send an SMTP NOOP command, which does nothing.
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"an",
"SMTP",
"NOOP",
"command",
"which",
"does",
"nothing",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L145-L158 | train | 235,152 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.vrfy | async def vrfy(
self, address: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP VRFY command, which tests an address for validity.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
parsed_address = parse_address(address)
async with self._command_lock:
response = await self.execute_command(
b"VRFY", parsed_address.encode("ascii"), timeout=timeout
)
success_codes = (
SMTPStatus.completed,
SMTPStatus.will_forward,
SMTPStatus.cannot_vrfy,
)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message)
return response | python | async def vrfy(
self, address: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP VRFY command, which tests an address for validity.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
parsed_address = parse_address(address)
async with self._command_lock:
response = await self.execute_command(
b"VRFY", parsed_address.encode("ascii"), timeout=timeout
)
success_codes = (
SMTPStatus.completed,
SMTPStatus.will_forward,
SMTPStatus.cannot_vrfy,
)
if response.code not in success_codes:
raise SMTPResponseException(response.code, response.message)
return response | [
"async",
"def",
"vrfy",
"(",
"self",
",",
"address",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"parsed_address",
"=",
"parse_address",
"(",
"address",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"VRFY\"",
",",
"parsed_address",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"timeout",
"=",
"timeout",
")",
"success_codes",
"=",
"(",
"SMTPStatus",
".",
"completed",
",",
"SMTPStatus",
".",
"will_forward",
",",
"SMTPStatus",
".",
"cannot_vrfy",
",",
")",
"if",
"response",
".",
"code",
"not",
"in",
"success_codes",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send an SMTP VRFY command, which tests an address for validity.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"an",
"SMTP",
"VRFY",
"command",
"which",
"tests",
"an",
"address",
"for",
"validity",
".",
"Not",
"many",
"servers",
"support",
"this",
"command",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L160-L187 | train | 235,153 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.expn | async def expn(
self, address: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP EXPN command, which expands a mailing list.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
parsed_address = parse_address(address)
async with self._command_lock:
response = await self.execute_command(
b"EXPN", parsed_address.encode("ascii"), timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | python | async def expn(
self, address: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP EXPN command, which expands a mailing list.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
parsed_address = parse_address(address)
async with self._command_lock:
response = await self.execute_command(
b"EXPN", parsed_address.encode("ascii"), timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | [
"async",
"def",
"expn",
"(",
"self",
",",
"address",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"parsed_address",
"=",
"parse_address",
"(",
"address",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"EXPN\"",
",",
"parsed_address",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send an SMTP EXPN command, which expands a mailing list.
Not many servers support this command.
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"an",
"SMTP",
"EXPN",
"command",
"which",
"expands",
"a",
"mailing",
"list",
".",
"Not",
"many",
"servers",
"support",
"this",
"command",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L189-L210 | train | 235,154 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.quit | async def quit(self, timeout: DefaultNumType = _default) -> SMTPResponse:
"""
Send the SMTP QUIT command, which closes the connection.
Also closes the connection from our side after a response is received.
:raises SMTPResponseException: on unexpected server response code
"""
# Can't quit without HELO/EHLO
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"QUIT", timeout=timeout)
if response.code != SMTPStatus.closing:
raise SMTPResponseException(response.code, response.message)
self.close()
return response | python | async def quit(self, timeout: DefaultNumType = _default) -> SMTPResponse:
"""
Send the SMTP QUIT command, which closes the connection.
Also closes the connection from our side after a response is received.
:raises SMTPResponseException: on unexpected server response code
"""
# Can't quit without HELO/EHLO
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"QUIT", timeout=timeout)
if response.code != SMTPStatus.closing:
raise SMTPResponseException(response.code, response.message)
self.close()
return response | [
"async",
"def",
"quit",
"(",
"self",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"# Can't quit without HELO/EHLO",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"QUIT\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"closing",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"self",
".",
"close",
"(",
")",
"return",
"response"
] | Send the SMTP QUIT command, which closes the connection.
Also closes the connection from our side after a response is received.
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"the",
"SMTP",
"QUIT",
"command",
"which",
"closes",
"the",
"connection",
".",
"Also",
"closes",
"the",
"connection",
"from",
"our",
"side",
"after",
"a",
"response",
"is",
"received",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L212-L229 | train | 235,155 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.rcpt | async def rcpt(
self,
recipient: str,
options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
"""
Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
preceded by 'MAIL'.
:raises SMTPRecipientRefused: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
options_bytes = [option.encode("ascii") for option in options]
to = b"TO:" + quote_address(recipient).encode("ascii")
async with self._command_lock:
response = await self.execute_command(
b"RCPT", to, *options_bytes, timeout=timeout
)
success_codes = (SMTPStatus.completed, SMTPStatus.will_forward)
if response.code not in success_codes:
raise SMTPRecipientRefused(response.code, response.message, recipient)
return response | python | async def rcpt(
self,
recipient: str,
options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
"""
Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
preceded by 'MAIL'.
:raises SMTPRecipientRefused: on unexpected server response code
"""
await self._ehlo_or_helo_if_needed()
if options is None:
options = []
options_bytes = [option.encode("ascii") for option in options]
to = b"TO:" + quote_address(recipient).encode("ascii")
async with self._command_lock:
response = await self.execute_command(
b"RCPT", to, *options_bytes, timeout=timeout
)
success_codes = (SMTPStatus.completed, SMTPStatus.will_forward)
if response.code not in success_codes:
raise SMTPRecipientRefused(response.code, response.message, recipient)
return response | [
"async",
"def",
"rcpt",
"(",
"self",
",",
"recipient",
":",
"str",
",",
"options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"[",
"]",
"options_bytes",
"=",
"[",
"option",
".",
"encode",
"(",
"\"ascii\"",
")",
"for",
"option",
"in",
"options",
"]",
"to",
"=",
"b\"TO:\"",
"+",
"quote_address",
"(",
"recipient",
")",
".",
"encode",
"(",
"\"ascii\"",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"RCPT\"",
",",
"to",
",",
"*",
"options_bytes",
",",
"timeout",
"=",
"timeout",
")",
"success_codes",
"=",
"(",
"SMTPStatus",
".",
"completed",
",",
"SMTPStatus",
".",
"will_forward",
")",
"if",
"response",
".",
"code",
"not",
"in",
"success_codes",
":",
"raise",
"SMTPRecipientRefused",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
",",
"recipient",
")",
"return",
"response"
] | Send an SMTP RCPT command, which specifies a single recipient for
the message. This command is sent once per recipient and must be
preceded by 'MAIL'.
:raises SMTPRecipientRefused: on unexpected server response code | [
"Send",
"an",
"SMTP",
"RCPT",
"command",
"which",
"specifies",
"a",
"single",
"recipient",
"for",
"the",
"message",
".",
"This",
"command",
"is",
"sent",
"once",
"per",
"recipient",
"and",
"must",
"be",
"preceded",
"by",
"MAIL",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L261-L291 | train | 235,156 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.data | async def data(
self, message: Union[str, bytes], timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP DATA command, followed by the message given.
This method transfers the actual email content to the server.
:raises SMTPDataError: on unexpected server response code
:raises SMTPServerDisconnected: connection lost
"""
await self._ehlo_or_helo_if_needed()
# As data accesses protocol directly, some handling is required
self._raise_error_if_disconnected()
if timeout is _default:
timeout = self.timeout # type: ignore
if isinstance(message, str):
message = message.encode("ascii")
async with self._command_lock:
start_response = await self.execute_command(b"DATA", timeout=timeout)
if start_response.code != SMTPStatus.start_input:
raise SMTPDataError(start_response.code, start_response.message)
try:
await self.protocol.write_message_data( # type: ignore
message, timeout=timeout
)
response = await self.protocol.read_response( # type: ignore
timeout=timeout
)
except SMTPServerDisconnected as exc:
self.close()
raise exc
if response.code != SMTPStatus.completed:
raise SMTPDataError(response.code, response.message)
return response | python | async def data(
self, message: Union[str, bytes], timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send an SMTP DATA command, followed by the message given.
This method transfers the actual email content to the server.
:raises SMTPDataError: on unexpected server response code
:raises SMTPServerDisconnected: connection lost
"""
await self._ehlo_or_helo_if_needed()
# As data accesses protocol directly, some handling is required
self._raise_error_if_disconnected()
if timeout is _default:
timeout = self.timeout # type: ignore
if isinstance(message, str):
message = message.encode("ascii")
async with self._command_lock:
start_response = await self.execute_command(b"DATA", timeout=timeout)
if start_response.code != SMTPStatus.start_input:
raise SMTPDataError(start_response.code, start_response.message)
try:
await self.protocol.write_message_data( # type: ignore
message, timeout=timeout
)
response = await self.protocol.read_response( # type: ignore
timeout=timeout
)
except SMTPServerDisconnected as exc:
self.close()
raise exc
if response.code != SMTPStatus.completed:
raise SMTPDataError(response.code, response.message)
return response | [
"async",
"def",
"data",
"(",
"self",
",",
"message",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"# As data accesses protocol directly, some handling is required",
"self",
".",
"_raise_error_if_disconnected",
"(",
")",
"if",
"timeout",
"is",
"_default",
":",
"timeout",
"=",
"self",
".",
"timeout",
"# type: ignore",
"if",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"\"ascii\"",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"start_response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"DATA\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"start_response",
".",
"code",
"!=",
"SMTPStatus",
".",
"start_input",
":",
"raise",
"SMTPDataError",
"(",
"start_response",
".",
"code",
",",
"start_response",
".",
"message",
")",
"try",
":",
"await",
"self",
".",
"protocol",
".",
"write_message_data",
"(",
"# type: ignore",
"message",
",",
"timeout",
"=",
"timeout",
")",
"response",
"=",
"await",
"self",
".",
"protocol",
".",
"read_response",
"(",
"# type: ignore",
"timeout",
"=",
"timeout",
")",
"except",
"SMTPServerDisconnected",
"as",
"exc",
":",
"self",
".",
"close",
"(",
")",
"raise",
"exc",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPDataError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send an SMTP DATA command, followed by the message given.
This method transfers the actual email content to the server.
:raises SMTPDataError: on unexpected server response code
:raises SMTPServerDisconnected: connection lost | [
"Send",
"an",
"SMTP",
"DATA",
"command",
"followed",
"by",
"the",
"message",
"given",
".",
"This",
"method",
"transfers",
"the",
"actual",
"email",
"content",
"to",
"the",
"server",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L293-L333 | train | 235,157 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.ehlo | async def ehlo(
self, hostname: str = None, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send the SMTP EHLO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
if hostname is None:
hostname = self.source_address
async with self._command_lock:
response = await self.execute_command(
b"EHLO", hostname.encode("ascii"), timeout=timeout
)
self.last_ehlo_response = response
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response | python | async def ehlo(
self, hostname: str = None, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Send the SMTP EHLO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code
"""
if hostname is None:
hostname = self.source_address
async with self._command_lock:
response = await self.execute_command(
b"EHLO", hostname.encode("ascii"), timeout=timeout
)
self.last_ehlo_response = response
if response.code != SMTPStatus.completed:
raise SMTPHeloError(response.code, response.message)
return response | [
"async",
"def",
"ehlo",
"(",
"self",
",",
"hostname",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"self",
".",
"source_address",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"EHLO\"",
",",
"hostname",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"timeout",
"=",
"timeout",
")",
"self",
".",
"last_ehlo_response",
"=",
"response",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPHeloError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | Send the SMTP EHLO command.
Hostname to send for this command defaults to the FQDN of the local
host.
:raises SMTPHeloError: on unexpected server response code | [
"Send",
"the",
"SMTP",
"EHLO",
"command",
".",
"Hostname",
"to",
"send",
"for",
"this",
"command",
"defaults",
"to",
"the",
"FQDN",
"of",
"the",
"local",
"host",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L337-L359 | train | 235,158 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP._reset_server_state | def _reset_server_state(self) -> None:
"""
Clear stored information about the server.
"""
self.last_helo_response = None
self._last_ehlo_response = None
self.esmtp_extensions = {}
self.supports_esmtp = False
self.server_auth_methods = [] | python | def _reset_server_state(self) -> None:
"""
Clear stored information about the server.
"""
self.last_helo_response = None
self._last_ehlo_response = None
self.esmtp_extensions = {}
self.supports_esmtp = False
self.server_auth_methods = [] | [
"def",
"_reset_server_state",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"last_helo_response",
"=",
"None",
"self",
".",
"_last_ehlo_response",
"=",
"None",
"self",
".",
"esmtp_extensions",
"=",
"{",
"}",
"self",
".",
"supports_esmtp",
"=",
"False",
"self",
".",
"server_auth_methods",
"=",
"[",
"]"
] | Clear stored information about the server. | [
"Clear",
"stored",
"information",
"about",
"the",
"server",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L384-L392 | train | 235,159 |
cole/aiosmtplib | src/aiosmtplib/auth.py | SMTPAuth.supported_auth_methods | def supported_auth_methods(self) -> List[str]:
"""
Get all AUTH methods supported by the both server and by us.
"""
return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods] | python | def supported_auth_methods(self) -> List[str]:
"""
Get all AUTH methods supported by the both server and by us.
"""
return [auth for auth in self.AUTH_METHODS if auth in self.server_auth_methods] | [
"def",
"supported_auth_methods",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"auth",
"for",
"auth",
"in",
"self",
".",
"AUTH_METHODS",
"if",
"auth",
"in",
"self",
".",
"server_auth_methods",
"]"
] | Get all AUTH methods supported by the both server and by us. | [
"Get",
"all",
"AUTH",
"methods",
"supported",
"by",
"the",
"both",
"server",
"and",
"by",
"us",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L40-L44 | train | 235,160 |
cole/aiosmtplib | src/aiosmtplib/auth.py | SMTPAuth.login | async def login(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Tries to login with supported auth methods.
Some servers advertise authentication methods they don't really
support, so if authentication fails, we continue until we've tried
all methods.
"""
await self._ehlo_or_helo_if_needed()
if not self.supports_extension("auth"):
raise SMTPException("SMTP AUTH extension not supported by server.")
response = None # type: Optional[SMTPResponse]
exception = None # type: Optional[SMTPAuthenticationError]
for auth_name in self.supported_auth_methods:
method_name = "auth_{}".format(auth_name.replace("-", ""))
try:
auth_method = getattr(self, method_name)
except AttributeError:
raise RuntimeError(
"Missing handler for auth method {}".format(auth_name)
)
try:
response = await auth_method(username, password, timeout=timeout)
except SMTPAuthenticationError as exc:
exception = exc
else:
# No exception means we're good
break
if response is None:
raise exception or SMTPException("No suitable authentication method found.")
return response | python | async def login(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Tries to login with supported auth methods.
Some servers advertise authentication methods they don't really
support, so if authentication fails, we continue until we've tried
all methods.
"""
await self._ehlo_or_helo_if_needed()
if not self.supports_extension("auth"):
raise SMTPException("SMTP AUTH extension not supported by server.")
response = None # type: Optional[SMTPResponse]
exception = None # type: Optional[SMTPAuthenticationError]
for auth_name in self.supported_auth_methods:
method_name = "auth_{}".format(auth_name.replace("-", ""))
try:
auth_method = getattr(self, method_name)
except AttributeError:
raise RuntimeError(
"Missing handler for auth method {}".format(auth_name)
)
try:
response = await auth_method(username, password, timeout=timeout)
except SMTPAuthenticationError as exc:
exception = exc
else:
# No exception means we're good
break
if response is None:
raise exception or SMTPException("No suitable authentication method found.")
return response | [
"async",
"def",
"login",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"if",
"not",
"self",
".",
"supports_extension",
"(",
"\"auth\"",
")",
":",
"raise",
"SMTPException",
"(",
"\"SMTP AUTH extension not supported by server.\"",
")",
"response",
"=",
"None",
"# type: Optional[SMTPResponse]",
"exception",
"=",
"None",
"# type: Optional[SMTPAuthenticationError]",
"for",
"auth_name",
"in",
"self",
".",
"supported_auth_methods",
":",
"method_name",
"=",
"\"auth_{}\"",
".",
"format",
"(",
"auth_name",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
")",
"try",
":",
"auth_method",
"=",
"getattr",
"(",
"self",
",",
"method_name",
")",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"\"Missing handler for auth method {}\"",
".",
"format",
"(",
"auth_name",
")",
")",
"try",
":",
"response",
"=",
"await",
"auth_method",
"(",
"username",
",",
"password",
",",
"timeout",
"=",
"timeout",
")",
"except",
"SMTPAuthenticationError",
"as",
"exc",
":",
"exception",
"=",
"exc",
"else",
":",
"# No exception means we're good",
"break",
"if",
"response",
"is",
"None",
":",
"raise",
"exception",
"or",
"SMTPException",
"(",
"\"No suitable authentication method found.\"",
")",
"return",
"response"
] | Tries to login with supported auth methods.
Some servers advertise authentication methods they don't really
support, so if authentication fails, we continue until we've tried
all methods. | [
"Tries",
"to",
"login",
"with",
"supported",
"auth",
"methods",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L46-L82 | train | 235,161 |
cole/aiosmtplib | src/aiosmtplib/auth.py | SMTPAuth.auth_crammd5 | async def auth_crammd5(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+
dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
"""
async with self._command_lock:
initial_response = await self.execute_command(
b"AUTH", b"CRAM-MD5", timeout=timeout
)
if initial_response.code != SMTPStatus.auth_continue:
raise SMTPAuthenticationError(
initial_response.code, initial_response.message
)
password_bytes = password.encode("ascii")
username_bytes = username.encode("ascii")
response_bytes = initial_response.message.encode("ascii")
verification_bytes = crammd5_verify(
username_bytes, password_bytes, response_bytes
)
response = await self.execute_command(verification_bytes)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | python | async def auth_crammd5(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+
dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
"""
async with self._command_lock:
initial_response = await self.execute_command(
b"AUTH", b"CRAM-MD5", timeout=timeout
)
if initial_response.code != SMTPStatus.auth_continue:
raise SMTPAuthenticationError(
initial_response.code, initial_response.message
)
password_bytes = password.encode("ascii")
username_bytes = username.encode("ascii")
response_bytes = initial_response.message.encode("ascii")
verification_bytes = crammd5_verify(
username_bytes, password_bytes, response_bytes
)
response = await self.execute_command(verification_bytes)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | [
"async",
"def",
"auth_crammd5",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"async",
"with",
"self",
".",
"_command_lock",
":",
"initial_response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"AUTH\"",
",",
"b\"CRAM-MD5\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"initial_response",
".",
"code",
"!=",
"SMTPStatus",
".",
"auth_continue",
":",
"raise",
"SMTPAuthenticationError",
"(",
"initial_response",
".",
"code",
",",
"initial_response",
".",
"message",
")",
"password_bytes",
"=",
"password",
".",
"encode",
"(",
"\"ascii\"",
")",
"username_bytes",
"=",
"username",
".",
"encode",
"(",
"\"ascii\"",
")",
"response_bytes",
"=",
"initial_response",
".",
"message",
".",
"encode",
"(",
"\"ascii\"",
")",
"verification_bytes",
"=",
"crammd5_verify",
"(",
"username_bytes",
",",
"password_bytes",
",",
"response_bytes",
")",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"verification_bytes",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"auth_successful",
":",
"raise",
"SMTPAuthenticationError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+
dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw | [
"CRAM",
"-",
"MD5",
"auth",
"uses",
"the",
"password",
"as",
"a",
"shared",
"secret",
"to",
"MD5",
"the",
"server",
"s",
"response",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L84-L122 | train | 235,162 |
cole/aiosmtplib | src/aiosmtplib/auth.py | SMTPAuth.auth_plain | async def auth_plain(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
PLAIN auth encodes the username and password in one Base64 encoded
string. No verification message is required.
Example::
220-esmtp.example.com
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
235 ok, go ahead (#2.0.0)
"""
username_bytes = username.encode("ascii")
password_bytes = password.encode("ascii")
username_and_password = b"\0" + username_bytes + b"\0" + password_bytes
encoded = base64.b64encode(username_and_password)
async with self._command_lock:
response = await self.execute_command(
b"AUTH", b"PLAIN", encoded, timeout=timeout
)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | python | async def auth_plain(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
PLAIN auth encodes the username and password in one Base64 encoded
string. No verification message is required.
Example::
220-esmtp.example.com
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
235 ok, go ahead (#2.0.0)
"""
username_bytes = username.encode("ascii")
password_bytes = password.encode("ascii")
username_and_password = b"\0" + username_bytes + b"\0" + password_bytes
encoded = base64.b64encode(username_and_password)
async with self._command_lock:
response = await self.execute_command(
b"AUTH", b"PLAIN", encoded, timeout=timeout
)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | [
"async",
"def",
"auth_plain",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"username_bytes",
"=",
"username",
".",
"encode",
"(",
"\"ascii\"",
")",
"password_bytes",
"=",
"password",
".",
"encode",
"(",
"\"ascii\"",
")",
"username_and_password",
"=",
"b\"\\0\"",
"+",
"username_bytes",
"+",
"b\"\\0\"",
"+",
"password_bytes",
"encoded",
"=",
"base64",
".",
"b64encode",
"(",
"username_and_password",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"AUTH\"",
",",
"b\"PLAIN\"",
",",
"encoded",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"auth_successful",
":",
"raise",
"SMTPAuthenticationError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | PLAIN auth encodes the username and password in one Base64 encoded
string. No verification message is required.
Example::
220-esmtp.example.com
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
235 ok, go ahead (#2.0.0) | [
"PLAIN",
"auth",
"encodes",
"the",
"username",
"and",
"password",
"in",
"one",
"Base64",
"encoded",
"string",
".",
"No",
"verification",
"message",
"is",
"required",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L124-L151 | train | 235,163 |
cole/aiosmtplib | src/aiosmtplib/auth.py | SMTPAuth.auth_login | async def auth_login(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
LOGIN auth sends the Base64 encoded username and password in sequence.
Example::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
Note that there is an alternate version sends the username
as a separate command::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login
334 VXNlcm5hbWU6
avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
However, since most servers seem to support both, we send the username
with the initial request.
"""
encoded_username = base64.b64encode(username.encode("ascii"))
encoded_password = base64.b64encode(password.encode("ascii"))
async with self._command_lock:
initial_response = await self.execute_command(
b"AUTH", b"LOGIN", encoded_username, timeout=timeout
)
if initial_response.code != SMTPStatus.auth_continue:
raise SMTPAuthenticationError(
initial_response.code, initial_response.message
)
response = await self.execute_command(encoded_password, timeout=timeout)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | python | async def auth_login(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
LOGIN auth sends the Base64 encoded username and password in sequence.
Example::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
Note that there is an alternate version sends the username
as a separate command::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login
334 VXNlcm5hbWU6
avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
However, since most servers seem to support both, we send the username
with the initial request.
"""
encoded_username = base64.b64encode(username.encode("ascii"))
encoded_password = base64.b64encode(password.encode("ascii"))
async with self._command_lock:
initial_response = await self.execute_command(
b"AUTH", b"LOGIN", encoded_username, timeout=timeout
)
if initial_response.code != SMTPStatus.auth_continue:
raise SMTPAuthenticationError(
initial_response.code, initial_response.message
)
response = await self.execute_command(encoded_password, timeout=timeout)
if response.code != SMTPStatus.auth_successful:
raise SMTPAuthenticationError(response.code, response.message)
return response | [
"async",
"def",
"auth_login",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"encoded_username",
"=",
"base64",
".",
"b64encode",
"(",
"username",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"encoded_password",
"=",
"base64",
".",
"b64encode",
"(",
"password",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"initial_response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"AUTH\"",
",",
"b\"LOGIN\"",
",",
"encoded_username",
",",
"timeout",
"=",
"timeout",
")",
"if",
"initial_response",
".",
"code",
"!=",
"SMTPStatus",
".",
"auth_continue",
":",
"raise",
"SMTPAuthenticationError",
"(",
"initial_response",
".",
"code",
",",
"initial_response",
".",
"message",
")",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"encoded_password",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"auth_successful",
":",
"raise",
"SMTPAuthenticationError",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
] | LOGIN auth sends the Base64 encoded username and password in sequence.
Example::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
Note that there is an alternate version sends the username
as a separate command::
250 AUTH LOGIN PLAIN CRAM-MD5
auth login
334 VXNlcm5hbWU6
avlsdkfj
334 UGFzc3dvcmQ6
avlsdkfj
However, since most servers seem to support both, we send the username
with the initial request. | [
"LOGIN",
"auth",
"sends",
"the",
"Base64",
"encoded",
"username",
"and",
"password",
"in",
"sequence",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L153-L197 | train | 235,164 |
cole/aiosmtplib | src/aiosmtplib/email.py | parse_address | def parse_address(address: str) -> str:
"""
Parse an email address, falling back to the raw string given.
"""
display_name, parsed_address = email.utils.parseaddr(address)
return parsed_address or address | python | def parse_address(address: str) -> str:
"""
Parse an email address, falling back to the raw string given.
"""
display_name, parsed_address = email.utils.parseaddr(address)
return parsed_address or address | [
"def",
"parse_address",
"(",
"address",
":",
"str",
")",
"->",
"str",
":",
"display_name",
",",
"parsed_address",
"=",
"email",
".",
"utils",
".",
"parseaddr",
"(",
"address",
")",
"return",
"parsed_address",
"or",
"address"
] | Parse an email address, falling back to the raw string given. | [
"Parse",
"an",
"email",
"address",
"falling",
"back",
"to",
"the",
"raw",
"string",
"given",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L16-L22 | train | 235,165 |
cole/aiosmtplib | src/aiosmtplib/email.py | quote_address | def quote_address(address: str) -> str:
"""
Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything email.utils.parseaddr can handle.
"""
display_name, parsed_address = email.utils.parseaddr(address)
if parsed_address:
quoted_address = "<{}>".format(parsed_address)
# parseaddr couldn't parse it, use it as is and hope for the best.
else:
quoted_address = "<{}>".format(address.strip())
return quoted_address | python | def quote_address(address: str) -> str:
"""
Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything email.utils.parseaddr can handle.
"""
display_name, parsed_address = email.utils.parseaddr(address)
if parsed_address:
quoted_address = "<{}>".format(parsed_address)
# parseaddr couldn't parse it, use it as is and hope for the best.
else:
quoted_address = "<{}>".format(address.strip())
return quoted_address | [
"def",
"quote_address",
"(",
"address",
":",
"str",
")",
"->",
"str",
":",
"display_name",
",",
"parsed_address",
"=",
"email",
".",
"utils",
".",
"parseaddr",
"(",
"address",
")",
"if",
"parsed_address",
":",
"quoted_address",
"=",
"\"<{}>\"",
".",
"format",
"(",
"parsed_address",
")",
"# parseaddr couldn't parse it, use it as is and hope for the best.",
"else",
":",
"quoted_address",
"=",
"\"<{}>\"",
".",
"format",
"(",
"address",
".",
"strip",
"(",
")",
")",
"return",
"quoted_address"
] | Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything email.utils.parseaddr can handle. | [
"Quote",
"a",
"subset",
"of",
"the",
"email",
"addresses",
"defined",
"by",
"RFC",
"821",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L25-L38 | train | 235,166 |
cole/aiosmtplib | src/aiosmtplib/email.py | _extract_sender | def _extract_sender(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> str:
"""
Extract the sender from the message object given.
"""
if resent_dates:
sender_header = "Resent-Sender"
from_header = "Resent-From"
else:
sender_header = "Sender"
from_header = "From"
# Prefer the sender field per RFC 2822:3.6.2.
if sender_header in message:
sender = message[sender_header]
else:
sender = message[from_header]
return str(sender) if sender else "" | python | def _extract_sender(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> str:
"""
Extract the sender from the message object given.
"""
if resent_dates:
sender_header = "Resent-Sender"
from_header = "Resent-From"
else:
sender_header = "Sender"
from_header = "From"
# Prefer the sender field per RFC 2822:3.6.2.
if sender_header in message:
sender = message[sender_header]
else:
sender = message[from_header]
return str(sender) if sender else "" | [
"def",
"_extract_sender",
"(",
"message",
":",
"Message",
",",
"resent_dates",
":",
"List",
"[",
"Union",
"[",
"str",
",",
"Header",
"]",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"resent_dates",
":",
"sender_header",
"=",
"\"Resent-Sender\"",
"from_header",
"=",
"\"Resent-From\"",
"else",
":",
"sender_header",
"=",
"\"Sender\"",
"from_header",
"=",
"\"From\"",
"# Prefer the sender field per RFC 2822:3.6.2.",
"if",
"sender_header",
"in",
"message",
":",
"sender",
"=",
"message",
"[",
"sender_header",
"]",
"else",
":",
"sender",
"=",
"message",
"[",
"from_header",
"]",
"return",
"str",
"(",
"sender",
")",
"if",
"sender",
"else",
"\"\""
] | Extract the sender from the message object given. | [
"Extract",
"the",
"sender",
"from",
"the",
"message",
"object",
"given",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L62-L81 | train | 235,167 |
cole/aiosmtplib | src/aiosmtplib/email.py | _extract_recipients | def _extract_recipients(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> List[str]:
"""
Extract the recipients from the message object given.
"""
recipients = [] # type: List[str]
if resent_dates:
recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
else:
recipient_headers = ("To", "Cc", "Bcc")
for header in recipient_headers:
recipients.extend(message.get_all(header, [])) # type: ignore
parsed_recipients = [
str(email.utils.formataddr(address))
for address in email.utils.getaddresses(recipients)
]
return parsed_recipients | python | def _extract_recipients(
message: Message, resent_dates: List[Union[str, Header]] = None
) -> List[str]:
"""
Extract the recipients from the message object given.
"""
recipients = [] # type: List[str]
if resent_dates:
recipient_headers = ("Resent-To", "Resent-Cc", "Resent-Bcc")
else:
recipient_headers = ("To", "Cc", "Bcc")
for header in recipient_headers:
recipients.extend(message.get_all(header, [])) # type: ignore
parsed_recipients = [
str(email.utils.formataddr(address))
for address in email.utils.getaddresses(recipients)
]
return parsed_recipients | [
"def",
"_extract_recipients",
"(",
"message",
":",
"Message",
",",
"resent_dates",
":",
"List",
"[",
"Union",
"[",
"str",
",",
"Header",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"recipients",
"=",
"[",
"]",
"# type: List[str]",
"if",
"resent_dates",
":",
"recipient_headers",
"=",
"(",
"\"Resent-To\"",
",",
"\"Resent-Cc\"",
",",
"\"Resent-Bcc\"",
")",
"else",
":",
"recipient_headers",
"=",
"(",
"\"To\"",
",",
"\"Cc\"",
",",
"\"Bcc\"",
")",
"for",
"header",
"in",
"recipient_headers",
":",
"recipients",
".",
"extend",
"(",
"message",
".",
"get_all",
"(",
"header",
",",
"[",
"]",
")",
")",
"# type: ignore",
"parsed_recipients",
"=",
"[",
"str",
"(",
"email",
".",
"utils",
".",
"formataddr",
"(",
"address",
")",
")",
"for",
"address",
"in",
"email",
".",
"utils",
".",
"getaddresses",
"(",
"recipients",
")",
"]",
"return",
"parsed_recipients"
] | Extract the recipients from the message object given. | [
"Extract",
"the",
"recipients",
"from",
"the",
"message",
"object",
"given",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L84-L105 | train | 235,168 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection.execute_command | async def execute_command(
self, *args: bytes, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Check that we're connected, if we got a timeout value, and then
pass the command to the protocol.
:raises SMTPServerDisconnected: connection lost
"""
if timeout is _default:
timeout = self.timeout # type: ignore
self._raise_error_if_disconnected()
try:
response = await self.protocol.execute_command( # type: ignore
*args, timeout=timeout
)
except SMTPServerDisconnected:
# On disconnect, clean up the connection.
self.close()
raise
# If the server is unavailable, be nice and close the connection
if response.code == SMTPStatus.domain_unavailable:
self.close()
return response | python | async def execute_command(
self, *args: bytes, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
Check that we're connected, if we got a timeout value, and then
pass the command to the protocol.
:raises SMTPServerDisconnected: connection lost
"""
if timeout is _default:
timeout = self.timeout # type: ignore
self._raise_error_if_disconnected()
try:
response = await self.protocol.execute_command( # type: ignore
*args, timeout=timeout
)
except SMTPServerDisconnected:
# On disconnect, clean up the connection.
self.close()
raise
# If the server is unavailable, be nice and close the connection
if response.code == SMTPStatus.domain_unavailable:
self.close()
return response | [
"async",
"def",
"execute_command",
"(",
"self",
",",
"*",
"args",
":",
"bytes",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"if",
"timeout",
"is",
"_default",
":",
"timeout",
"=",
"self",
".",
"timeout",
"# type: ignore",
"self",
".",
"_raise_error_if_disconnected",
"(",
")",
"try",
":",
"response",
"=",
"await",
"self",
".",
"protocol",
".",
"execute_command",
"(",
"# type: ignore",
"*",
"args",
",",
"timeout",
"=",
"timeout",
")",
"except",
"SMTPServerDisconnected",
":",
"# On disconnect, clean up the connection.",
"self",
".",
"close",
"(",
")",
"raise",
"# If the server is unavailable, be nice and close the connection",
"if",
"response",
".",
"code",
"==",
"SMTPStatus",
".",
"domain_unavailable",
":",
"self",
".",
"close",
"(",
")",
"return",
"response"
] | Check that we're connected, if we got a timeout value, and then
pass the command to the protocol.
:raises SMTPServerDisconnected: connection lost | [
"Check",
"that",
"we",
"re",
"connected",
"if",
"we",
"got",
"a",
"timeout",
"value",
"and",
"then",
"pass",
"the",
"command",
"to",
"the",
"protocol",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L274-L301 | train | 235,169 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection._get_tls_context | def _get_tls_context(self) -> ssl.SSLContext:
"""
Build an SSLContext object from the options we've been given.
"""
if self.tls_context is not None:
context = self.tls_context
else:
# SERVER_AUTH is what we want for a client side socket
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.check_hostname = bool(self.validate_certs)
if self.validate_certs:
context.verify_mode = ssl.CERT_REQUIRED
else:
context.verify_mode = ssl.CERT_NONE
if self.cert_bundle is not None:
context.load_verify_locations(cafile=self.cert_bundle)
if self.client_cert is not None:
context.load_cert_chain(self.client_cert, keyfile=self.client_key)
return context | python | def _get_tls_context(self) -> ssl.SSLContext:
"""
Build an SSLContext object from the options we've been given.
"""
if self.tls_context is not None:
context = self.tls_context
else:
# SERVER_AUTH is what we want for a client side socket
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.check_hostname = bool(self.validate_certs)
if self.validate_certs:
context.verify_mode = ssl.CERT_REQUIRED
else:
context.verify_mode = ssl.CERT_NONE
if self.cert_bundle is not None:
context.load_verify_locations(cafile=self.cert_bundle)
if self.client_cert is not None:
context.load_cert_chain(self.client_cert, keyfile=self.client_key)
return context | [
"def",
"_get_tls_context",
"(",
"self",
")",
"->",
"ssl",
".",
"SSLContext",
":",
"if",
"self",
".",
"tls_context",
"is",
"not",
"None",
":",
"context",
"=",
"self",
".",
"tls_context",
"else",
":",
"# SERVER_AUTH is what we want for a client side socket",
"context",
"=",
"ssl",
".",
"create_default_context",
"(",
"ssl",
".",
"Purpose",
".",
"SERVER_AUTH",
")",
"context",
".",
"check_hostname",
"=",
"bool",
"(",
"self",
".",
"validate_certs",
")",
"if",
"self",
".",
"validate_certs",
":",
"context",
".",
"verify_mode",
"=",
"ssl",
".",
"CERT_REQUIRED",
"else",
":",
"context",
".",
"verify_mode",
"=",
"ssl",
".",
"CERT_NONE",
"if",
"self",
".",
"cert_bundle",
"is",
"not",
"None",
":",
"context",
".",
"load_verify_locations",
"(",
"cafile",
"=",
"self",
".",
"cert_bundle",
")",
"if",
"self",
".",
"client_cert",
"is",
"not",
"None",
":",
"context",
".",
"load_cert_chain",
"(",
"self",
".",
"client_cert",
",",
"keyfile",
"=",
"self",
".",
"client_key",
")",
"return",
"context"
] | Build an SSLContext object from the options we've been given. | [
"Build",
"an",
"SSLContext",
"object",
"from",
"the",
"options",
"we",
"ve",
"been",
"given",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L306-L327 | train | 235,170 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection._raise_error_if_disconnected | def _raise_error_if_disconnected(self) -> None:
"""
See if we're still connected, and if not, raise
``SMTPServerDisconnected``.
"""
if (
self.transport is None
or self.protocol is None
or self.transport.is_closing()
):
self.close()
raise SMTPServerDisconnected("Disconnected from SMTP server") | python | def _raise_error_if_disconnected(self) -> None:
"""
See if we're still connected, and if not, raise
``SMTPServerDisconnected``.
"""
if (
self.transport is None
or self.protocol is None
or self.transport.is_closing()
):
self.close()
raise SMTPServerDisconnected("Disconnected from SMTP server") | [
"def",
"_raise_error_if_disconnected",
"(",
"self",
")",
"->",
"None",
":",
"if",
"(",
"self",
".",
"transport",
"is",
"None",
"or",
"self",
".",
"protocol",
"is",
"None",
"or",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
")",
":",
"self",
".",
"close",
"(",
")",
"raise",
"SMTPServerDisconnected",
"(",
"\"Disconnected from SMTP server\"",
")"
] | See if we're still connected, and if not, raise
``SMTPServerDisconnected``. | [
"See",
"if",
"we",
"re",
"still",
"connected",
"and",
"if",
"not",
"raise",
"SMTPServerDisconnected",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L329-L340 | train | 235,171 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP.sendmail | async def sendmail(
self,
sender: str,
recipients: RecipientsType,
message: Union[str, bytes],
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
"""
This command performs an entire mail transaction.
The arguments are:
- sender: The address sending this mail.
- recipients: A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
- message: The message string to send.
- mail_options: List of options (such as ESMTP 8bitmime) for the
MAIL command.
- rcpt_options: List of options (such as DSN commands) for all the
RCPT commands.
message must be a string containing characters in the ASCII range.
The string is encoded to bytes using the ascii codec, and lone \\\\r
and \\\\n characters are converted to \\\\r\\\\n characters.
If there has been no previous HELO or EHLO command this session, this
method tries EHLO first.
This method will return normally if the mail is accepted for at least
one recipient. It returns a tuple consisting of:
- an error dictionary, with one entry for each recipient that was
refused. Each entry contains a tuple of the SMTP error code
and the accompanying error message sent by the server.
- the message sent by the server in response to the DATA command
(often containing a message id)
Example:
>>> loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> loop.run_until_complete(smtp.connect())
(220, ...)
>>> recipients = ["one@one.org", "two@two.org", "3@three.org"]
>>> message = "From: Me@my.org\\nSubject: testing\\nHello World"
>>> send_coro = smtp.sendmail("me@my.org", recipients, message)
>>> loop.run_until_complete(send_coro)
({}, 'OK')
>>> loop.run_until_complete(smtp.quit())
(221, Bye)
In the above example, the message was accepted for delivery for all
three addresses. If delivery had been only successful to two
of the three addresses, and one was rejected, the response would look
something like::
(
{"nobody@three.org": (550, "User unknown")},
"Written safely to disk. #902487694.289148.12219.",
)
If delivery is not successful to any addresses,
:exc:`.SMTPRecipientsRefused` is raised.
If :exc:`.SMTPResponseException` is raised by this method, we try to
send an RSET command to reset the server envelope automatically for
the next attempt.
:raises SMTPRecipientsRefused: delivery to all recipients failed
:raises SMTPResponseException: on invalid response
"""
if isinstance(recipients, str):
recipients = [recipients]
else:
recipients = list(recipients)
if mail_options is None:
mail_options = []
else:
mail_options = list(mail_options)
if rcpt_options is None:
rcpt_options = []
else:
rcpt_options = list(rcpt_options)
async with self._sendmail_lock:
if self.supports_extension("size"):
size_option = "size={}".format(len(message))
mail_options.append(size_option)
try:
await self.mail(sender, options=mail_options, timeout=timeout)
recipient_errors = await self._send_recipients(
recipients, options=rcpt_options, timeout=timeout
)
response = await self.data(message, timeout=timeout)
except (SMTPResponseException, SMTPRecipientsRefused) as exc:
# If we got an error, reset the envelope.
try:
await self.rset(timeout=timeout)
except (ConnectionError, SMTPResponseException):
# If we're disconnected on the reset, or we get a bad
# status, don't raise that as it's confusing
pass
raise exc
return recipient_errors, response.message | python | async def sendmail(
self,
sender: str,
recipients: RecipientsType,
message: Union[str, bytes],
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
"""
This command performs an entire mail transaction.
The arguments are:
- sender: The address sending this mail.
- recipients: A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
- message: The message string to send.
- mail_options: List of options (such as ESMTP 8bitmime) for the
MAIL command.
- rcpt_options: List of options (such as DSN commands) for all the
RCPT commands.
message must be a string containing characters in the ASCII range.
The string is encoded to bytes using the ascii codec, and lone \\\\r
and \\\\n characters are converted to \\\\r\\\\n characters.
If there has been no previous HELO or EHLO command this session, this
method tries EHLO first.
This method will return normally if the mail is accepted for at least
one recipient. It returns a tuple consisting of:
- an error dictionary, with one entry for each recipient that was
refused. Each entry contains a tuple of the SMTP error code
and the accompanying error message sent by the server.
- the message sent by the server in response to the DATA command
(often containing a message id)
Example:
>>> loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> loop.run_until_complete(smtp.connect())
(220, ...)
>>> recipients = ["one@one.org", "two@two.org", "3@three.org"]
>>> message = "From: Me@my.org\\nSubject: testing\\nHello World"
>>> send_coro = smtp.sendmail("me@my.org", recipients, message)
>>> loop.run_until_complete(send_coro)
({}, 'OK')
>>> loop.run_until_complete(smtp.quit())
(221, Bye)
In the above example, the message was accepted for delivery for all
three addresses. If delivery had been only successful to two
of the three addresses, and one was rejected, the response would look
something like::
(
{"nobody@three.org": (550, "User unknown")},
"Written safely to disk. #902487694.289148.12219.",
)
If delivery is not successful to any addresses,
:exc:`.SMTPRecipientsRefused` is raised.
If :exc:`.SMTPResponseException` is raised by this method, we try to
send an RSET command to reset the server envelope automatically for
the next attempt.
:raises SMTPRecipientsRefused: delivery to all recipients failed
:raises SMTPResponseException: on invalid response
"""
if isinstance(recipients, str):
recipients = [recipients]
else:
recipients = list(recipients)
if mail_options is None:
mail_options = []
else:
mail_options = list(mail_options)
if rcpt_options is None:
rcpt_options = []
else:
rcpt_options = list(rcpt_options)
async with self._sendmail_lock:
if self.supports_extension("size"):
size_option = "size={}".format(len(message))
mail_options.append(size_option)
try:
await self.mail(sender, options=mail_options, timeout=timeout)
recipient_errors = await self._send_recipients(
recipients, options=rcpt_options, timeout=timeout
)
response = await self.data(message, timeout=timeout)
except (SMTPResponseException, SMTPRecipientsRefused) as exc:
# If we got an error, reset the envelope.
try:
await self.rset(timeout=timeout)
except (ConnectionError, SMTPResponseException):
# If we're disconnected on the reset, or we get a bad
# status, don't raise that as it's confusing
pass
raise exc
return recipient_errors, response.message | [
"async",
"def",
"sendmail",
"(",
"self",
",",
"sender",
":",
"str",
",",
"recipients",
":",
"RecipientsType",
",",
"message",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"mail_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"rcpt_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SendmailResponseType",
":",
"if",
"isinstance",
"(",
"recipients",
",",
"str",
")",
":",
"recipients",
"=",
"[",
"recipients",
"]",
"else",
":",
"recipients",
"=",
"list",
"(",
"recipients",
")",
"if",
"mail_options",
"is",
"None",
":",
"mail_options",
"=",
"[",
"]",
"else",
":",
"mail_options",
"=",
"list",
"(",
"mail_options",
")",
"if",
"rcpt_options",
"is",
"None",
":",
"rcpt_options",
"=",
"[",
"]",
"else",
":",
"rcpt_options",
"=",
"list",
"(",
"rcpt_options",
")",
"async",
"with",
"self",
".",
"_sendmail_lock",
":",
"if",
"self",
".",
"supports_extension",
"(",
"\"size\"",
")",
":",
"size_option",
"=",
"\"size={}\"",
".",
"format",
"(",
"len",
"(",
"message",
")",
")",
"mail_options",
".",
"append",
"(",
"size_option",
")",
"try",
":",
"await",
"self",
".",
"mail",
"(",
"sender",
",",
"options",
"=",
"mail_options",
",",
"timeout",
"=",
"timeout",
")",
"recipient_errors",
"=",
"await",
"self",
".",
"_send_recipients",
"(",
"recipients",
",",
"options",
"=",
"rcpt_options",
",",
"timeout",
"=",
"timeout",
")",
"response",
"=",
"await",
"self",
".",
"data",
"(",
"message",
",",
"timeout",
"=",
"timeout",
")",
"except",
"(",
"SMTPResponseException",
",",
"SMTPRecipientsRefused",
")",
"as",
"exc",
":",
"# If we got an error, reset the envelope.",
"try",
":",
"await",
"self",
".",
"rset",
"(",
"timeout",
"=",
"timeout",
")",
"except",
"(",
"ConnectionError",
",",
"SMTPResponseException",
")",
":",
"# If we're disconnected on the reset, or we get a bad",
"# status, don't raise that as it's confusing",
"pass",
"raise",
"exc",
"return",
"recipient_errors",
",",
"response",
".",
"message"
] | This command performs an entire mail transaction.
The arguments are:
- sender: The address sending this mail.
- recipients: A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
- message: The message string to send.
- mail_options: List of options (such as ESMTP 8bitmime) for the
MAIL command.
- rcpt_options: List of options (such as DSN commands) for all the
RCPT commands.
message must be a string containing characters in the ASCII range.
The string is encoded to bytes using the ascii codec, and lone \\\\r
and \\\\n characters are converted to \\\\r\\\\n characters.
If there has been no previous HELO or EHLO command this session, this
method tries EHLO first.
This method will return normally if the mail is accepted for at least
one recipient. It returns a tuple consisting of:
- an error dictionary, with one entry for each recipient that was
refused. Each entry contains a tuple of the SMTP error code
and the accompanying error message sent by the server.
- the message sent by the server in response to the DATA command
(often containing a message id)
Example:
>>> loop = asyncio.get_event_loop()
>>> smtp = aiosmtplib.SMTP(hostname="127.0.0.1", port=1025)
>>> loop.run_until_complete(smtp.connect())
(220, ...)
>>> recipients = ["one@one.org", "two@two.org", "3@three.org"]
>>> message = "From: Me@my.org\\nSubject: testing\\nHello World"
>>> send_coro = smtp.sendmail("me@my.org", recipients, message)
>>> loop.run_until_complete(send_coro)
({}, 'OK')
>>> loop.run_until_complete(smtp.quit())
(221, Bye)
In the above example, the message was accepted for delivery for all
three addresses. If delivery had been only successful to two
of the three addresses, and one was rejected, the response would look
something like::
(
{"nobody@three.org": (550, "User unknown")},
"Written safely to disk. #902487694.289148.12219.",
)
If delivery is not successful to any addresses,
:exc:`.SMTPRecipientsRefused` is raised.
If :exc:`.SMTPResponseException` is raised by this method, we try to
send an RSET command to reset the server envelope automatically for
the next attempt.
:raises SMTPRecipientsRefused: delivery to all recipients failed
:raises SMTPResponseException: on invalid response | [
"This",
"command",
"performs",
"an",
"entire",
"mail",
"transaction",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L57-L166 | train | 235,172 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP._run_sync | def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_complete(self.connect())
task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
result = self.loop.run_until_complete(task)
self.loop.run_until_complete(self.quit())
return result | python | def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_complete(self.connect())
task = asyncio.Task(method(*args, **kwargs), loop=self.loop)
result = self.loop.run_until_complete(task)
self.loop.run_until_complete(self.quit())
return result | [
"def",
"_run_sync",
"(",
"self",
",",
"method",
":",
"Callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"if",
"self",
".",
"loop",
".",
"is_running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Event loop is already running.\"",
")",
"if",
"not",
"self",
".",
"is_connected",
":",
"self",
".",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"connect",
"(",
")",
")",
"task",
"=",
"asyncio",
".",
"Task",
"(",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"loop",
"=",
"self",
".",
"loop",
")",
"result",
"=",
"self",
".",
"loop",
".",
"run_until_complete",
"(",
"task",
")",
"self",
".",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"quit",
"(",
")",
")",
"return",
"result"
] | Utility method to run commands synchronously for testing. | [
"Utility",
"method",
"to",
"run",
"commands",
"synchronously",
"for",
"testing",
"."
] | 0cd00e5059005371cbdfca995feff9183a16a51f | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L237-L252 | train | 235,173 |
cs50/submit50 | submit50/__main__.py | check_announcements | def check_announcements():
"""Check for any announcements from cs50.me, raise Error if so."""
res = requests.get("https://cs50.me/status/submit50") # TODO change this to submit50.io!
if res.status_code == 200 and res.text.strip():
raise Error(res.text.strip()) | python | def check_announcements():
"""Check for any announcements from cs50.me, raise Error if so."""
res = requests.get("https://cs50.me/status/submit50") # TODO change this to submit50.io!
if res.status_code == 200 and res.text.strip():
raise Error(res.text.strip()) | [
"def",
"check_announcements",
"(",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"\"https://cs50.me/status/submit50\"",
")",
"# TODO change this to submit50.io!",
"if",
"res",
".",
"status_code",
"==",
"200",
"and",
"res",
".",
"text",
".",
"strip",
"(",
")",
":",
"raise",
"Error",
"(",
"res",
".",
"text",
".",
"strip",
"(",
")",
")"
] | Check for any announcements from cs50.me, raise Error if so. | [
"Check",
"for",
"any",
"announcements",
"from",
"cs50",
".",
"me",
"raise",
"Error",
"if",
"so",
"."
] | 5f4c8b3675e8e261c8422f76eacd6a6330c23831 | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L28-L32 | train | 235,174 |
cs50/submit50 | submit50/__main__.py | check_version | def check_version():
"""Check that submit50 is the latest version according to submit50.io."""
# Retrieve version info
res = requests.get("https://cs50.me/versions/submit50") # TODO change this to submit50.io!
if res.status_code != 200:
raise Error(_("You have an unknown version of submit50. "
"Email sysadmins@cs50.harvard.edu!"))
# Check that latest version == version installed
required_required = pkg_resources.parse_version(res.text.strip()) | python | def check_version():
"""Check that submit50 is the latest version according to submit50.io."""
# Retrieve version info
res = requests.get("https://cs50.me/versions/submit50") # TODO change this to submit50.io!
if res.status_code != 200:
raise Error(_("You have an unknown version of submit50. "
"Email sysadmins@cs50.harvard.edu!"))
# Check that latest version == version installed
required_required = pkg_resources.parse_version(res.text.strip()) | [
"def",
"check_version",
"(",
")",
":",
"# Retrieve version info",
"res",
"=",
"requests",
".",
"get",
"(",
"\"https://cs50.me/versions/submit50\"",
")",
"# TODO change this to submit50.io!",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"raise",
"Error",
"(",
"_",
"(",
"\"You have an unknown version of submit50. \"",
"\"Email sysadmins@cs50.harvard.edu!\"",
")",
")",
"# Check that latest version == version installed",
"required_required",
"=",
"pkg_resources",
".",
"parse_version",
"(",
"res",
".",
"text",
".",
"strip",
"(",
")",
")"
] | Check that submit50 is the latest version according to submit50.io. | [
"Check",
"that",
"submit50",
"is",
"the",
"latest",
"version",
"according",
"to",
"submit50",
".",
"io",
"."
] | 5f4c8b3675e8e261c8422f76eacd6a6330c23831 | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L35-L44 | train | 235,175 |
cs50/submit50 | submit50/__main__.py | excepthook | def excepthook(type, value, tb):
"""Report an exception."""
if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value):
for line in str(value).split("\n"):
cprint(str(line), "yellow")
else:
cprint(_("Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!"), "yellow")
if excepthook.verbose:
traceback.print_exception(type, value, tb)
cprint(_("Submission cancelled."), "red") | python | def excepthook(type, value, tb):
"""Report an exception."""
if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value):
for line in str(value).split("\n"):
cprint(str(line), "yellow")
else:
cprint(_("Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!"), "yellow")
if excepthook.verbose:
traceback.print_exception(type, value, tb)
cprint(_("Submission cancelled."), "red") | [
"def",
"excepthook",
"(",
"type",
",",
"value",
",",
"tb",
")",
":",
"if",
"(",
"issubclass",
"(",
"type",
",",
"Error",
")",
"or",
"issubclass",
"(",
"type",
",",
"lib50",
".",
"Error",
")",
")",
"and",
"str",
"(",
"value",
")",
":",
"for",
"line",
"in",
"str",
"(",
"value",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"cprint",
"(",
"str",
"(",
"line",
")",
",",
"\"yellow\"",
")",
"else",
":",
"cprint",
"(",
"_",
"(",
"\"Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!\"",
")",
",",
"\"yellow\"",
")",
"if",
"excepthook",
".",
"verbose",
":",
"traceback",
".",
"print_exception",
"(",
"type",
",",
"value",
",",
"tb",
")",
"cprint",
"(",
"_",
"(",
"\"Submission cancelled.\"",
")",
",",
"\"red\"",
")"
] | Report an exception. | [
"Report",
"an",
"exception",
"."
] | 5f4c8b3675e8e261c8422f76eacd6a6330c23831 | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L93-L104 | train | 235,176 |
kedder/ofxstatement | src/ofxstatement/statement.py | generate_transaction_id | def generate_transaction_id(stmt_line):
"""Generate pseudo-unique id for given statement line.
This function can be used in statement parsers when real transaction id is
not available in source statement.
"""
return str(abs(hash((stmt_line.date,
stmt_line.memo,
stmt_line.amount)))) | python | def generate_transaction_id(stmt_line):
"""Generate pseudo-unique id for given statement line.
This function can be used in statement parsers when real transaction id is
not available in source statement.
"""
return str(abs(hash((stmt_line.date,
stmt_line.memo,
stmt_line.amount)))) | [
"def",
"generate_transaction_id",
"(",
"stmt_line",
")",
":",
"return",
"str",
"(",
"abs",
"(",
"hash",
"(",
"(",
"stmt_line",
".",
"date",
",",
"stmt_line",
".",
"memo",
",",
"stmt_line",
".",
"amount",
")",
")",
")",
")"
] | Generate pseudo-unique id for given statement line.
This function can be used in statement parsers when real transaction id is
not available in source statement. | [
"Generate",
"pseudo",
"-",
"unique",
"id",
"for",
"given",
"statement",
"line",
"."
] | 61f9dc1cfe6024874b859c8aec108b9d9acee57a | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L155-L163 | train | 235,177 |
kedder/ofxstatement | src/ofxstatement/statement.py | recalculate_balance | def recalculate_balance(stmt):
"""Recalculate statement starting and ending dates and balances.
When starting balance is not available, it will be assumed to be 0.
This function can be used in statement parsers when balance information is
not available in source statement.
"""
total_amount = sum(sl.amount for sl in stmt.lines)
stmt.start_balance = stmt.start_balance or D(0)
stmt.end_balance = stmt.start_balance + total_amount
stmt.start_date = min(sl.date for sl in stmt.lines)
stmt.end_date = max(sl.date for sl in stmt.lines) | python | def recalculate_balance(stmt):
"""Recalculate statement starting and ending dates and balances.
When starting balance is not available, it will be assumed to be 0.
This function can be used in statement parsers when balance information is
not available in source statement.
"""
total_amount = sum(sl.amount for sl in stmt.lines)
stmt.start_balance = stmt.start_balance or D(0)
stmt.end_balance = stmt.start_balance + total_amount
stmt.start_date = min(sl.date for sl in stmt.lines)
stmt.end_date = max(sl.date for sl in stmt.lines) | [
"def",
"recalculate_balance",
"(",
"stmt",
")",
":",
"total_amount",
"=",
"sum",
"(",
"sl",
".",
"amount",
"for",
"sl",
"in",
"stmt",
".",
"lines",
")",
"stmt",
".",
"start_balance",
"=",
"stmt",
".",
"start_balance",
"or",
"D",
"(",
"0",
")",
"stmt",
".",
"end_balance",
"=",
"stmt",
".",
"start_balance",
"+",
"total_amount",
"stmt",
".",
"start_date",
"=",
"min",
"(",
"sl",
".",
"date",
"for",
"sl",
"in",
"stmt",
".",
"lines",
")",
"stmt",
".",
"end_date",
"=",
"max",
"(",
"sl",
".",
"date",
"for",
"sl",
"in",
"stmt",
".",
"lines",
")"
] | Recalculate statement starting and ending dates and balances.
When starting balance is not available, it will be assumed to be 0.
This function can be used in statement parsers when balance information is
not available in source statement. | [
"Recalculate",
"statement",
"starting",
"and",
"ending",
"dates",
"and",
"balances",
"."
] | 61f9dc1cfe6024874b859c8aec108b9d9acee57a | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L166-L180 | train | 235,178 |
kedder/ofxstatement | src/ofxstatement/statement.py | StatementLine.assert_valid | def assert_valid(self):
"""Ensure that fields have valid values
"""
assert self.trntype in TRANSACTION_TYPES, \
"trntype must be one of %s" % TRANSACTION_TYPES
if self.bank_account_to:
self.bank_account_to.assert_valid() | python | def assert_valid(self):
"""Ensure that fields have valid values
"""
assert self.trntype in TRANSACTION_TYPES, \
"trntype must be one of %s" % TRANSACTION_TYPES
if self.bank_account_to:
self.bank_account_to.assert_valid() | [
"def",
"assert_valid",
"(",
"self",
")",
":",
"assert",
"self",
".",
"trntype",
"in",
"TRANSACTION_TYPES",
",",
"\"trntype must be one of %s\"",
"%",
"TRANSACTION_TYPES",
"if",
"self",
".",
"bank_account_to",
":",
"self",
".",
"bank_account_to",
".",
"assert_valid",
"(",
")"
] | Ensure that fields have valid values | [
"Ensure",
"that",
"fields",
"have",
"valid",
"values"
] | 61f9dc1cfe6024874b859c8aec108b9d9acee57a | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L113-L120 | train | 235,179 |
kedder/ofxstatement | src/ofxstatement/parser.py | StatementParser.parse | def parse(self):
"""Read and parse statement
Return Statement object
May raise exceptions.ParseException on malformed input.
"""
reader = self.split_records()
for line in reader:
self.cur_record += 1
if not line:
continue
stmt_line = self.parse_record(line)
if stmt_line:
stmt_line.assert_valid()
self.statement.lines.append(stmt_line)
return self.statement | python | def parse(self):
"""Read and parse statement
Return Statement object
May raise exceptions.ParseException on malformed input.
"""
reader = self.split_records()
for line in reader:
self.cur_record += 1
if not line:
continue
stmt_line = self.parse_record(line)
if stmt_line:
stmt_line.assert_valid()
self.statement.lines.append(stmt_line)
return self.statement | [
"def",
"parse",
"(",
"self",
")",
":",
"reader",
"=",
"self",
".",
"split_records",
"(",
")",
"for",
"line",
"in",
"reader",
":",
"self",
".",
"cur_record",
"+=",
"1",
"if",
"not",
"line",
":",
"continue",
"stmt_line",
"=",
"self",
".",
"parse_record",
"(",
"line",
")",
"if",
"stmt_line",
":",
"stmt_line",
".",
"assert_valid",
"(",
")",
"self",
".",
"statement",
".",
"lines",
".",
"append",
"(",
"stmt_line",
")",
"return",
"self",
".",
"statement"
] | Read and parse statement
Return Statement object
May raise exceptions.ParseException on malformed input. | [
"Read",
"and",
"parse",
"statement"
] | 61f9dc1cfe6024874b859c8aec108b9d9acee57a | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/parser.py#L17-L33 | train | 235,180 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.acquire_auth_token_ticket | def acquire_auth_token_ticket(self, headers=None):
'''
Acquire an auth token from the CAS server.
'''
logging.debug('[CAS] Acquiring Auth token ticket')
url = self._get_auth_token_tickets_url()
text = self._perform_post(url, headers=headers)
auth_token_ticket = json.loads(text)['ticket']
logging.debug('[CAS] Acquire Auth token ticket: {}'.format(
auth_token_ticket))
return auth_token_ticket | python | def acquire_auth_token_ticket(self, headers=None):
'''
Acquire an auth token from the CAS server.
'''
logging.debug('[CAS] Acquiring Auth token ticket')
url = self._get_auth_token_tickets_url()
text = self._perform_post(url, headers=headers)
auth_token_ticket = json.loads(text)['ticket']
logging.debug('[CAS] Acquire Auth token ticket: {}'.format(
auth_token_ticket))
return auth_token_ticket | [
"def",
"acquire_auth_token_ticket",
"(",
"self",
",",
"headers",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"'[CAS] Acquiring Auth token ticket'",
")",
"url",
"=",
"self",
".",
"_get_auth_token_tickets_url",
"(",
")",
"text",
"=",
"self",
".",
"_perform_post",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"auth_token_ticket",
"=",
"json",
".",
"loads",
"(",
"text",
")",
"[",
"'ticket'",
"]",
"logging",
".",
"debug",
"(",
"'[CAS] Acquire Auth token ticket: {}'",
".",
"format",
"(",
"auth_token_ticket",
")",
")",
"return",
"auth_token_ticket"
] | Acquire an auth token from the CAS server. | [
"Acquire",
"an",
"auth",
"token",
"from",
"the",
"CAS",
"server",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L53-L63 | train | 235,181 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.create_session | def create_session(self, ticket, payload=None, expires=None):
'''
Create a session record from a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Creating session for ticket {}'.format(ticket))
self.session_storage_adapter.create(
ticket,
payload=payload,
expires=expires,
) | python | def create_session(self, ticket, payload=None, expires=None):
'''
Create a session record from a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Creating session for ticket {}'.format(ticket))
self.session_storage_adapter.create(
ticket,
payload=payload,
expires=expires,
) | [
"def",
"create_session",
"(",
"self",
",",
"ticket",
",",
"payload",
"=",
"None",
",",
"expires",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"session_storage_adapter",
",",
"CASSessionAdapter",
")",
"logging",
".",
"debug",
"(",
"'[CAS] Creating session for ticket {}'",
".",
"format",
"(",
"ticket",
")",
")",
"self",
".",
"session_storage_adapter",
".",
"create",
"(",
"ticket",
",",
"payload",
"=",
"payload",
",",
"expires",
"=",
"expires",
",",
")"
] | Create a session record from a service ticket. | [
"Create",
"a",
"session",
"record",
"from",
"a",
"service",
"ticket",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L65-L75 | train | 235,182 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.delete_session | def delete_session(self, ticket):
'''
Delete a session record associated with a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Deleting session for ticket {}'.format(ticket))
self.session_storage_adapter.delete(ticket) | python | def delete_session(self, ticket):
'''
Delete a session record associated with a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Deleting session for ticket {}'.format(ticket))
self.session_storage_adapter.delete(ticket) | [
"def",
"delete_session",
"(",
"self",
",",
"ticket",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"session_storage_adapter",
",",
"CASSessionAdapter",
")",
"logging",
".",
"debug",
"(",
"'[CAS] Deleting session for ticket {}'",
".",
"format",
"(",
"ticket",
")",
")",
"self",
".",
"session_storage_adapter",
".",
"delete",
"(",
"ticket",
")"
] | Delete a session record associated with a service ticket. | [
"Delete",
"a",
"session",
"record",
"associated",
"with",
"a",
"service",
"ticket",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L77-L83 | train | 235,183 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.get_api_url | def get_api_url(
self,
api_resource,
auth_token_ticket,
authenticator,
private_key,
service_url=None,
**kwargs
):
'''
Build an auth-token-protected CAS API url.
'''
auth_token, auth_token_signature = self._build_auth_token_data(
auth_token_ticket,
authenticator,
private_key,
**kwargs
)
params = {
'at': auth_token,
'ats': auth_token_signature,
}
if service_url is not None:
params['service'] = service_url
url = '{}?{}'.format(
self._get_api_url(api_resource),
urlencode(params),
)
return url | python | def get_api_url(
self,
api_resource,
auth_token_ticket,
authenticator,
private_key,
service_url=None,
**kwargs
):
'''
Build an auth-token-protected CAS API url.
'''
auth_token, auth_token_signature = self._build_auth_token_data(
auth_token_ticket,
authenticator,
private_key,
**kwargs
)
params = {
'at': auth_token,
'ats': auth_token_signature,
}
if service_url is not None:
params['service'] = service_url
url = '{}?{}'.format(
self._get_api_url(api_resource),
urlencode(params),
)
return url | [
"def",
"get_api_url",
"(",
"self",
",",
"api_resource",
",",
"auth_token_ticket",
",",
"authenticator",
",",
"private_key",
",",
"service_url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_token",
",",
"auth_token_signature",
"=",
"self",
".",
"_build_auth_token_data",
"(",
"auth_token_ticket",
",",
"authenticator",
",",
"private_key",
",",
"*",
"*",
"kwargs",
")",
"params",
"=",
"{",
"'at'",
":",
"auth_token",
",",
"'ats'",
":",
"auth_token_signature",
",",
"}",
"if",
"service_url",
"is",
"not",
"None",
":",
"params",
"[",
"'service'",
"]",
"=",
"service_url",
"url",
"=",
"'{}?{}'",
".",
"format",
"(",
"self",
".",
"_get_api_url",
"(",
"api_resource",
")",
",",
"urlencode",
"(",
"params",
")",
",",
")",
"return",
"url"
] | Build an auth-token-protected CAS API url. | [
"Build",
"an",
"auth",
"-",
"token",
"-",
"protected",
"CAS",
"API",
"url",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L85-L113 | train | 235,184 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.get_auth_token_login_url | def get_auth_token_login_url(
self,
auth_token_ticket,
authenticator,
private_key,
service_url,
username,
):
'''
Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details.
'''
auth_token, auth_token_signature = self._build_auth_token_data(
auth_token_ticket,
authenticator,
private_key,
username=username,
)
logging.debug('[CAS] AuthToken: {}'.format(auth_token))
url = self._get_auth_token_login_url(
auth_token=auth_token,
auth_token_signature=auth_token_signature,
service_url=service_url,
)
logging.debug('[CAS] AuthToken Login URL: {}'.format(url))
return url | python | def get_auth_token_login_url(
self,
auth_token_ticket,
authenticator,
private_key,
service_url,
username,
):
'''
Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details.
'''
auth_token, auth_token_signature = self._build_auth_token_data(
auth_token_ticket,
authenticator,
private_key,
username=username,
)
logging.debug('[CAS] AuthToken: {}'.format(auth_token))
url = self._get_auth_token_login_url(
auth_token=auth_token,
auth_token_signature=auth_token_signature,
service_url=service_url,
)
logging.debug('[CAS] AuthToken Login URL: {}'.format(url))
return url | [
"def",
"get_auth_token_login_url",
"(",
"self",
",",
"auth_token_ticket",
",",
"authenticator",
",",
"private_key",
",",
"service_url",
",",
"username",
",",
")",
":",
"auth_token",
",",
"auth_token_signature",
"=",
"self",
".",
"_build_auth_token_data",
"(",
"auth_token_ticket",
",",
"authenticator",
",",
"private_key",
",",
"username",
"=",
"username",
",",
")",
"logging",
".",
"debug",
"(",
"'[CAS] AuthToken: {}'",
".",
"format",
"(",
"auth_token",
")",
")",
"url",
"=",
"self",
".",
"_get_auth_token_login_url",
"(",
"auth_token",
"=",
"auth_token",
",",
"auth_token_signature",
"=",
"auth_token_signature",
",",
"service_url",
"=",
"service_url",
",",
")",
"logging",
".",
"debug",
"(",
"'[CAS] AuthToken Login URL: {}'",
".",
"format",
"(",
"url",
")",
")",
"return",
"url"
] | Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details. | [
"Build",
"an",
"auth",
"token",
"login",
"URL",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L115-L141 | train | 235,185 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.parse_logout_request | def parse_logout_request(self, message_text):
'''
Parse the contents of a CAS `LogoutRequest` XML message.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> message_text = """
... <samlp:LogoutRequest
... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553"
... Version="2.0"
... IssueInstant="2016-04-08 00:40:55 +0000">
... <saml:NameID>@NOT_USED@</saml:NameID>
... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex>
... </samlp:LogoutRequest>
... """
>>> parsed_message = client.parse_logout_request(message_text)
>>> import pprint
>>> pprint.pprint(parsed_message)
{'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553',
'IssueInstant': '2016-04-08 00:40:55 +0000',
'Version': '2.0',
'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH',
'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion',
'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'}
'''
result = {}
xml_document = parseString(message_text)
for node in xml_document.getElementsByTagName('saml:NameId'):
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
result['name_id'] = child.nodeValue.strip()
for node in xml_document.getElementsByTagName('samlp:SessionIndex'):
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
result['session_index'] = str(child.nodeValue.strip())
for key in xml_document.documentElement.attributes.keys():
result[str(key)] = str(xml_document.documentElement.getAttribute(key))
logging.debug('[CAS] LogoutRequest:\n{}'.format(
json.dumps(result, sort_keys=True, indent=4, separators=[',', ': ']),
))
return result | python | def parse_logout_request(self, message_text):
'''
Parse the contents of a CAS `LogoutRequest` XML message.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> message_text = """
... <samlp:LogoutRequest
... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553"
... Version="2.0"
... IssueInstant="2016-04-08 00:40:55 +0000">
... <saml:NameID>@NOT_USED@</saml:NameID>
... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex>
... </samlp:LogoutRequest>
... """
>>> parsed_message = client.parse_logout_request(message_text)
>>> import pprint
>>> pprint.pprint(parsed_message)
{'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553',
'IssueInstant': '2016-04-08 00:40:55 +0000',
'Version': '2.0',
'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH',
'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion',
'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'}
'''
result = {}
xml_document = parseString(message_text)
for node in xml_document.getElementsByTagName('saml:NameId'):
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
result['name_id'] = child.nodeValue.strip()
for node in xml_document.getElementsByTagName('samlp:SessionIndex'):
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
result['session_index'] = str(child.nodeValue.strip())
for key in xml_document.documentElement.attributes.keys():
result[str(key)] = str(xml_document.documentElement.getAttribute(key))
logging.debug('[CAS] LogoutRequest:\n{}'.format(
json.dumps(result, sort_keys=True, indent=4, separators=[',', ': ']),
))
return result | [
"def",
"parse_logout_request",
"(",
"self",
",",
"message_text",
")",
":",
"result",
"=",
"{",
"}",
"xml_document",
"=",
"parseString",
"(",
"message_text",
")",
"for",
"node",
"in",
"xml_document",
".",
"getElementsByTagName",
"(",
"'saml:NameId'",
")",
":",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"child",
".",
"TEXT_NODE",
":",
"result",
"[",
"'name_id'",
"]",
"=",
"child",
".",
"nodeValue",
".",
"strip",
"(",
")",
"for",
"node",
"in",
"xml_document",
".",
"getElementsByTagName",
"(",
"'samlp:SessionIndex'",
")",
":",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"child",
".",
"TEXT_NODE",
":",
"result",
"[",
"'session_index'",
"]",
"=",
"str",
"(",
"child",
".",
"nodeValue",
".",
"strip",
"(",
")",
")",
"for",
"key",
"in",
"xml_document",
".",
"documentElement",
".",
"attributes",
".",
"keys",
"(",
")",
":",
"result",
"[",
"str",
"(",
"key",
")",
"]",
"=",
"str",
"(",
"xml_document",
".",
"documentElement",
".",
"getAttribute",
"(",
"key",
")",
")",
"logging",
".",
"debug",
"(",
"'[CAS] LogoutRequest:\\n{}'",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"result",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"[",
"','",
",",
"': '",
"]",
")",
",",
")",
")",
"return",
"result"
] | Parse the contents of a CAS `LogoutRequest` XML message.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> message_text = """
... <samlp:LogoutRequest
... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553"
... Version="2.0"
... IssueInstant="2016-04-08 00:40:55 +0000">
... <saml:NameID>@NOT_USED@</saml:NameID>
... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex>
... </samlp:LogoutRequest>
... """
>>> parsed_message = client.parse_logout_request(message_text)
>>> import pprint
>>> pprint.pprint(parsed_message)
{'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553',
'IssueInstant': '2016-04-08 00:40:55 +0000',
'Version': '2.0',
'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH',
'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion',
'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'} | [
"Parse",
"the",
"contents",
"of",
"a",
"CAS",
"LogoutRequest",
"XML",
"message",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L209-L254 | train | 235,186 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.perform_api_request | def perform_api_request(
self,
url,
method='POST',
headers=None,
body=None,
**kwargs
):
'''
Perform an auth-token-protected request against a CAS API endpoint.
'''
assert method in ('GET', 'POST')
if method == 'GET':
response = self._perform_get(url, headers=headers, **kwargs)
elif method == 'POST':
response = self._perform_post(url, headers=headers, data=body, **kwargs)
return response | python | def perform_api_request(
self,
url,
method='POST',
headers=None,
body=None,
**kwargs
):
'''
Perform an auth-token-protected request against a CAS API endpoint.
'''
assert method in ('GET', 'POST')
if method == 'GET':
response = self._perform_get(url, headers=headers, **kwargs)
elif method == 'POST':
response = self._perform_post(url, headers=headers, data=body, **kwargs)
return response | [
"def",
"perform_api_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'POST'",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"method",
"in",
"(",
"'GET'",
",",
"'POST'",
")",
"if",
"method",
"==",
"'GET'",
":",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"kwargs",
")",
"elif",
"method",
"==",
"'POST'",
":",
"response",
"=",
"self",
".",
"_perform_post",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"body",
",",
"*",
"*",
"kwargs",
")",
"return",
"response"
] | Perform an auth-token-protected request against a CAS API endpoint. | [
"Perform",
"an",
"auth",
"-",
"token",
"-",
"protected",
"request",
"against",
"a",
"CAS",
"API",
"endpoint",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L256-L272 | train | 235,187 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.perform_proxy | def perform_proxy(self, proxy_ticket, headers=None):
'''
Fetch a response from the remote CAS `proxy` endpoint.
'''
url = self._get_proxy_url(ticket=proxy_ticket)
logging.debug('[CAS] Proxy URL: {}'.format(url))
return self._perform_cas_call(
url,
ticket=proxy_ticket,
headers=headers,
) | python | def perform_proxy(self, proxy_ticket, headers=None):
'''
Fetch a response from the remote CAS `proxy` endpoint.
'''
url = self._get_proxy_url(ticket=proxy_ticket)
logging.debug('[CAS] Proxy URL: {}'.format(url))
return self._perform_cas_call(
url,
ticket=proxy_ticket,
headers=headers,
) | [
"def",
"perform_proxy",
"(",
"self",
",",
"proxy_ticket",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_get_proxy_url",
"(",
"ticket",
"=",
"proxy_ticket",
")",
"logging",
".",
"debug",
"(",
"'[CAS] Proxy URL: {}'",
".",
"format",
"(",
"url",
")",
")",
"return",
"self",
".",
"_perform_cas_call",
"(",
"url",
",",
"ticket",
"=",
"proxy_ticket",
",",
"headers",
"=",
"headers",
",",
")"
] | Fetch a response from the remote CAS `proxy` endpoint. | [
"Fetch",
"a",
"response",
"from",
"the",
"remote",
"CAS",
"proxy",
"endpoint",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L274-L284 | train | 235,188 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.perform_proxy_validate | def perform_proxy_validate(self, proxied_service_ticket, headers=None):
'''
Fetch a response from the remote CAS `proxyValidate` endpoint.
'''
url = self._get_proxy_validate_url(ticket=proxied_service_ticket)
logging.debug('[CAS] ProxyValidate URL: {}'.format(url))
return self._perform_cas_call(
url,
ticket=proxied_service_ticket,
headers=headers,
) | python | def perform_proxy_validate(self, proxied_service_ticket, headers=None):
'''
Fetch a response from the remote CAS `proxyValidate` endpoint.
'''
url = self._get_proxy_validate_url(ticket=proxied_service_ticket)
logging.debug('[CAS] ProxyValidate URL: {}'.format(url))
return self._perform_cas_call(
url,
ticket=proxied_service_ticket,
headers=headers,
) | [
"def",
"perform_proxy_validate",
"(",
"self",
",",
"proxied_service_ticket",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_get_proxy_validate_url",
"(",
"ticket",
"=",
"proxied_service_ticket",
")",
"logging",
".",
"debug",
"(",
"'[CAS] ProxyValidate URL: {}'",
".",
"format",
"(",
"url",
")",
")",
"return",
"self",
".",
"_perform_cas_call",
"(",
"url",
",",
"ticket",
"=",
"proxied_service_ticket",
",",
"headers",
"=",
"headers",
",",
")"
] | Fetch a response from the remote CAS `proxyValidate` endpoint. | [
"Fetch",
"a",
"response",
"from",
"the",
"remote",
"CAS",
"proxyValidate",
"endpoint",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L286-L296 | train | 235,189 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.perform_service_validate | def perform_service_validate(
self,
ticket=None,
service_url=None,
headers=None,
):
'''
Fetch a response from the remote CAS `serviceValidate` endpoint.
'''
url = self._get_service_validate_url(ticket, service_url=service_url)
logging.debug('[CAS] ServiceValidate URL: {}'.format(url))
return self._perform_cas_call(url, ticket=ticket, headers=headers) | python | def perform_service_validate(
self,
ticket=None,
service_url=None,
headers=None,
):
'''
Fetch a response from the remote CAS `serviceValidate` endpoint.
'''
url = self._get_service_validate_url(ticket, service_url=service_url)
logging.debug('[CAS] ServiceValidate URL: {}'.format(url))
return self._perform_cas_call(url, ticket=ticket, headers=headers) | [
"def",
"perform_service_validate",
"(",
"self",
",",
"ticket",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
"headers",
"=",
"None",
",",
")",
":",
"url",
"=",
"self",
".",
"_get_service_validate_url",
"(",
"ticket",
",",
"service_url",
"=",
"service_url",
")",
"logging",
".",
"debug",
"(",
"'[CAS] ServiceValidate URL: {}'",
".",
"format",
"(",
"url",
")",
")",
"return",
"self",
".",
"_perform_cas_call",
"(",
"url",
",",
"ticket",
"=",
"ticket",
",",
"headers",
"=",
"headers",
")"
] | Fetch a response from the remote CAS `serviceValidate` endpoint. | [
"Fetch",
"a",
"response",
"from",
"the",
"remote",
"CAS",
"serviceValidate",
"endpoint",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L298-L309 | train | 235,190 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.session_exists | def session_exists(self, ticket):
'''
Test if a session records exists for a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
exists = self.session_storage_adapter.exists(ticket)
logging.debug('[CAS] Session [{}] exists: {}'.format(ticket, exists))
return exists | python | def session_exists(self, ticket):
'''
Test if a session records exists for a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
exists = self.session_storage_adapter.exists(ticket)
logging.debug('[CAS] Session [{}] exists: {}'.format(ticket, exists))
return exists | [
"def",
"session_exists",
"(",
"self",
",",
"ticket",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"session_storage_adapter",
",",
"CASSessionAdapter",
")",
"exists",
"=",
"self",
".",
"session_storage_adapter",
".",
"exists",
"(",
"ticket",
")",
"logging",
".",
"debug",
"(",
"'[CAS] Session [{}] exists: {}'",
".",
"format",
"(",
"ticket",
",",
"exists",
")",
")",
"return",
"exists"
] | Test if a session records exists for a service ticket. | [
"Test",
"if",
"a",
"session",
"records",
"exists",
"for",
"a",
"service",
"ticket",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L311-L318 | train | 235,191 |
discogs/python-cas-client | cas_client/cas_client.py | MemcachedCASSessionAdapter.create | def create(self, ticket, payload=None, expires=None):
'''
Create a session identifier in memcache associated with ``ticket``.
'''
if not payload:
payload = True
self._client.set(str(ticket), payload, expires) | python | def create(self, ticket, payload=None, expires=None):
'''
Create a session identifier in memcache associated with ``ticket``.
'''
if not payload:
payload = True
self._client.set(str(ticket), payload, expires) | [
"def",
"create",
"(",
"self",
",",
"ticket",
",",
"payload",
"=",
"None",
",",
"expires",
"=",
"None",
")",
":",
"if",
"not",
"payload",
":",
"payload",
"=",
"True",
"self",
".",
"_client",
".",
"set",
"(",
"str",
"(",
"ticket",
")",
",",
"payload",
",",
"expires",
")"
] | Create a session identifier in memcache associated with ``ticket``. | [
"Create",
"a",
"session",
"identifier",
"in",
"memcache",
"associated",
"with",
"ticket",
"."
] | f1efa2f49a22d43135014cb1b8d9dd3875304318 | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L612-L618 | train | 235,192 |
CZ-NIC/python-rt | rt.py | Rt.__check_response | def __check_response(self, msg):
""" Search general errors in server response and raise exceptions when found.
:keyword msg: Result message
:raises NotAllowed: Exception raised when operation was called with
insufficient privileges
:raises AuthorizationError: Credentials are invalid or missing
:raises APISyntaxError: Syntax error
"""
if not isinstance(msg, list):
msg = msg.split("\n")
if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]):
raise NotAllowed(msg[2][2:])
if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]):
raise AuthorizationError('Credentials required.')
if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]):
raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.')
if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]):
raise BadRequest(msg[3] if len(msg) > 2 else 'Bad request.') | python | def __check_response(self, msg):
""" Search general errors in server response and raise exceptions when found.
:keyword msg: Result message
:raises NotAllowed: Exception raised when operation was called with
insufficient privileges
:raises AuthorizationError: Credentials are invalid or missing
:raises APISyntaxError: Syntax error
"""
if not isinstance(msg, list):
msg = msg.split("\n")
if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]):
raise NotAllowed(msg[2][2:])
if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]):
raise AuthorizationError('Credentials required.')
if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]):
raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.')
if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]):
raise BadRequest(msg[3] if len(msg) > 2 else 'Bad request.') | [
"def",
"__check_response",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"list",
")",
":",
"msg",
"=",
"msg",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'not_allowed_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
":",
"raise",
"NotAllowed",
"(",
"msg",
"[",
"2",
"]",
"[",
"2",
":",
"]",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'credentials_required_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"0",
"]",
")",
":",
"raise",
"AuthorizationError",
"(",
"'Credentials required.'",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'syntax_error_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"0",
"]",
")",
":",
"raise",
"APISyntaxError",
"(",
"msg",
"[",
"2",
"]",
"[",
"2",
":",
"]",
"if",
"len",
"(",
"msg",
")",
">",
"2",
"else",
"'Syntax error.'",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'bad_request_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"0",
"]",
")",
":",
"raise",
"BadRequest",
"(",
"msg",
"[",
"3",
"]",
"if",
"len",
"(",
"msg",
")",
">",
"2",
"else",
"'Bad request.'",
")"
] | Search general errors in server response and raise exceptions when found.
:keyword msg: Result message
:raises NotAllowed: Exception raised when operation was called with
insufficient privileges
:raises AuthorizationError: Credentials are invalid or missing
:raises APISyntaxError: Syntax error | [
"Search",
"general",
"errors",
"in",
"server",
"response",
"and",
"raise",
"exceptions",
"when",
"found",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L313-L331 | train | 235,193 |
CZ-NIC/python-rt | rt.py | Rt.__normalize_list | def __normalize_list(self, msg):
"""Split message to list by commas and trim whitespace."""
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(","))) | python | def __normalize_list(self, msg):
"""Split message to list by commas and trim whitespace."""
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(","))) | [
"def",
"__normalize_list",
"(",
"self",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"list",
")",
":",
"msg",
"=",
"\"\"",
".",
"join",
"(",
"msg",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"msg",
".",
"split",
"(",
"\",\"",
")",
")",
")"
] | Split message to list by commas and trim whitespace. | [
"Split",
"message",
"to",
"list",
"by",
"commas",
"and",
"trim",
"whitespace",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L333-L337 | train | 235,194 |
CZ-NIC/python-rt | rt.py | Rt.login | def login(self, login=None, password=None):
""" Login with default or supplied credetials.
.. note::
Calling this method is not necessary when HTTP basic or HTTP
digest_auth authentication is used and RT accepts it as external
authentication method, because the login in this case is done
transparently by requests module. Anyway this method can be useful
to check whether given credentials are valid or not.
:keyword login: Username used for RT, if not supplied together with
*password* :py:attr:`~Rt.default_login` and
:py:attr:`~Rt.default_password` are used instead
:keyword password: Similarly as *login*
:returns: ``True``
Successful login
``False``
Otherwise
:raises AuthorizationError: In case that credentials are not supplied neither
during inicialization or call of this method.
"""
if (login is not None) and (password is not None):
login_data = {'user': login, 'pass': password}
elif (self.default_login is not None) and (self.default_password is not None):
login_data = {'user': self.default_login, 'pass': self.default_password}
elif self.session.auth:
login_data = None
else:
raise AuthorizationError('Credentials required, fill login and password.')
try:
self.login_result = self.__get_status_code(self.__request('',
post_data=login_data,
without_login=True)) == 200
except AuthorizationError:
# This happens when HTTP Basic or Digest authentication fails, but
# we will not raise the error but just return False to indicate
# invalid credentials
return False
return self.login_result | python | def login(self, login=None, password=None):
""" Login with default or supplied credetials.
.. note::
Calling this method is not necessary when HTTP basic or HTTP
digest_auth authentication is used and RT accepts it as external
authentication method, because the login in this case is done
transparently by requests module. Anyway this method can be useful
to check whether given credentials are valid or not.
:keyword login: Username used for RT, if not supplied together with
*password* :py:attr:`~Rt.default_login` and
:py:attr:`~Rt.default_password` are used instead
:keyword password: Similarly as *login*
:returns: ``True``
Successful login
``False``
Otherwise
:raises AuthorizationError: In case that credentials are not supplied neither
during inicialization or call of this method.
"""
if (login is not None) and (password is not None):
login_data = {'user': login, 'pass': password}
elif (self.default_login is not None) and (self.default_password is not None):
login_data = {'user': self.default_login, 'pass': self.default_password}
elif self.session.auth:
login_data = None
else:
raise AuthorizationError('Credentials required, fill login and password.')
try:
self.login_result = self.__get_status_code(self.__request('',
post_data=login_data,
without_login=True)) == 200
except AuthorizationError:
# This happens when HTTP Basic or Digest authentication fails, but
# we will not raise the error but just return False to indicate
# invalid credentials
return False
return self.login_result | [
"def",
"login",
"(",
"self",
",",
"login",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"(",
"login",
"is",
"not",
"None",
")",
"and",
"(",
"password",
"is",
"not",
"None",
")",
":",
"login_data",
"=",
"{",
"'user'",
":",
"login",
",",
"'pass'",
":",
"password",
"}",
"elif",
"(",
"self",
".",
"default_login",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"default_password",
"is",
"not",
"None",
")",
":",
"login_data",
"=",
"{",
"'user'",
":",
"self",
".",
"default_login",
",",
"'pass'",
":",
"self",
".",
"default_password",
"}",
"elif",
"self",
".",
"session",
".",
"auth",
":",
"login_data",
"=",
"None",
"else",
":",
"raise",
"AuthorizationError",
"(",
"'Credentials required, fill login and password.'",
")",
"try",
":",
"self",
".",
"login_result",
"=",
"self",
".",
"__get_status_code",
"(",
"self",
".",
"__request",
"(",
"''",
",",
"post_data",
"=",
"login_data",
",",
"without_login",
"=",
"True",
")",
")",
"==",
"200",
"except",
"AuthorizationError",
":",
"# This happens when HTTP Basic or Digest authentication fails, but",
"# we will not raise the error but just return False to indicate",
"# invalid credentials",
"return",
"False",
"return",
"self",
".",
"login_result"
] | Login with default or supplied credetials.
.. note::
Calling this method is not necessary when HTTP basic or HTTP
digest_auth authentication is used and RT accepts it as external
authentication method, because the login in this case is done
transparently by requests module. Anyway this method can be useful
to check whether given credentials are valid or not.
:keyword login: Username used for RT, if not supplied together with
*password* :py:attr:`~Rt.default_login` and
:py:attr:`~Rt.default_password` are used instead
:keyword password: Similarly as *login*
:returns: ``True``
Successful login
``False``
Otherwise
:raises AuthorizationError: In case that credentials are not supplied neither
during inicialization or call of this method. | [
"Login",
"with",
"default",
"or",
"supplied",
"credetials",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L339-L380 | train | 235,195 |
CZ-NIC/python-rt | rt.py | Rt.logout | def logout(self):
""" Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login)
"""
ret = False
if self.login_result is True:
ret = self.__get_status_code(self.__request('logout')) == 200
self.login_result = None
return ret | python | def logout(self):
""" Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login)
"""
ret = False
if self.login_result is True:
ret = self.__get_status_code(self.__request('logout')) == 200
self.login_result = None
return ret | [
"def",
"logout",
"(",
"self",
")",
":",
"ret",
"=",
"False",
"if",
"self",
".",
"login_result",
"is",
"True",
":",
"ret",
"=",
"self",
".",
"__get_status_code",
"(",
"self",
".",
"__request",
"(",
"'logout'",
")",
")",
"==",
"200",
"self",
".",
"login_result",
"=",
"None",
"return",
"ret"
] | Logout of user.
:returns: ``True``
Successful logout
``False``
Logout failed (mainly because user was not login) | [
"Logout",
"of",
"user",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L382-L394 | train | 235,196 |
CZ-NIC/python-rt | rt.py | Rt.new_correspondence | def new_correspondence(self, queue=None):
""" Obtains tickets changed by other users than the system one.
:keyword queue: Queue where to search
:returns: List of tickets which were last updated by other user than
the system one ordered in decreasing order by LastUpdated.
Each ticket is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.
"""
return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login) | python | def new_correspondence(self, queue=None):
""" Obtains tickets changed by other users than the system one.
:keyword queue: Queue where to search
:returns: List of tickets which were last updated by other user than
the system one ordered in decreasing order by LastUpdated.
Each ticket is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.
"""
return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login) | [
"def",
"new_correspondence",
"(",
"self",
",",
"queue",
"=",
"None",
")",
":",
"return",
"self",
".",
"search",
"(",
"Queue",
"=",
"queue",
",",
"order",
"=",
"'-LastUpdated'",
",",
"LastUpdatedBy__notexact",
"=",
"self",
".",
"default_login",
")"
] | Obtains tickets changed by other users than the system one.
:keyword queue: Queue where to search
:returns: List of tickets which were last updated by other user than
the system one ordered in decreasing order by LastUpdated.
Each ticket is dictionary, the same as in
:py:meth:`~Rt.get_ticket`. | [
"Obtains",
"tickets",
"changed",
"by",
"other",
"users",
"than",
"the",
"system",
"one",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L396-L406 | train | 235,197 |
CZ-NIC/python-rt | rt.py | Rt.last_updated | def last_updated(self, since, queue=None):
""" Obtains tickets changed after given date.
:param since: Date as string in form '2011-02-24'
:keyword queue: Queue where to search
:returns: List of tickets with LastUpdated parameter later than
*since* ordered in decreasing order by LastUpdated.
Each tickets is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.
"""
return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since) | python | def last_updated(self, since, queue=None):
""" Obtains tickets changed after given date.
:param since: Date as string in form '2011-02-24'
:keyword queue: Queue where to search
:returns: List of tickets with LastUpdated parameter later than
*since* ordered in decreasing order by LastUpdated.
Each tickets is dictionary, the same as in
:py:meth:`~Rt.get_ticket`.
"""
return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since) | [
"def",
"last_updated",
"(",
"self",
",",
"since",
",",
"queue",
"=",
"None",
")",
":",
"return",
"self",
".",
"search",
"(",
"Queue",
"=",
"queue",
",",
"order",
"=",
"'-LastUpdated'",
",",
"LastUpdatedBy__notexact",
"=",
"self",
".",
"default_login",
",",
"LastUpdated__gt",
"=",
"since",
")"
] | Obtains tickets changed after given date.
:param since: Date as string in form '2011-02-24'
:keyword queue: Queue where to search
:returns: List of tickets with LastUpdated parameter later than
*since* ordered in decreasing order by LastUpdated.
Each tickets is dictionary, the same as in
:py:meth:`~Rt.get_ticket`. | [
"Obtains",
"tickets",
"changed",
"after",
"given",
"date",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L408-L419 | train | 235,198 |
CZ-NIC/python-rt | rt.py | Rt.get_ticket | def get_ticket(self, ticket_id):
""" Fetch ticket by its ID.
:param ticket_id: ID of demanded ticket
:returns: Dictionary with key, value pairs for ticket with
*ticket_id* or None if ticket does not exist. List of keys:
* id
* numerical_id
* Queue
* Owner
* Creator
* Subject
* Status
* Priority
* InitialPriority
* FinalPriority
* Requestors
* Cc
* AdminCc
* Created
* Starts
* Started
* Due
* Resolved
* Told
* TimeEstimated
* TimeWorked
* TimeLeft
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
msg = self.__request('ticket/{}/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if status_code == 200:
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)]
req_id = req_matching[0] if req_matching else None
if not req_id:
raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.')
for i in range(req_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
requestors = [msg[req_id][12:]]
req_id += 1
while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12):
requestors.append(msg[req_id][12:])
req_id += 1
pairs['Requestors'] = self.__normalize_list(requestors)
for i in range(req_id, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
if 'Cc' in pairs:
pairs['Cc'] = self.__normalize_list(pairs['Cc'])
if 'AdminCc' in pairs:
pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc'])
if 'id' not in pairs and not pairs['id'].startswitch('ticket/'):
raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id')
else:
pairs['numerical_id'] = pairs['id'].split('ticket/')[1]
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | python | def get_ticket(self, ticket_id):
""" Fetch ticket by its ID.
:param ticket_id: ID of demanded ticket
:returns: Dictionary with key, value pairs for ticket with
*ticket_id* or None if ticket does not exist. List of keys:
* id
* numerical_id
* Queue
* Owner
* Creator
* Subject
* Status
* Priority
* InitialPriority
* FinalPriority
* Requestors
* Cc
* AdminCc
* Created
* Starts
* Started
* Due
* Resolved
* Told
* TimeEstimated
* TimeWorked
* TimeLeft
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
msg = self.__request('ticket/{}/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if status_code == 200:
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
req_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['requestors_pattern'].match(m)]
req_id = req_matching[0] if req_matching else None
if not req_id:
raise UnexpectedMessageFormat('Missing line starting with `Requestors:`.')
for i in range(req_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
requestors = [msg[req_id][12:]]
req_id += 1
while (req_id < len(msg)) and (msg[req_id][:12] == ' ' * 12):
requestors.append(msg[req_id][12:])
req_id += 1
pairs['Requestors'] = self.__normalize_list(requestors)
for i in range(req_id, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
if 'Cc' in pairs:
pairs['Cc'] = self.__normalize_list(pairs['Cc'])
if 'AdminCc' in pairs:
pairs['AdminCc'] = self.__normalize_list(pairs['AdminCc'])
if 'id' not in pairs and not pairs['id'].startswitch('ticket/'):
raise UnexpectedMessageFormat('Response from RT didn\'t contain a valid ticket_id')
else:
pairs['numerical_id'] = pairs['id'].split('ticket/')[1]
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | [
"def",
"get_ticket",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/show'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"if",
"status_code",
"==",
"200",
":",
"pairs",
"=",
"{",
"}",
"msg",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
":",
"return",
"None",
"req_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'requestors_pattern'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"req_id",
"=",
"req_matching",
"[",
"0",
"]",
"if",
"req_matching",
"else",
"None",
"if",
"not",
"req_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Missing line starting with `Requestors:`.'",
")",
"for",
"i",
"in",
"range",
"(",
"req_id",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"requestors",
"=",
"[",
"msg",
"[",
"req_id",
"]",
"[",
"12",
":",
"]",
"]",
"req_id",
"+=",
"1",
"while",
"(",
"req_id",
"<",
"len",
"(",
"msg",
")",
")",
"and",
"(",
"msg",
"[",
"req_id",
"]",
"[",
":",
"12",
"]",
"==",
"' '",
"*",
"12",
")",
":",
"requestors",
".",
"append",
"(",
"msg",
"[",
"req_id",
"]",
"[",
"12",
":",
"]",
")",
"req_id",
"+=",
"1",
"pairs",
"[",
"'Requestors'",
"]",
"=",
"self",
".",
"__normalize_list",
"(",
"requestors",
")",
"for",
"i",
"in",
"range",
"(",
"req_id",
",",
"len",
"(",
"msg",
")",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"if",
"'Cc'",
"in",
"pairs",
":",
"pairs",
"[",
"'Cc'",
"]",
"=",
"self",
".",
"__normalize_list",
"(",
"pairs",
"[",
"'Cc'",
"]",
")",
"if",
"'AdminCc'",
"in",
"pairs",
":",
"pairs",
"[",
"'AdminCc'",
"]",
"=",
"self",
".",
"__normalize_list",
"(",
"pairs",
"[",
"'AdminCc'",
"]",
")",
"if",
"'id'",
"not",
"in",
"pairs",
"and",
"not",
"pairs",
"[",
"'id'",
"]",
".",
"startswitch",
"(",
"'ticket/'",
")",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Response from RT didn\\'t contain a valid ticket_id'",
")",
"else",
":",
"pairs",
"[",
"'numerical_id'",
"]",
"=",
"pairs",
"[",
"'id'",
"]",
".",
"split",
"(",
"'ticket/'",
")",
"[",
"1",
"]",
"return",
"pairs",
"else",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Received status code is {:d} instead of 200.'",
".",
"format",
"(",
"status_code",
")",
")"
] | Fetch ticket by its ID.
:param ticket_id: ID of demanded ticket
:returns: Dictionary with key, value pairs for ticket with
*ticket_id* or None if ticket does not exist. List of keys:
* id
* numerical_id
* Queue
* Owner
* Creator
* Subject
* Status
* Priority
* InitialPriority
* FinalPriority
* Requestors
* Cc
* AdminCc
* Created
* Starts
* Started
* Due
* Resolved
* Told
* TimeEstimated
* TimeWorked
* TimeLeft
:raises UnexpectedMessageFormat: Unexpected format of returned message. | [
"Fetch",
"ticket",
"by",
"its",
"ID",
"."
] | e7a9f555e136708aec3317f857045145a2271e16 | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L570-L640 | train | 235,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.