repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L299-L319 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L321-L334 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L336-L342 |
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):
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')
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()
for check in self._early_checks:
self.check_incoming(*check)
self._early_checks = []
while True:
if not self.check_periodic():
break
await asyncio.sleep(0.02)
if self._check_list:
res = await self._check_list_state.get()
else:
res = ICE_FAILED
for check in self._check_list:
if check.handle:
check.handle.cancel()
if res != ICE_COMPLETED:
raise ConnectionError('ICE negotiation failed')
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L344-L395 |
aiortc/aioice | aioice/ice.py | Connection.close | async def close(self):
"""
Close the connection.
"""
# stop consent freshness tests
if self._query_consent_handle and not self._query_consent_handle.done():
self._query_consent_handle.cancel()
try:
await self._query_consent_handle
except asyncio.CancelledError:
pass
# stop check list
if self._check_list and not self._check_list_done:
await self._check_list_state.put(ICE_FAILED)
self._nominated.clear()
for protocol in self._protocols:
await protocol.close()
self._protocols.clear()
self._local_candidates.clear() | python | async def close(self):
if self._query_consent_handle and not self._query_consent_handle.done():
self._query_consent_handle.cancel()
try:
await self._query_consent_handle
except asyncio.CancelledError:
pass
if self._check_list and not self._check_list_done:
await self._check_list_state.put(ICE_FAILED)
self._nominated.clear()
for protocol in self._protocols:
await protocol.close()
self._protocols.clear()
self._local_candidates.clear() | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"# stop consent freshness tests",
"if",
"self",
".",
"_query_consent_handle",
"and",
"not",
"self",
".",
"_query_consent_handle",
".",
"done",
"(",
")",
":",
"self",
".",
"_query_consent_handle",
".",
"cancel",
"(",
")",
"try",
":",
"await",
"self",
".",
"_query_consent_handle",
"except",
"asyncio",
".",
"CancelledError",
":",
"pass",
"# stop check list",
"if",
"self",
".",
"_check_list",
"and",
"not",
"self",
".",
"_check_list_done",
":",
"await",
"self",
".",
"_check_list_state",
".",
"put",
"(",
"ICE_FAILED",
")",
"self",
".",
"_nominated",
".",
"clear",
"(",
")",
"for",
"protocol",
"in",
"self",
".",
"_protocols",
":",
"await",
"protocol",
".",
"close",
"(",
")",
"self",
".",
"_protocols",
".",
"clear",
"(",
")",
"self",
".",
"_local_candidates",
".",
"clear",
"(",
")"
]
| Close the connection. | [
"Close",
"the",
"connection",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L397-L417 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L430-L446 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L456-L466 |
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):
protocol = None
for p in self._protocols:
if (p.local_candidate.component == component and
p.local_candidate.foundation == local_foundation):
protocol = p
break
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L468-L490 |
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):
component = protocol.local_candidate.component
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:
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)
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()
if pair.state in [CandidatePair.State.WAITING, CandidatePair.State.FAILED]:
pair.handle = asyncio.ensure_future(self.check_start(pair))
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L554-L598 |
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):
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:
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
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
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L619-L654 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L656-L661 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L663-L670 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L740-L750 |
aiortc/aioice | aioice/ice.py | Connection.query_consent | async def query_consent(self):
"""
Periodically check consent (RFC 7675).
"""
failures = 0
while True:
# randomize between 0.8 and 1.2 times CONSENT_INTERVAL
await asyncio.sleep(CONSENT_INTERVAL * (0.8 + 0.4 * random.random()))
for pair in self._nominated.values():
request = self.build_request(pair)
try:
await pair.protocol.request(
request, pair.remote_addr,
integrity_key=self.remote_password.encode('utf8'),
retransmissions=0)
failures = 0
except exceptions.TransactionError:
failures += 1
if failures >= CONSENT_FAILURES:
self.__log_info('Consent to send expired')
self._query_consent_handle = None
return await self.close() | python | async def query_consent(self):
failures = 0
while True:
await asyncio.sleep(CONSENT_INTERVAL * (0.8 + 0.4 * random.random()))
for pair in self._nominated.values():
request = self.build_request(pair)
try:
await pair.protocol.request(
request, pair.remote_addr,
integrity_key=self.remote_password.encode('utf8'),
retransmissions=0)
failures = 0
except exceptions.TransactionError:
failures += 1
if failures >= CONSENT_FAILURES:
self.__log_info('Consent to send expired')
self._query_consent_handle = None
return await self.close() | [
"async",
"def",
"query_consent",
"(",
"self",
")",
":",
"failures",
"=",
"0",
"while",
"True",
":",
"# randomize between 0.8 and 1.2 times CONSENT_INTERVAL",
"await",
"asyncio",
".",
"sleep",
"(",
"CONSENT_INTERVAL",
"*",
"(",
"0.8",
"+",
"0.4",
"*",
"random",
".",
"random",
"(",
")",
")",
")",
"for",
"pair",
"in",
"self",
".",
"_nominated",
".",
"values",
"(",
")",
":",
"request",
"=",
"self",
".",
"build_request",
"(",
"pair",
")",
"try",
":",
"await",
"pair",
".",
"protocol",
".",
"request",
"(",
"request",
",",
"pair",
".",
"remote_addr",
",",
"integrity_key",
"=",
"self",
".",
"remote_password",
".",
"encode",
"(",
"'utf8'",
")",
",",
"retransmissions",
"=",
"0",
")",
"failures",
"=",
"0",
"except",
"exceptions",
".",
"TransactionError",
":",
"failures",
"+=",
"1",
"if",
"failures",
">=",
"CONSENT_FAILURES",
":",
"self",
".",
"__log_info",
"(",
"'Consent to send expired'",
")",
"self",
".",
"_query_consent_handle",
"=",
"None",
"return",
"await",
"self",
".",
"close",
"(",
")"
]
| Periodically check consent (RFC 7675). | [
"Periodically",
"check",
"consent",
"(",
"RFC",
"7675",
")",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L752-L774 |
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):
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",
"."
]
| train | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/stun.py#L268-L306 |
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:
if self._stream_reader is None:
raise SMTPServerDisconnected("Client not connected")
self._stream_reader._transport = transport
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(
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L50-L68 |
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:
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
tls_protocol = SSLProtocol(
self._loop,
self,
context,
waiter,
server_side=False,
server_hostname=server_hostname,
)
app_transport = tls_protocol._app_transport
if hasattr(transport, "set_protocol"):
transport.set_protocol(tls_protocol)
else:
transport._protocol = tls_protocol
self._stream_reader._transport = app_transport
self._stream_writer._transport = app_transport
tls_protocol.connection_made(transport)
self._over_ssl = True
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L70-L109 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L111-L148 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L150-L160 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L162-L176 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L178-L190 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol.starttls | async def starttls(
self,
tls_context: ssl.SSLContext,
server_hostname: str = None,
timeout: NumType = None,
) -> StartTLSResponse:
"""
Puts the connection to the SMTP server into TLS mode.
"""
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
response = await self.execute_command(b"STARTTLS", timeout=timeout)
if response.code != SMTPStatus.ready:
raise SMTPResponseException(response.code, response.message)
await self._drain_writer(timeout)
waiter = asyncio.Future(loop=self._loop) # type: asyncio.Future
tls_protocol = self.upgrade_transport(
tls_context, server_hostname=server_hostname, waiter=waiter
)
try:
await asyncio.wait_for(waiter, timeout=timeout, loop=self._loop)
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc))
return response, tls_protocol | python | async def starttls(
self,
tls_context: ssl.SSLContext,
server_hostname: str = None,
timeout: NumType = None,
) -> StartTLSResponse:
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
response = await self.execute_command(b"STARTTLS", timeout=timeout)
if response.code != SMTPStatus.ready:
raise SMTPResponseException(response.code, response.message)
await self._drain_writer(timeout)
waiter = asyncio.Future(loop=self._loop)
tls_protocol = self.upgrade_transport(
tls_context, server_hostname=server_hostname, waiter=waiter
)
try:
await asyncio.wait_for(waiter, timeout=timeout, loop=self._loop)
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc))
return response, tls_protocol | [
"async",
"def",
"starttls",
"(",
"self",
",",
"tls_context",
":",
"ssl",
".",
"SSLContext",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
"timeout",
":",
"NumType",
"=",
"None",
",",
")",
"->",
"StartTLSResponse",
":",
"if",
"self",
".",
"_stream_reader",
"is",
"None",
"or",
"self",
".",
"_stream_writer",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"STARTTLS\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"ready",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"await",
"self",
".",
"_drain_writer",
"(",
"timeout",
")",
"waiter",
"=",
"asyncio",
".",
"Future",
"(",
"loop",
"=",
"self",
".",
"_loop",
")",
"# type: asyncio.Future",
"tls_protocol",
"=",
"self",
".",
"upgrade_transport",
"(",
"tls_context",
",",
"server_hostname",
"=",
"server_hostname",
",",
"waiter",
"=",
"waiter",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"waiter",
",",
"timeout",
"=",
"timeout",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"except",
"asyncio",
".",
"TimeoutError",
"as",
"exc",
":",
"raise",
"SMTPTimeoutError",
"(",
"str",
"(",
"exc",
")",
")",
"return",
"response",
",",
"tls_protocol"
]
| Puts the connection to the SMTP server into TLS mode. | [
"Puts",
"the",
"connection",
"to",
"the",
"SMTP",
"server",
"into",
"TLS",
"mode",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L192-L222 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol._drain_writer | async def _drain_writer(self, timeout: NumType = None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
# Wrapping drain in a task makes mypy happy
drain_task = asyncio.Task(self._stream_writer.drain(), loop=self._loop)
try:
await asyncio.wait_for(drain_task, timeout, loop=self._loop)
except ConnectionError as exc:
raise SMTPServerDisconnected(str(exc))
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc)) | python | async def _drain_writer(self, timeout: NumType = None) -> None:
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
drain_task = asyncio.Task(self._stream_writer.drain(), loop=self._loop)
try:
await asyncio.wait_for(drain_task, timeout, loop=self._loop)
except ConnectionError as exc:
raise SMTPServerDisconnected(str(exc))
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc)) | [
"async",
"def",
"_drain_writer",
"(",
"self",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"_stream_writer",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"# Wrapping drain in a task makes mypy happy",
"drain_task",
"=",
"asyncio",
".",
"Task",
"(",
"self",
".",
"_stream_writer",
".",
"drain",
"(",
")",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"try",
":",
"await",
"asyncio",
".",
"wait_for",
"(",
"drain_task",
",",
"timeout",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"except",
"ConnectionError",
"as",
"exc",
":",
"raise",
"SMTPServerDisconnected",
"(",
"str",
"(",
"exc",
")",
")",
"except",
"asyncio",
".",
"TimeoutError",
"as",
"exc",
":",
"raise",
"SMTPTimeoutError",
"(",
"str",
"(",
"exc",
")",
")"
]
| Wraps writer.drain() with error handling. | [
"Wraps",
"writer",
".",
"drain",
"()",
"with",
"error",
"handling",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L224-L238 |
cole/aiosmtplib | src/aiosmtplib/protocol.py | SMTPProtocol._readline | async def _readline(self, timeout: NumType = None):
"""
Wraps reader.readuntil() with error handling.
"""
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
read_task = asyncio.Task(
self._stream_reader.readuntil(separator=b"\n"), loop=self._loop
)
try:
line = await asyncio.wait_for(
read_task, timeout, loop=self._loop
) # type: bytes
except asyncio.LimitOverrunError:
raise SMTPResponseException(
SMTPStatus.unrecognized_command, "Line too long."
)
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc))
except asyncio.IncompleteReadError as exc:
if exc.partial == b"":
# if we got only an EOF, raise SMTPServerDisconnected
raise SMTPServerDisconnected("Unexpected EOF received")
else:
# otherwise, close our connection but try to parse the
# response anyways
self._stream_writer.close()
line = exc.partial
return line | python | async def _readline(self, timeout: NumType = None):
if self._stream_reader is None or self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
read_task = asyncio.Task(
self._stream_reader.readuntil(separator=b"\n"), loop=self._loop
)
try:
line = await asyncio.wait_for(
read_task, timeout, loop=self._loop
)
except asyncio.LimitOverrunError:
raise SMTPResponseException(
SMTPStatus.unrecognized_command, "Line too long."
)
except asyncio.TimeoutError as exc:
raise SMTPTimeoutError(str(exc))
except asyncio.IncompleteReadError as exc:
if exc.partial == b"":
raise SMTPServerDisconnected("Unexpected EOF received")
else:
self._stream_writer.close()
line = exc.partial
return line | [
"async",
"def",
"_readline",
"(",
"self",
",",
"timeout",
":",
"NumType",
"=",
"None",
")",
":",
"if",
"self",
".",
"_stream_reader",
"is",
"None",
"or",
"self",
".",
"_stream_writer",
"is",
"None",
":",
"raise",
"SMTPServerDisconnected",
"(",
"\"Client not connected\"",
")",
"read_task",
"=",
"asyncio",
".",
"Task",
"(",
"self",
".",
"_stream_reader",
".",
"readuntil",
"(",
"separator",
"=",
"b\"\\n\"",
")",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"try",
":",
"line",
"=",
"await",
"asyncio",
".",
"wait_for",
"(",
"read_task",
",",
"timeout",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"# type: bytes",
"except",
"asyncio",
".",
"LimitOverrunError",
":",
"raise",
"SMTPResponseException",
"(",
"SMTPStatus",
".",
"unrecognized_command",
",",
"\"Line too long.\"",
")",
"except",
"asyncio",
".",
"TimeoutError",
"as",
"exc",
":",
"raise",
"SMTPTimeoutError",
"(",
"str",
"(",
"exc",
")",
")",
"except",
"asyncio",
".",
"IncompleteReadError",
"as",
"exc",
":",
"if",
"exc",
".",
"partial",
"==",
"b\"\"",
":",
"# if we got only an EOF, raise SMTPServerDisconnected",
"raise",
"SMTPServerDisconnected",
"(",
"\"Unexpected EOF received\"",
")",
"else",
":",
"# otherwise, close our connection but try to parse the",
"# response anyways",
"self",
".",
"_stream_writer",
".",
"close",
"(",
")",
"line",
"=",
"exc",
".",
"partial",
"return",
"line"
]
| Wraps reader.readuntil() with error handling. | [
"Wraps",
"reader",
".",
"readuntil",
"()",
"with",
"error",
"handling",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/protocol.py#L240-L270 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | parse_esmtp_extensions | def parse_esmtp_extensions(message: str) -> Tuple[Dict[str, str], List[str]]:
"""
Parse an EHLO response from the server into a dict of {extension: params}
and a list of auth method names.
It might look something like:
220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
EHLO heaven.af.mil
250-size.does.matter.af.MIL offers FIFTEEN extensions:
250-8BITMIME
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-EXPN
250-HELP
250-SAML
250-SEND
250-SOML
250-TURN
250-XADR
250-XSTA
250-ETRN
250-XGEN
250 SIZE 51200000
"""
esmtp_extensions = {}
auth_types = [] # type: List[str]
response_lines = message.split("\n")
# ignore the first line
for line in response_lines[1:]:
# To be able to communicate with as many SMTP servers as possible,
# we have to take the old-style auth advertisement into account,
# because:
# 1) Else our SMTP feature parser gets confused.
# 2) There are some servers that only advertise the auth methods we
# support using the old style.
auth_match = OLDSTYLE_AUTH_REGEX.match(line)
if auth_match is not None:
auth_type = auth_match.group("auth")
auth_types.append(auth_type.lower().strip())
# RFC 1869 requires a space between ehlo keyword and parameters.
# It's actually stricter, in that only spaces are allowed between
# parameters, but were not going to check for that here. Note
# that the space isn't present if there are no parameters.
extensions = EXTENSIONS_REGEX.match(line)
if extensions is not None:
extension = extensions.group("ext").lower()
params = extensions.string[extensions.end("ext") :].strip()
esmtp_extensions[extension] = params
if extension == "auth":
auth_types.extend([param.strip().lower() for param in params.split()])
return esmtp_extensions, auth_types | python | def parse_esmtp_extensions(message: str) -> Tuple[Dict[str, str], List[str]]:
esmtp_extensions = {}
auth_types = []
response_lines = message.split("\n")
for line in response_lines[1:]:
auth_match = OLDSTYLE_AUTH_REGEX.match(line)
if auth_match is not None:
auth_type = auth_match.group("auth")
auth_types.append(auth_type.lower().strip())
extensions = EXTENSIONS_REGEX.match(line)
if extensions is not None:
extension = extensions.group("ext").lower()
params = extensions.string[extensions.end("ext") :].strip()
esmtp_extensions[extension] = params
if extension == "auth":
auth_types.extend([param.strip().lower() for param in params.split()])
return esmtp_extensions, auth_types | [
"def",
"parse_esmtp_extensions",
"(",
"message",
":",
"str",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"esmtp_extensions",
"=",
"{",
"}",
"auth_types",
"=",
"[",
"]",
"# type: List[str]",
"response_lines",
"=",
"message",
".",
"split",
"(",
"\"\\n\"",
")",
"# ignore the first line",
"for",
"line",
"in",
"response_lines",
"[",
"1",
":",
"]",
":",
"# To be able to communicate with as many SMTP servers as possible,",
"# we have to take the old-style auth advertisement into account,",
"# because:",
"# 1) Else our SMTP feature parser gets confused.",
"# 2) There are some servers that only advertise the auth methods we",
"# support using the old style.",
"auth_match",
"=",
"OLDSTYLE_AUTH_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"auth_match",
"is",
"not",
"None",
":",
"auth_type",
"=",
"auth_match",
".",
"group",
"(",
"\"auth\"",
")",
"auth_types",
".",
"append",
"(",
"auth_type",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
")",
"# RFC 1869 requires a space between ehlo keyword and parameters.",
"# It's actually stricter, in that only spaces are allowed between",
"# parameters, but were not going to check for that here. Note",
"# that the space isn't present if there are no parameters.",
"extensions",
"=",
"EXTENSIONS_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"extensions",
"is",
"not",
"None",
":",
"extension",
"=",
"extensions",
".",
"group",
"(",
"\"ext\"",
")",
".",
"lower",
"(",
")",
"params",
"=",
"extensions",
".",
"string",
"[",
"extensions",
".",
"end",
"(",
"\"ext\"",
")",
":",
"]",
".",
"strip",
"(",
")",
"esmtp_extensions",
"[",
"extension",
"]",
"=",
"params",
"if",
"extension",
"==",
"\"auth\"",
":",
"auth_types",
".",
"extend",
"(",
"[",
"param",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"for",
"param",
"in",
"params",
".",
"split",
"(",
")",
"]",
")",
"return",
"esmtp_extensions",
",",
"auth_types"
]
| Parse an EHLO response from the server into a dict of {extension: params}
and a list of auth method names.
It might look something like:
220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
EHLO heaven.af.mil
250-size.does.matter.af.MIL offers FIFTEEN extensions:
250-8BITMIME
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-EXPN
250-HELP
250-SAML
250-SEND
250-SOML
250-TURN
250-XADR
250-XSTA
250-ETRN
250-XGEN
250 SIZE 51200000 | [
"Parse",
"an",
"EHLO",
"response",
"from",
"the",
"server",
"into",
"a",
"dict",
"of",
"{",
"extension",
":",
"params",
"}",
"and",
"a",
"list",
"of",
"auth",
"method",
"names",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L471-L528 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L59-L68 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L86-L107 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L109-L127 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.rset | async def rset(self, timeout: DefaultNumType = _default) -> SMTPResponse:
"""
Send an SMTP RSET command, which resets the server's envelope
(the envelope contains the sender, recipient, and mail data).
: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"RSET", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | python | async def rset(self, timeout: DefaultNumType = _default) -> SMTPResponse:
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"RSET", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResponseException(response.code, response.message)
return response | [
"async",
"def",
"rset",
"(",
"self",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"RSET\"",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPResponseException",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
")",
"return",
"response"
]
| Send an SMTP RSET command, which resets the server's envelope
(the envelope contains the sender, recipient, and mail data).
:raises SMTPResponseException: on unexpected server response code | [
"Send",
"an",
"SMTP",
"RSET",
"command",
"which",
"resets",
"the",
"server",
"s",
"envelope",
"(",
"the",
"envelope",
"contains",
"the",
"sender",
"recipient",
"and",
"mail",
"data",
")",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L129-L143 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L145-L158 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L160-L187 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L189-L210 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L212-L229 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.mail | async def mail(
self,
sender: str,
options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
"""
Send an SMTP MAIL command, which specifies the message sender and
begins a new mail transfer session ("envelope").
:raises SMTPSenderRefused: 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]
from_string = b"FROM:" + quote_address(sender).encode("ascii")
async with self._command_lock:
response = await self.execute_command(
b"MAIL", from_string, *options_bytes, timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPSenderRefused(response.code, response.message, sender)
return response | python | async def mail(
self,
sender: 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]
from_string = b"FROM:" + quote_address(sender).encode("ascii")
async with self._command_lock:
response = await self.execute_command(
b"MAIL", from_string, *options_bytes, timeout=timeout
)
if response.code != SMTPStatus.completed:
raise SMTPSenderRefused(response.code, response.message, sender)
return response | [
"async",
"def",
"mail",
"(",
"self",
",",
"sender",
":",
"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",
"]",
"from_string",
"=",
"b\"FROM:\"",
"+",
"quote_address",
"(",
"sender",
")",
".",
"encode",
"(",
"\"ascii\"",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"response",
"=",
"await",
"self",
".",
"execute_command",
"(",
"b\"MAIL\"",
",",
"from_string",
",",
"*",
"options_bytes",
",",
"timeout",
"=",
"timeout",
")",
"if",
"response",
".",
"code",
"!=",
"SMTPStatus",
".",
"completed",
":",
"raise",
"SMTPSenderRefused",
"(",
"response",
".",
"code",
",",
"response",
".",
"message",
",",
"sender",
")",
"return",
"response"
]
| Send an SMTP MAIL command, which specifies the message sender and
begins a new mail transfer session ("envelope").
:raises SMTPSenderRefused: on unexpected server response code | [
"Send",
"an",
"SMTP",
"MAIL",
"command",
"which",
"specifies",
"the",
"message",
"sender",
"and",
"begins",
"a",
"new",
"mail",
"transfer",
"session",
"(",
"envelope",
")",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L231-L259 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L261-L291 |
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:
await self._ehlo_or_helo_if_needed()
self._raise_error_if_disconnected()
if timeout is _default:
timeout = self.timeout
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(
message, timeout=timeout
)
response = await self.protocol.read_response(
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L293-L333 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L337-L359 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP._ehlo_or_helo_if_needed | async def _ehlo_or_helo_if_needed(self) -> None:
"""
Call self.ehlo() and/or self.helo() if needed.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
"""
async with self._ehlo_or_helo_lock:
if self.is_ehlo_or_helo_needed:
try:
await self.ehlo()
except SMTPHeloError as exc:
if self.is_connected:
await self.helo()
else:
raise exc | python | async def _ehlo_or_helo_if_needed(self) -> None:
async with self._ehlo_or_helo_lock:
if self.is_ehlo_or_helo_needed:
try:
await self.ehlo()
except SMTPHeloError as exc:
if self.is_connected:
await self.helo()
else:
raise exc | [
"async",
"def",
"_ehlo_or_helo_if_needed",
"(",
"self",
")",
"->",
"None",
":",
"async",
"with",
"self",
".",
"_ehlo_or_helo_lock",
":",
"if",
"self",
".",
"is_ehlo_or_helo_needed",
":",
"try",
":",
"await",
"self",
".",
"ehlo",
"(",
")",
"except",
"SMTPHeloError",
"as",
"exc",
":",
"if",
"self",
".",
"is_connected",
":",
"await",
"self",
".",
"helo",
"(",
")",
"else",
":",
"raise",
"exc"
]
| Call self.ehlo() and/or self.helo() if needed.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first. | [
"Call",
"self",
".",
"ehlo",
"()",
"and",
"/",
"or",
"self",
".",
"helo",
"()",
"if",
"needed",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L367-L382 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L384-L392 |
cole/aiosmtplib | src/aiosmtplib/esmtp.py | ESMTP.starttls | async def starttls(
self,
server_hostname: str = None,
validate_certs: bool = None,
client_cert: DefaultStrType = _default,
client_key: DefaultStrType = _default,
cert_bundle: DefaultStrType = _default,
tls_context: DefaultSSLContextType = _default,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
"""
Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked (if
validate_certs is True). You can also provide a custom SSLContext
object. If no certs or SSLContext is given, and TLS config was
provided when initializing the class, STARTTLS will use to that,
otherwise it will use the Python defaults.
:raises SMTPException: server does not support STARTTLS
:raises SMTPServerDisconnected: connection lost
:raises ValueError: invalid options provided
"""
self._raise_error_if_disconnected()
await self._ehlo_or_helo_if_needed()
if validate_certs is not None:
self.validate_certs = validate_certs
if timeout is _default:
timeout = self.timeout # type: ignore
if client_cert is not _default:
self.client_cert = client_cert # type: ignore
if client_key is not _default:
self.client_key = client_key # type: ignore
if cert_bundle is not _default:
self.cert_bundle = cert_bundle # type: ignore
if tls_context is not _default:
self.tls_context = tls_context # type: ignore
if self.tls_context is not None and self.client_cert is not None:
raise ValueError(
"Either a TLS context or a certificate/key must be provided"
)
if server_hostname is None:
server_hostname = self.hostname
tls_context = self._get_tls_context()
if not self.supports_extension("starttls"):
raise SMTPException("SMTP STARTTLS extension not supported by server.")
async with self._command_lock:
try:
response, protocol = await self.protocol.starttls( # type: ignore
tls_context, server_hostname=server_hostname, timeout=timeout
)
except SMTPServerDisconnected:
self.close()
raise
self.transport = protocol._app_transport
# RFC 3207 part 4.2:
# The client MUST discard any knowledge obtained from the server, such
# as the list of SMTP service extensions, which was not obtained from
# the TLS negotiation itself.
self._reset_server_state()
return response | python | async def starttls(
self,
server_hostname: str = None,
validate_certs: bool = None,
client_cert: DefaultStrType = _default,
client_key: DefaultStrType = _default,
cert_bundle: DefaultStrType = _default,
tls_context: DefaultSSLContextType = _default,
timeout: DefaultNumType = _default,
) -> SMTPResponse:
self._raise_error_if_disconnected()
await self._ehlo_or_helo_if_needed()
if validate_certs is not None:
self.validate_certs = validate_certs
if timeout is _default:
timeout = self.timeout
if client_cert is not _default:
self.client_cert = client_cert
if client_key is not _default:
self.client_key = client_key
if cert_bundle is not _default:
self.cert_bundle = cert_bundle
if tls_context is not _default:
self.tls_context = tls_context
if self.tls_context is not None and self.client_cert is not None:
raise ValueError(
"Either a TLS context or a certificate/key must be provided"
)
if server_hostname is None:
server_hostname = self.hostname
tls_context = self._get_tls_context()
if not self.supports_extension("starttls"):
raise SMTPException("SMTP STARTTLS extension not supported by server.")
async with self._command_lock:
try:
response, protocol = await self.protocol.starttls(
tls_context, server_hostname=server_hostname, timeout=timeout
)
except SMTPServerDisconnected:
self.close()
raise
self.transport = protocol._app_transport
self._reset_server_state()
return response | [
"async",
"def",
"starttls",
"(",
"self",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
"validate_certs",
":",
"bool",
"=",
"None",
",",
"client_cert",
":",
"DefaultStrType",
"=",
"_default",
",",
"client_key",
":",
"DefaultStrType",
"=",
"_default",
",",
"cert_bundle",
":",
"DefaultStrType",
"=",
"_default",
",",
"tls_context",
":",
"DefaultSSLContextType",
"=",
"_default",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SMTPResponse",
":",
"self",
".",
"_raise_error_if_disconnected",
"(",
")",
"await",
"self",
".",
"_ehlo_or_helo_if_needed",
"(",
")",
"if",
"validate_certs",
"is",
"not",
"None",
":",
"self",
".",
"validate_certs",
"=",
"validate_certs",
"if",
"timeout",
"is",
"_default",
":",
"timeout",
"=",
"self",
".",
"timeout",
"# type: ignore",
"if",
"client_cert",
"is",
"not",
"_default",
":",
"self",
".",
"client_cert",
"=",
"client_cert",
"# type: ignore",
"if",
"client_key",
"is",
"not",
"_default",
":",
"self",
".",
"client_key",
"=",
"client_key",
"# type: ignore",
"if",
"cert_bundle",
"is",
"not",
"_default",
":",
"self",
".",
"cert_bundle",
"=",
"cert_bundle",
"# type: ignore",
"if",
"tls_context",
"is",
"not",
"_default",
":",
"self",
".",
"tls_context",
"=",
"tls_context",
"# type: ignore",
"if",
"self",
".",
"tls_context",
"is",
"not",
"None",
"and",
"self",
".",
"client_cert",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Either a TLS context or a certificate/key must be provided\"",
")",
"if",
"server_hostname",
"is",
"None",
":",
"server_hostname",
"=",
"self",
".",
"hostname",
"tls_context",
"=",
"self",
".",
"_get_tls_context",
"(",
")",
"if",
"not",
"self",
".",
"supports_extension",
"(",
"\"starttls\"",
")",
":",
"raise",
"SMTPException",
"(",
"\"SMTP STARTTLS extension not supported by server.\"",
")",
"async",
"with",
"self",
".",
"_command_lock",
":",
"try",
":",
"response",
",",
"protocol",
"=",
"await",
"self",
".",
"protocol",
".",
"starttls",
"(",
"# type: ignore",
"tls_context",
",",
"server_hostname",
"=",
"server_hostname",
",",
"timeout",
"=",
"timeout",
")",
"except",
"SMTPServerDisconnected",
":",
"self",
".",
"close",
"(",
")",
"raise",
"self",
".",
"transport",
"=",
"protocol",
".",
"_app_transport",
"# RFC 3207 part 4.2:",
"# The client MUST discard any knowledge obtained from the server, such",
"# as the list of SMTP service extensions, which was not obtained from",
"# the TLS negotiation itself.",
"self",
".",
"_reset_server_state",
"(",
")",
"return",
"response"
]
| Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked (if
validate_certs is True). You can also provide a custom SSLContext
object. If no certs or SSLContext is given, and TLS config was
provided when initializing the class, STARTTLS will use to that,
otherwise it will use the Python defaults.
:raises SMTPException: server does not support STARTTLS
:raises SMTPServerDisconnected: connection lost
:raises ValueError: invalid options provided | [
"Puts",
"the",
"connection",
"to",
"the",
"SMTP",
"server",
"into",
"TLS",
"mode",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/esmtp.py#L394-L468 |
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]:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L40-L44 |
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:
await self._ehlo_or_helo_if_needed()
if not self.supports_extension("auth"):
raise SMTPException("SMTP AUTH extension not supported by server.")
response = None
exception = None
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L46-L82 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L84-L122 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L124-L151 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/auth.py#L153-L197 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L16-L22 |
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:
display_name, parsed_address = email.utils.parseaddr(address)
if parsed_address:
quoted_address = "<{}>".format(parsed_address)
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L25-L38 |
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:
if resent_dates:
sender_header = "Resent-Sender"
from_header = "Resent-From"
else:
sender_header = "Sender"
from_header = "From"
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L62-L81 |
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]:
recipients = []
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, []))
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/email.py#L84-L105 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection.source_address | def source_address(self) -> str:
"""
Get the system hostname to be sent to the SMTP server.
Simply caches the result of :func:`socket.getfqdn`.
"""
if self._source_address is None:
self._source_address = socket.getfqdn()
return self._source_address | python | def source_address(self) -> str:
if self._source_address is None:
self._source_address = socket.getfqdn()
return self._source_address | [
"def",
"source_address",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_source_address",
"is",
"None",
":",
"self",
".",
"_source_address",
"=",
"socket",
".",
"getfqdn",
"(",
")",
"return",
"self",
".",
"_source_address"
]
| Get the system hostname to be sent to the SMTP server.
Simply caches the result of :func:`socket.getfqdn`. | [
"Get",
"the",
"system",
"hostname",
"to",
"be",
"sent",
"to",
"the",
"SMTP",
"server",
".",
"Simply",
"caches",
"the",
"result",
"of",
":",
"func",
":",
"socket",
".",
"getfqdn",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L134-L142 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection.connect | async def connect(
self,
hostname: str = None,
port: int = None,
source_address: DefaultStrType = _default,
timeout: DefaultNumType = _default,
loop: asyncio.AbstractEventLoop = None,
use_tls: bool = None,
validate_certs: bool = None,
client_cert: DefaultStrType = _default,
client_key: DefaultStrType = _default,
tls_context: DefaultSSLContextType = _default,
cert_bundle: DefaultStrType = _default,
) -> SMTPResponse:
"""
Initialize a connection to the server. Options provided to
:meth:`.connect` take precedence over those used to initialize the
class.
:keyword hostname: Server name (or IP) to connect to
:keyword port: Server port. Defaults to 25 if ``use_tls`` is
False, 465 if ``use_tls`` is True.
:keyword source_address: The hostname of the client. Defaults to the
result of :func:`socket.getfqdn`. Note that this call blocks.
:keyword timeout: Default timeout value for the connection, in seconds.
Defaults to 60.
:keyword loop: event loop to run on. If not set, uses
:func:`asyncio.get_event_loop()`.
:keyword use_tls: If True, make the initial connection to the server
over TLS/SSL. Note that if the server supports STARTTLS only, this
should be False.
:keyword validate_certs: Determines if server certificates are
validated. Defaults to True.
:keyword client_cert: Path to client side certificate, for TLS.
:keyword client_key: Path to client side key, for TLS.
:keyword tls_context: An existing :class:`ssl.SSLContext`, for TLS.
Mutually exclusive with ``client_cert``/``client_key``.
:keyword cert_bundle: Path to certificate bundle, for TLS verification.
:raises ValueError: mutually exclusive options provided
"""
await self._connect_lock.acquire()
if hostname is not None:
self.hostname = hostname
if loop is not None:
self.loop = loop
if use_tls is not None:
self.use_tls = use_tls
if validate_certs is not None:
self.validate_certs = validate_certs
if port is not None:
self.port = port
if self.port is None:
self.port = SMTP_TLS_PORT if self.use_tls else SMTP_PORT
if timeout is not _default:
self.timeout = timeout # type: ignore
if source_address is not _default:
self._source_address = source_address # type: ignore
if client_cert is not _default:
self.client_cert = client_cert # type: ignore
if client_key is not _default:
self.client_key = client_key # type: ignore
if tls_context is not _default:
self.tls_context = tls_context # type: ignore
if cert_bundle is not _default:
self.cert_bundle = cert_bundle # type: ignore
if self.tls_context is not None and self.client_cert is not None:
raise ValueError(
"Either a TLS context or a certificate/key must be provided"
)
response = await self._create_connection()
return response | python | async def connect(
self,
hostname: str = None,
port: int = None,
source_address: DefaultStrType = _default,
timeout: DefaultNumType = _default,
loop: asyncio.AbstractEventLoop = None,
use_tls: bool = None,
validate_certs: bool = None,
client_cert: DefaultStrType = _default,
client_key: DefaultStrType = _default,
tls_context: DefaultSSLContextType = _default,
cert_bundle: DefaultStrType = _default,
) -> SMTPResponse:
await self._connect_lock.acquire()
if hostname is not None:
self.hostname = hostname
if loop is not None:
self.loop = loop
if use_tls is not None:
self.use_tls = use_tls
if validate_certs is not None:
self.validate_certs = validate_certs
if port is not None:
self.port = port
if self.port is None:
self.port = SMTP_TLS_PORT if self.use_tls else SMTP_PORT
if timeout is not _default:
self.timeout = timeout
if source_address is not _default:
self._source_address = source_address
if client_cert is not _default:
self.client_cert = client_cert
if client_key is not _default:
self.client_key = client_key
if tls_context is not _default:
self.tls_context = tls_context
if cert_bundle is not _default:
self.cert_bundle = cert_bundle
if self.tls_context is not None and self.client_cert is not None:
raise ValueError(
"Either a TLS context or a certificate/key must be provided"
)
response = await self._create_connection()
return response | [
"async",
"def",
"connect",
"(",
"self",
",",
"hostname",
":",
"str",
"=",
"None",
",",
"port",
":",
"int",
"=",
"None",
",",
"source_address",
":",
"DefaultStrType",
"=",
"_default",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
"=",
"None",
",",
"use_tls",
":",
"bool",
"=",
"None",
",",
"validate_certs",
":",
"bool",
"=",
"None",
",",
"client_cert",
":",
"DefaultStrType",
"=",
"_default",
",",
"client_key",
":",
"DefaultStrType",
"=",
"_default",
",",
"tls_context",
":",
"DefaultSSLContextType",
"=",
"_default",
",",
"cert_bundle",
":",
"DefaultStrType",
"=",
"_default",
",",
")",
"->",
"SMTPResponse",
":",
"await",
"self",
".",
"_connect_lock",
".",
"acquire",
"(",
")",
"if",
"hostname",
"is",
"not",
"None",
":",
"self",
".",
"hostname",
"=",
"hostname",
"if",
"loop",
"is",
"not",
"None",
":",
"self",
".",
"loop",
"=",
"loop",
"if",
"use_tls",
"is",
"not",
"None",
":",
"self",
".",
"use_tls",
"=",
"use_tls",
"if",
"validate_certs",
"is",
"not",
"None",
":",
"self",
".",
"validate_certs",
"=",
"validate_certs",
"if",
"port",
"is",
"not",
"None",
":",
"self",
".",
"port",
"=",
"port",
"if",
"self",
".",
"port",
"is",
"None",
":",
"self",
".",
"port",
"=",
"SMTP_TLS_PORT",
"if",
"self",
".",
"use_tls",
"else",
"SMTP_PORT",
"if",
"timeout",
"is",
"not",
"_default",
":",
"self",
".",
"timeout",
"=",
"timeout",
"# type: ignore",
"if",
"source_address",
"is",
"not",
"_default",
":",
"self",
".",
"_source_address",
"=",
"source_address",
"# type: ignore",
"if",
"client_cert",
"is",
"not",
"_default",
":",
"self",
".",
"client_cert",
"=",
"client_cert",
"# type: ignore",
"if",
"client_key",
"is",
"not",
"_default",
":",
"self",
".",
"client_key",
"=",
"client_key",
"# type: ignore",
"if",
"tls_context",
"is",
"not",
"_default",
":",
"self",
".",
"tls_context",
"=",
"tls_context",
"# type: ignore",
"if",
"cert_bundle",
"is",
"not",
"_default",
":",
"self",
".",
"cert_bundle",
"=",
"cert_bundle",
"# type: ignore",
"if",
"self",
".",
"tls_context",
"is",
"not",
"None",
"and",
"self",
".",
"client_cert",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Either a TLS context or a certificate/key must be provided\"",
")",
"response",
"=",
"await",
"self",
".",
"_create_connection",
"(",
")",
"return",
"response"
]
| Initialize a connection to the server. Options provided to
:meth:`.connect` take precedence over those used to initialize the
class.
:keyword hostname: Server name (or IP) to connect to
:keyword port: Server port. Defaults to 25 if ``use_tls`` is
False, 465 if ``use_tls`` is True.
:keyword source_address: The hostname of the client. Defaults to the
result of :func:`socket.getfqdn`. Note that this call blocks.
:keyword timeout: Default timeout value for the connection, in seconds.
Defaults to 60.
:keyword loop: event loop to run on. If not set, uses
:func:`asyncio.get_event_loop()`.
:keyword use_tls: If True, make the initial connection to the server
over TLS/SSL. Note that if the server supports STARTTLS only, this
should be False.
:keyword validate_certs: Determines if server certificates are
validated. Defaults to True.
:keyword client_cert: Path to client side certificate, for TLS.
:keyword client_key: Path to client side key, for TLS.
:keyword tls_context: An existing :class:`ssl.SSLContext`, for TLS.
Mutually exclusive with ``client_cert``/``client_key``.
:keyword cert_bundle: Path to certificate bundle, for TLS verification.
:raises ValueError: mutually exclusive options provided | [
"Initialize",
"a",
"connection",
"to",
"the",
"server",
".",
"Options",
"provided",
"to",
":",
"meth",
":",
".",
"connect",
"take",
"precedence",
"over",
"those",
"used",
"to",
"initialize",
"the",
"class",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L144-L222 |
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:
if timeout is _default:
timeout = self.timeout
self._raise_error_if_disconnected()
try:
response = await self.protocol.execute_command(
*args, timeout=timeout
)
except SMTPServerDisconnected:
self.close()
raise
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L274-L301 |
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:
if self.tls_context is not None:
context = self.tls_context
else:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L306-L327 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L329-L340 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection.close | def close(self) -> None:
"""
Closes the connection.
"""
if self.transport is not None and not self.transport.is_closing():
self.transport.close()
if self._connect_lock.locked():
self._connect_lock.release()
self.protocol = None
self.transport = None | python | def close(self) -> None:
if self.transport is not None and not self.transport.is_closing():
self.transport.close()
if self._connect_lock.locked():
self._connect_lock.release()
self.protocol = None
self.transport = None | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"transport",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"transport",
".",
"is_closing",
"(",
")",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"if",
"self",
".",
"_connect_lock",
".",
"locked",
"(",
")",
":",
"self",
".",
"_connect_lock",
".",
"release",
"(",
")",
"self",
".",
"protocol",
"=",
"None",
"self",
".",
"transport",
"=",
"None"
]
| Closes the connection. | [
"Closes",
"the",
"connection",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L342-L353 |
cole/aiosmtplib | src/aiosmtplib/connection.py | SMTPConnection.get_transport_info | def get_transport_info(self, key: str) -> Any:
"""
Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
- ``sslobject``
:raises SMTPServerDisconnected: connection lost
"""
self._raise_error_if_disconnected()
return self.transport.get_extra_info(key) | python | def get_transport_info(self, key: str) -> Any:
self._raise_error_if_disconnected()
return self.transport.get_extra_info(key) | [
"def",
"get_transport_info",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"Any",
":",
"self",
".",
"_raise_error_if_disconnected",
"(",
")",
"return",
"self",
".",
"transport",
".",
"get_extra_info",
"(",
"key",
")"
]
| Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
- ``sslobject``
:raises SMTPServerDisconnected: connection lost | [
"Get",
"extra",
"info",
"from",
"the",
"transport",
".",
"Supported",
"keys",
":"
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/connection.py#L355-L373 |
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 = ["[email protected]", "[email protected]", "[email protected]"]
>>> message = "From: [email protected]\\nSubject: testing\\nHello World"
>>> send_coro = smtp.sendmail("[email protected]", 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::
(
{"[email protected]": (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:
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:
try:
await self.rset(timeout=timeout)
except (ConnectionError, SMTPResponseException):
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 = ["[email protected]", "[email protected]", "[email protected]"]
>>> message = "From: [email protected]\\nSubject: testing\\nHello World"
>>> send_coro = smtp.sendmail("[email protected]", 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::
(
{"[email protected]": (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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L57-L166 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP._send_recipients | async def _send_recipients(
self,
recipients: List[str],
options: List[str] = None,
timeout: DefaultNumType = _default,
) -> RecipientErrorsType:
"""
Send the recipients given to the server. Used as part of
:meth:`.sendmail`.
"""
recipient_errors = []
for address in recipients:
try:
await self.rcpt(address, timeout=timeout)
except SMTPRecipientRefused as exc:
recipient_errors.append(exc)
if len(recipient_errors) == len(recipients):
raise SMTPRecipientsRefused(recipient_errors)
formatted_errors = {
err.recipient: SMTPResponse(err.code, err.message)
for err in recipient_errors
}
return formatted_errors | python | async def _send_recipients(
self,
recipients: List[str],
options: List[str] = None,
timeout: DefaultNumType = _default,
) -> RecipientErrorsType:
recipient_errors = []
for address in recipients:
try:
await self.rcpt(address, timeout=timeout)
except SMTPRecipientRefused as exc:
recipient_errors.append(exc)
if len(recipient_errors) == len(recipients):
raise SMTPRecipientsRefused(recipient_errors)
formatted_errors = {
err.recipient: SMTPResponse(err.code, err.message)
for err in recipient_errors
}
return formatted_errors | [
"async",
"def",
"_send_recipients",
"(",
"self",
",",
"recipients",
":",
"List",
"[",
"str",
"]",
",",
"options",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"RecipientErrorsType",
":",
"recipient_errors",
"=",
"[",
"]",
"for",
"address",
"in",
"recipients",
":",
"try",
":",
"await",
"self",
".",
"rcpt",
"(",
"address",
",",
"timeout",
"=",
"timeout",
")",
"except",
"SMTPRecipientRefused",
"as",
"exc",
":",
"recipient_errors",
".",
"append",
"(",
"exc",
")",
"if",
"len",
"(",
"recipient_errors",
")",
"==",
"len",
"(",
"recipients",
")",
":",
"raise",
"SMTPRecipientsRefused",
"(",
"recipient_errors",
")",
"formatted_errors",
"=",
"{",
"err",
".",
"recipient",
":",
"SMTPResponse",
"(",
"err",
".",
"code",
",",
"err",
".",
"message",
")",
"for",
"err",
"in",
"recipient_errors",
"}",
"return",
"formatted_errors"
]
| Send the recipients given to the server. Used as part of
:meth:`.sendmail`. | [
"Send",
"the",
"recipients",
"given",
"to",
"the",
"server",
".",
"Used",
"as",
"part",
"of",
":",
"meth",
":",
".",
"sendmail",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L168-L193 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP.send_message | async def send_message(
self,
message: Message,
sender: str = None,
recipients: RecipientsType = None,
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
r"""
Sends an :class:`email.message.Message` object.
Arguments are as for :meth:`.sendmail`, except that message is an
:class:`email.message.Message` object. If sender is None or recipients
is None, these arguments are taken from the headers of the Message as
described in RFC 2822. Regardless of the values of sender and
recipients, any Bcc field (or Resent-Bcc field, when the Message is a
resent) of the Message object will not be transmitted. The Message
object is then serialized using :class:`email.generator.Generator` and
:meth:`.sendmail` is called to transmit the message.
'Resent-Date' is a mandatory field if the Message is resent (RFC 2822
Section 3.6.6). In such a case, we use the 'Resent-\*' fields.
However, if there is more than one 'Resent-' block there's no way to
unambiguously determine which one is the most recent in all cases,
so rather than guess we raise a ``ValueError`` in that case.
:raises ValueError: on more than one Resent header block
:raises SMTPRecipientsRefused: delivery to all recipients failed
:raises SMTPResponseException: on invalid response
"""
header_sender, header_recipients, flat_message = flatten_message(message)
if sender is None:
sender = header_sender
if recipients is None:
recipients = header_recipients
result = await self.sendmail(sender, recipients, flat_message, timeout=timeout)
return result | python | async def send_message(
self,
message: Message,
sender: str = None,
recipients: RecipientsType = None,
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
r
header_sender, header_recipients, flat_message = flatten_message(message)
if sender is None:
sender = header_sender
if recipients is None:
recipients = header_recipients
result = await self.sendmail(sender, recipients, flat_message, timeout=timeout)
return result | [
"async",
"def",
"send_message",
"(",
"self",
",",
"message",
":",
"Message",
",",
"sender",
":",
"str",
"=",
"None",
",",
"recipients",
":",
"RecipientsType",
"=",
"None",
",",
"mail_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"rcpt_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SendmailResponseType",
":",
"header_sender",
",",
"header_recipients",
",",
"flat_message",
"=",
"flatten_message",
"(",
"message",
")",
"if",
"sender",
"is",
"None",
":",
"sender",
"=",
"header_sender",
"if",
"recipients",
"is",
"None",
":",
"recipients",
"=",
"header_recipients",
"result",
"=",
"await",
"self",
".",
"sendmail",
"(",
"sender",
",",
"recipients",
",",
"flat_message",
",",
"timeout",
"=",
"timeout",
")",
"return",
"result"
]
| r"""
Sends an :class:`email.message.Message` object.
Arguments are as for :meth:`.sendmail`, except that message is an
:class:`email.message.Message` object. If sender is None or recipients
is None, these arguments are taken from the headers of the Message as
described in RFC 2822. Regardless of the values of sender and
recipients, any Bcc field (or Resent-Bcc field, when the Message is a
resent) of the Message object will not be transmitted. The Message
object is then serialized using :class:`email.generator.Generator` and
:meth:`.sendmail` is called to transmit the message.
'Resent-Date' is a mandatory field if the Message is resent (RFC 2822
Section 3.6.6). In such a case, we use the 'Resent-\*' fields.
However, if there is more than one 'Resent-' block there's no way to
unambiguously determine which one is the most recent in all cases,
so rather than guess we raise a ``ValueError`` in that case.
:raises ValueError: on more than one Resent header block
:raises SMTPRecipientsRefused: delivery to all recipients failed
:raises SMTPResponseException: on invalid response | [
"r",
"Sends",
"an",
":",
"class",
":",
"email",
".",
"message",
".",
"Message",
"object",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L195-L235 |
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:
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",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L237-L252 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP.sendmail_sync | def sendmail_sync(
self,
sender: str,
recipients: RecipientsType,
message: Union[str, bytes],
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
"""
Synchronous version of :meth:`.sendmail`. This method starts
the event loop to connect, send the message, and disconnect.
"""
return self._run_sync(
self.sendmail,
sender,
recipients,
message,
mail_options=mail_options,
rcpt_options=rcpt_options,
timeout=timeout,
) | python | def sendmail_sync(
self,
sender: str,
recipients: RecipientsType,
message: Union[str, bytes],
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
return self._run_sync(
self.sendmail,
sender,
recipients,
message,
mail_options=mail_options,
rcpt_options=rcpt_options,
timeout=timeout,
) | [
"def",
"sendmail_sync",
"(",
"self",
",",
"sender",
":",
"str",
",",
"recipients",
":",
"RecipientsType",
",",
"message",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"mail_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"rcpt_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SendmailResponseType",
":",
"return",
"self",
".",
"_run_sync",
"(",
"self",
".",
"sendmail",
",",
"sender",
",",
"recipients",
",",
"message",
",",
"mail_options",
"=",
"mail_options",
",",
"rcpt_options",
"=",
"rcpt_options",
",",
"timeout",
"=",
"timeout",
",",
")"
]
| Synchronous version of :meth:`.sendmail`. This method starts
the event loop to connect, send the message, and disconnect. | [
"Synchronous",
"version",
"of",
":",
"meth",
":",
".",
"sendmail",
".",
"This",
"method",
"starts",
"the",
"event",
"loop",
"to",
"connect",
"send",
"the",
"message",
"and",
"disconnect",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L254-L275 |
cole/aiosmtplib | src/aiosmtplib/smtp.py | SMTP.send_message_sync | def send_message_sync(
self,
message: Message,
sender: str = None,
recipients: RecipientsType = None,
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
"""
Synchronous version of :meth:`.send_message`. This method
starts the event loop to connect, send the message, and disconnect.
"""
return self._run_sync(
self.send_message,
message,
sender=sender,
recipients=recipients,
mail_options=mail_options,
rcpt_options=rcpt_options,
timeout=timeout,
) | python | def send_message_sync(
self,
message: Message,
sender: str = None,
recipients: RecipientsType = None,
mail_options: Iterable[str] = None,
rcpt_options: Iterable[str] = None,
timeout: DefaultNumType = _default,
) -> SendmailResponseType:
return self._run_sync(
self.send_message,
message,
sender=sender,
recipients=recipients,
mail_options=mail_options,
rcpt_options=rcpt_options,
timeout=timeout,
) | [
"def",
"send_message_sync",
"(",
"self",
",",
"message",
":",
"Message",
",",
"sender",
":",
"str",
"=",
"None",
",",
"recipients",
":",
"RecipientsType",
"=",
"None",
",",
"mail_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"rcpt_options",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
",",
")",
"->",
"SendmailResponseType",
":",
"return",
"self",
".",
"_run_sync",
"(",
"self",
".",
"send_message",
",",
"message",
",",
"sender",
"=",
"sender",
",",
"recipients",
"=",
"recipients",
",",
"mail_options",
"=",
"mail_options",
",",
"rcpt_options",
"=",
"rcpt_options",
",",
"timeout",
"=",
"timeout",
",",
")"
]
| Synchronous version of :meth:`.send_message`. This method
starts the event loop to connect, send the message, and disconnect. | [
"Synchronous",
"version",
"of",
":",
"meth",
":",
".",
"send_message",
".",
"This",
"method",
"starts",
"the",
"event",
"loop",
"to",
"connect",
"send",
"the",
"message",
"and",
"disconnect",
"."
]
| train | https://github.com/cole/aiosmtplib/blob/0cd00e5059005371cbdfca995feff9183a16a51f/src/aiosmtplib/smtp.py#L277-L298 |
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():
res = requests.get("https://cs50.me/status/submit50")
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",
"."
]
| train | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L28-L32 |
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 [email protected]!"))
# Check that latest version == version installed
required_required = pkg_resources.parse_version(res.text.strip()) | python | def check_version():
res = requests.get("https://cs50.me/versions/submit50")
if res.status_code != 200:
raise Error(_("You have an unknown version of submit50. "
"Email [email protected]!"))
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 [email protected]!\"",
")",
")",
"# 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",
"."
]
| train | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L35-L44 |
cs50/submit50 | submit50/__main__.py | cprint | def cprint(text="", color=None, on_color=None, attrs=None, **kwargs):
"""Colorizes text (and wraps to terminal's width)."""
# Assume 80 in case not running in a terminal
columns, lines = shutil.get_terminal_size()
if columns == 0:
columns = 80 # Because get_terminal_size's default fallback doesn't work in pipes
# Print text
termcolor.cprint(textwrap.fill(text, columns, drop_whitespace=False),
color=color, on_color=on_color, attrs=attrs, **kwargs) | python | def cprint(text="", color=None, on_color=None, attrs=None, **kwargs):
columns, lines = shutil.get_terminal_size()
if columns == 0:
columns = 80
termcolor.cprint(textwrap.fill(text, columns, drop_whitespace=False),
color=color, on_color=on_color, attrs=attrs, **kwargs) | [
"def",
"cprint",
"(",
"text",
"=",
"\"\"",
",",
"color",
"=",
"None",
",",
"on_color",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Assume 80 in case not running in a terminal",
"columns",
",",
"lines",
"=",
"shutil",
".",
"get_terminal_size",
"(",
")",
"if",
"columns",
"==",
"0",
":",
"columns",
"=",
"80",
"# Because get_terminal_size's default fallback doesn't work in pipes",
"# Print text",
"termcolor",
".",
"cprint",
"(",
"textwrap",
".",
"fill",
"(",
"text",
",",
"columns",
",",
"drop_whitespace",
"=",
"False",
")",
",",
"color",
"=",
"color",
",",
"on_color",
"=",
"on_color",
",",
"attrs",
"=",
"attrs",
",",
"*",
"*",
"kwargs",
")"
]
| Colorizes text (and wraps to terminal's width). | [
"Colorizes",
"text",
"(",
"and",
"wraps",
"to",
"terminal",
"s",
"width",
")",
"."
]
| train | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L53-L62 |
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 [email protected] know!"), "yellow")
if excepthook.verbose:
traceback.print_exception(type, value, tb)
cprint(_("Submission cancelled."), "red") | python | 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 [email protected] 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 [email protected] know!\"",
")",
",",
"\"yellow\"",
")",
"if",
"excepthook",
".",
"verbose",
":",
"traceback",
".",
"print_exception",
"(",
"type",
",",
"value",
",",
"tb",
")",
"cprint",
"(",
"_",
"(",
"\"Submission cancelled.\"",
")",
",",
"\"red\"",
")"
]
| Report an exception. | [
"Report",
"an",
"exception",
"."
]
| train | https://github.com/cs50/submit50/blob/5f4c8b3675e8e261c8422f76eacd6a6330c23831/submit50/__main__.py#L93-L104 |
kedder/ofxstatement | src/ofxstatement/plugin.py | list_plugins | def list_plugins():
"""Return list of all plugin classes registered as a list of tuples:
[(name, plugin_class)]
"""
plugin_eps = pkg_resources.iter_entry_points('ofxstatement')
return sorted((ep.name, ep.load()) for ep in plugin_eps) | python | def list_plugins():
plugin_eps = pkg_resources.iter_entry_points('ofxstatement')
return sorted((ep.name, ep.load()) for ep in plugin_eps) | [
"def",
"list_plugins",
"(",
")",
":",
"plugin_eps",
"=",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'ofxstatement'",
")",
"return",
"sorted",
"(",
"(",
"ep",
".",
"name",
",",
"ep",
".",
"load",
"(",
")",
")",
"for",
"ep",
"in",
"plugin_eps",
")"
]
| Return list of all plugin classes registered as a list of tuples:
[(name, plugin_class)] | [
"Return",
"list",
"of",
"all",
"plugin",
"classes",
"registered",
"as",
"a",
"list",
"of",
"tuples",
":"
]
| train | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/plugin.py#L20-L26 |
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):
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",
"."
]
| train | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L155-L163 |
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):
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",
"."
]
| train | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L166-L180 |
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):
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"
]
| train | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/statement.py#L113-L120 |
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):
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"
]
| train | https://github.com/kedder/ofxstatement/blob/61f9dc1cfe6024874b859c8aec108b9d9acee57a/src/ofxstatement/parser.py#L17-L33 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L53-L63 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L65-L75 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L77-L83 |
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
):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L85-L113 |
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,
):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L115-L141 |
discogs/python-cas-client | cas_client/cas_client.py | CASClient.get_destroy_other_sessions_url | def get_destroy_other_sessions_url(self, service_url=None):
'''
Get the URL for a remote CAS `destroy-other-sessions` endpoint.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> service_url = 'http://myservice.net'
>>> client.get_destroy_other_sessions_url(service_url)
'https://logmein.com/cas/destroy-other-sessions?service=http://myservice.net'
'''
template = '{server_url}{auth_prefix}/destroy-other-sessions?service={service_url}'
url = template.format(
server_url=self.server_url,
auth_prefix=self.auth_prefix,
service_url=service_url or self.service_url,
)
logging.debug('[CAS] Destroy Sessions URL: {}'.format(url))
return url | python | def get_destroy_other_sessions_url(self, service_url=None):
template = '{server_url}{auth_prefix}/destroy-other-sessions?service={service_url}'
url = template.format(
server_url=self.server_url,
auth_prefix=self.auth_prefix,
service_url=service_url or self.service_url,
)
logging.debug('[CAS] Destroy Sessions URL: {}'.format(url))
return url | [
"def",
"get_destroy_other_sessions_url",
"(",
"self",
",",
"service_url",
"=",
"None",
")",
":",
"template",
"=",
"'{server_url}{auth_prefix}/destroy-other-sessions?service={service_url}'",
"url",
"=",
"template",
".",
"format",
"(",
"server_url",
"=",
"self",
".",
"server_url",
",",
"auth_prefix",
"=",
"self",
".",
"auth_prefix",
",",
"service_url",
"=",
"service_url",
"or",
"self",
".",
"service_url",
",",
")",
"logging",
".",
"debug",
"(",
"'[CAS] Destroy Sessions URL: {}'",
".",
"format",
"(",
"url",
")",
")",
"return",
"url"
]
| Get the URL for a remote CAS `destroy-other-sessions` endpoint.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> service_url = 'http://myservice.net'
>>> client.get_destroy_other_sessions_url(service_url)
'https://logmein.com/cas/destroy-other-sessions?service=http://myservice.net' | [
"Get",
"the",
"URL",
"for",
"a",
"remote",
"CAS",
"destroy",
"-",
"other",
"-",
"sessions",
"endpoint",
".",
"::"
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L143-L163 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L209-L254 |
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
):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L256-L272 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L274-L284 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L286-L296 |
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,
):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L298-L309 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L311-L318 |
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):
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",
"."
]
| train | https://github.com/discogs/python-cas-client/blob/f1efa2f49a22d43135014cb1b8d9dd3875304318/cas_client/cas_client.py#L612-L618 |
CZ-NIC/python-rt | rt.py | Rt.__request | def __request(self, selector, get_params={}, post_data={}, files=[], without_login=False,
text_response=True):
""" General request for :term:`API`.
:keyword selector: End part of URL which completes self.url parameter
set during class initialization.
E.g.: ``ticket/123456/show``
:keyword post_data: Dictionary with POST method fields
:keyword files: List of pairs (filename, file-like object) describing
files to attach as multipart/form-data
(list is necessary to keep files ordered)
:keyword without_login: Turns off checking last login result
(usually needed just for login itself)
:keyword text_response: If set to false the received message will be
returned without decoding (useful for attachments)
:returns: Requested messsage including state line in form
``RT/3.8.7 200 Ok\\n``
:rtype: string or bytes if text_response is False
:raises AuthorizationError: In case that request is called without previous
login or login attempt failed.
:raises ConnectionError: In case of connection error.
"""
try:
if (not self.login_result) and (not without_login):
raise AuthorizationError('First login by calling method `login`.')
url = str(urljoin(self.url, selector))
if not files:
if post_data:
response = self.session.post(url, data=post_data)
else:
response = self.session.get(url, params=get_params)
else:
files_data = {}
for i, file_pair in enumerate(files):
files_data['attachment_{:d}'.format(i + 1)] = file_pair
response = self.session.post(url, data=post_data, files=files_data)
if self.debug_mode or DEBUG_MODE:
method = "GET"
if post_data or files:
method = "POST"
print("### {0}".format(datetime.datetime.now().isoformat()))
print("Request URL: {0}".format(url))
print("Request method: {0}".format(method))
print("Respone status code: {0}".format(response.status_code))
print("Response content:")
print(response.content.decode())
if response.status_code == 401:
raise AuthorizationError('Server could not verify that you are authorized to access the requested document.')
if response.status_code != 200:
raise UnexpectedResponse('Received status code {:d} instead of 200.'.format(response.status_code))
try:
if response.encoding:
result = response.content.decode(response.encoding.lower())
else:
# try utf-8 if encoding is not filled
result = response.content.decode('utf-8')
except LookupError:
raise UnexpectedResponse('Unknown response encoding: {}.'.format(response.encoding))
except UnicodeError:
if text_response:
raise UnexpectedResponse('Unknown response encoding (UTF-8 does not work).')
else:
# replace errors - we need decoded content just to check for error codes in __check_response
result = response.content.decode('utf-8', 'replace')
self.__check_response(result)
if not text_response:
return response.content
return result
except requests.exceptions.ConnectionError as e:
raise ConnectionError("Connection error", e) | python | def __request(self, selector, get_params={}, post_data={}, files=[], without_login=False,
text_response=True):
try:
if (not self.login_result) and (not without_login):
raise AuthorizationError('First login by calling method `login`.')
url = str(urljoin(self.url, selector))
if not files:
if post_data:
response = self.session.post(url, data=post_data)
else:
response = self.session.get(url, params=get_params)
else:
files_data = {}
for i, file_pair in enumerate(files):
files_data['attachment_{:d}'.format(i + 1)] = file_pair
response = self.session.post(url, data=post_data, files=files_data)
if self.debug_mode or DEBUG_MODE:
method = "GET"
if post_data or files:
method = "POST"
print("
print("Request URL: {0}".format(url))
print("Request method: {0}".format(method))
print("Respone status code: {0}".format(response.status_code))
print("Response content:")
print(response.content.decode())
if response.status_code == 401:
raise AuthorizationError('Server could not verify that you are authorized to access the requested document.')
if response.status_code != 200:
raise UnexpectedResponse('Received status code {:d} instead of 200.'.format(response.status_code))
try:
if response.encoding:
result = response.content.decode(response.encoding.lower())
else:
result = response.content.decode('utf-8')
except LookupError:
raise UnexpectedResponse('Unknown response encoding: {}.'.format(response.encoding))
except UnicodeError:
if text_response:
raise UnexpectedResponse('Unknown response encoding (UTF-8 does not work).')
else:
result = response.content.decode('utf-8', 'replace')
self.__check_response(result)
if not text_response:
return response.content
return result
except requests.exceptions.ConnectionError as e:
raise ConnectionError("Connection error", e) | [
"def",
"__request",
"(",
"self",
",",
"selector",
",",
"get_params",
"=",
"{",
"}",
",",
"post_data",
"=",
"{",
"}",
",",
"files",
"=",
"[",
"]",
",",
"without_login",
"=",
"False",
",",
"text_response",
"=",
"True",
")",
":",
"try",
":",
"if",
"(",
"not",
"self",
".",
"login_result",
")",
"and",
"(",
"not",
"without_login",
")",
":",
"raise",
"AuthorizationError",
"(",
"'First login by calling method `login`.'",
")",
"url",
"=",
"str",
"(",
"urljoin",
"(",
"self",
".",
"url",
",",
"selector",
")",
")",
"if",
"not",
"files",
":",
"if",
"post_data",
":",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"post_data",
")",
"else",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"params",
"=",
"get_params",
")",
"else",
":",
"files_data",
"=",
"{",
"}",
"for",
"i",
",",
"file_pair",
"in",
"enumerate",
"(",
"files",
")",
":",
"files_data",
"[",
"'attachment_{:d}'",
".",
"format",
"(",
"i",
"+",
"1",
")",
"]",
"=",
"file_pair",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"post_data",
",",
"files",
"=",
"files_data",
")",
"if",
"self",
".",
"debug_mode",
"or",
"DEBUG_MODE",
":",
"method",
"=",
"\"GET\"",
"if",
"post_data",
"or",
"files",
":",
"method",
"=",
"\"POST\"",
"print",
"(",
"\"### {0}\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"isoformat",
"(",
")",
")",
")",
"print",
"(",
"\"Request URL: {0}\"",
".",
"format",
"(",
"url",
")",
")",
"print",
"(",
"\"Request method: {0}\"",
".",
"format",
"(",
"method",
")",
")",
"print",
"(",
"\"Respone status code: {0}\"",
".",
"format",
"(",
"response",
".",
"status_code",
")",
")",
"print",
"(",
"\"Response content:\"",
")",
"print",
"(",
"response",
".",
"content",
".",
"decode",
"(",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"raise",
"AuthorizationError",
"(",
"'Server could not verify that you are authorized to access the requested document.'",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"UnexpectedResponse",
"(",
"'Received status code {:d} instead of 200.'",
".",
"format",
"(",
"response",
".",
"status_code",
")",
")",
"try",
":",
"if",
"response",
".",
"encoding",
":",
"result",
"=",
"response",
".",
"content",
".",
"decode",
"(",
"response",
".",
"encoding",
".",
"lower",
"(",
")",
")",
"else",
":",
"# try utf-8 if encoding is not filled",
"result",
"=",
"response",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"LookupError",
":",
"raise",
"UnexpectedResponse",
"(",
"'Unknown response encoding: {}.'",
".",
"format",
"(",
"response",
".",
"encoding",
")",
")",
"except",
"UnicodeError",
":",
"if",
"text_response",
":",
"raise",
"UnexpectedResponse",
"(",
"'Unknown response encoding (UTF-8 does not work).'",
")",
"else",
":",
"# replace errors - we need decoded content just to check for error codes in __check_response",
"result",
"=",
"response",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"self",
".",
"__check_response",
"(",
"result",
")",
"if",
"not",
"text_response",
":",
"return",
"response",
".",
"content",
"return",
"result",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"raise",
"ConnectionError",
"(",
"\"Connection error\"",
",",
"e",
")"
]
| General request for :term:`API`.
:keyword selector: End part of URL which completes self.url parameter
set during class initialization.
E.g.: ``ticket/123456/show``
:keyword post_data: Dictionary with POST method fields
:keyword files: List of pairs (filename, file-like object) describing
files to attach as multipart/form-data
(list is necessary to keep files ordered)
:keyword without_login: Turns off checking last login result
(usually needed just for login itself)
:keyword text_response: If set to false the received message will be
returned without decoding (useful for attachments)
:returns: Requested messsage including state line in form
``RT/3.8.7 200 Ok\\n``
:rtype: string or bytes if text_response is False
:raises AuthorizationError: In case that request is called without previous
login or login attempt failed.
:raises ConnectionError: In case of connection error. | [
"General",
"request",
"for",
":",
"term",
":",
"API",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L229-L299 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L313-L331 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L333-L337 |
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):
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:
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L339-L380 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L382-L394 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L396-L406 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L408-L419 |
CZ-NIC/python-rt | rt.py | Rt.search | def search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs):
""" Search arbitrary needles in given fields and queue.
Example::
>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')
>>> tracker.login()
>>> tickets = tracker.search(CF_Domain='example.com', Subject__like='warning')
>>> tickets = tracker.search(Queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")
:keyword Queue: Queue where to search. If you wish to search across
all of your queues, pass the ALL_QUEUES object as the
argument.
:keyword order: Name of field sorting result list, for descending
order put - before the field name. E.g. -Created
will put the newest tickets at the beginning
:keyword raw_query: A raw query to provide to RT if you know what
you are doing. You may still pass Queue and order
kwargs, so use these instead of including them in
the raw query. You can refer to the RT query builder.
If passing raw_query, all other **kwargs will be ignored.
:keyword Format: Format of the query:
- i: only `id' fields are populated
- s: only `id' and `subject' fields are populated
- l: multi-line format, all fields are populated
:keyword kwargs: Other arguments possible to set if not passing raw_query:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
To alter lookup operators you can append one of the
following endings to each keyword:
__exact for operator = (default)
__notexact for operator !=
__gt for operator >
__lt for operator <
__like for operator LIKE
__notlike for operator NOT LIKE
Setting values to keywords constrain search
result to the tickets satisfying all of them.
:returns: List of matching tickets. Each ticket is the same dictionary
as in :py:meth:`~Rt.get_ticket`.
:raises: UnexpectedMessageFormat: Unexpected format of returned message.
InvalidQueryError: If raw query is malformed
"""
get_params = {}
query = []
url = 'search/ticket'
if Queue is not ALL_QUEUES:
query.append("Queue=\'{}\'".format(Queue or self.default_queue))
if not raw_query:
operators_map = {
'gt': '>',
'lt': '<',
'exact': '=',
'notexact': '!=',
'like': ' LIKE ',
'notlike': ' NOT LIKE '
}
for key, value in iteritems(kwargs):
op = '='
key_parts = key.split('__')
if len(key_parts) > 1:
key = '__'.join(key_parts[:-1])
op = operators_map.get(key_parts[-1], '=')
if key[:3] != 'CF_':
query.append("{}{}\'{}\'".format(key, op, value))
else:
query.append("'CF.{{{}}}'{}\'{}\'".format(key[3:], op, value))
else:
query.append(raw_query)
get_params['query'] = ' AND '.join('(' + part + ')' for part in query)
if order:
get_params['orderby'] = order
get_params['format'] = Format
msg = self.__request(url, get_params=get_params)
lines = msg.split('\n')
if len(lines) > 2:
if self.__get_status_code(lines[0]) != 200 and lines[2].startswith('Invalid query: '):
raise InvalidQueryError(lines[2])
if lines[2].startswith('No matching results.'):
return []
if Format == 'l':
msgs = map(lambda x: x.split('\n'), msg.split('\n--\n'))
items = []
for msg in msgs:
pairs = {}
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 pairs:
items.append(pairs)
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 items
elif Format == 's':
items = []
msgs = lines[2:]
for msg in msgs:
if "" == msg: # Ignore blank line at the end
continue
ticket_id, subject = self.split_header(msg)
items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id, 'Subject': subject})
return items
elif Format == 'i':
items = []
msgs = lines[2:]
for msg in msgs:
if "" == msg: # Ignore blank line at the end
continue
_, ticket_id = msg.split('/', 1)
items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id})
return items | python | def search(self, Queue=None, order=None, raw_query=None, Format='l', **kwargs):
get_params = {}
query = []
url = 'search/ticket'
if Queue is not ALL_QUEUES:
query.append("Queue=\'{}\'".format(Queue or self.default_queue))
if not raw_query:
operators_map = {
'gt': '>',
'lt': '<',
'exact': '=',
'notexact': '!=',
'like': ' LIKE ',
'notlike': ' NOT LIKE '
}
for key, value in iteritems(kwargs):
op = '='
key_parts = key.split('__')
if len(key_parts) > 1:
key = '__'.join(key_parts[:-1])
op = operators_map.get(key_parts[-1], '=')
if key[:3] != 'CF_':
query.append("{}{}\'{}\'".format(key, op, value))
else:
query.append("'CF.{{{}}}'{}\'{}\'".format(key[3:], op, value))
else:
query.append(raw_query)
get_params['query'] = ' AND '.join('(' + part + ')' for part in query)
if order:
get_params['orderby'] = order
get_params['format'] = Format
msg = self.__request(url, get_params=get_params)
lines = msg.split('\n')
if len(lines) > 2:
if self.__get_status_code(lines[0]) != 200 and lines[2].startswith('Invalid query: '):
raise InvalidQueryError(lines[2])
if lines[2].startswith('No matching results.'):
return []
if Format == 'l':
msgs = map(lambda x: x.split('\n'), msg.split('\n--\n'))
items = []
for msg in msgs:
pairs = {}
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 pairs:
items.append(pairs)
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 items
elif Format == 's':
items = []
msgs = lines[2:]
for msg in msgs:
if "" == msg:
continue
ticket_id, subject = self.split_header(msg)
items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id, 'Subject': subject})
return items
elif Format == 'i':
items = []
msgs = lines[2:]
for msg in msgs:
if "" == msg:
continue
_, ticket_id = msg.split('/', 1)
items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id})
return items | [
"def",
"search",
"(",
"self",
",",
"Queue",
"=",
"None",
",",
"order",
"=",
"None",
",",
"raw_query",
"=",
"None",
",",
"Format",
"=",
"'l'",
",",
"*",
"*",
"kwargs",
")",
":",
"get_params",
"=",
"{",
"}",
"query",
"=",
"[",
"]",
"url",
"=",
"'search/ticket'",
"if",
"Queue",
"is",
"not",
"ALL_QUEUES",
":",
"query",
".",
"append",
"(",
"\"Queue=\\'{}\\'\"",
".",
"format",
"(",
"Queue",
"or",
"self",
".",
"default_queue",
")",
")",
"if",
"not",
"raw_query",
":",
"operators_map",
"=",
"{",
"'gt'",
":",
"'>'",
",",
"'lt'",
":",
"'<'",
",",
"'exact'",
":",
"'='",
",",
"'notexact'",
":",
"'!='",
",",
"'like'",
":",
"' LIKE '",
",",
"'notlike'",
":",
"' NOT LIKE '",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"op",
"=",
"'='",
"key_parts",
"=",
"key",
".",
"split",
"(",
"'__'",
")",
"if",
"len",
"(",
"key_parts",
")",
">",
"1",
":",
"key",
"=",
"'__'",
".",
"join",
"(",
"key_parts",
"[",
":",
"-",
"1",
"]",
")",
"op",
"=",
"operators_map",
".",
"get",
"(",
"key_parts",
"[",
"-",
"1",
"]",
",",
"'='",
")",
"if",
"key",
"[",
":",
"3",
"]",
"!=",
"'CF_'",
":",
"query",
".",
"append",
"(",
"\"{}{}\\'{}\\'\"",
".",
"format",
"(",
"key",
",",
"op",
",",
"value",
")",
")",
"else",
":",
"query",
".",
"append",
"(",
"\"'CF.{{{}}}'{}\\'{}\\'\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"op",
",",
"value",
")",
")",
"else",
":",
"query",
".",
"append",
"(",
"raw_query",
")",
"get_params",
"[",
"'query'",
"]",
"=",
"' AND '",
".",
"join",
"(",
"'('",
"+",
"part",
"+",
"')'",
"for",
"part",
"in",
"query",
")",
"if",
"order",
":",
"get_params",
"[",
"'orderby'",
"]",
"=",
"order",
"get_params",
"[",
"'format'",
"]",
"=",
"Format",
"msg",
"=",
"self",
".",
"__request",
"(",
"url",
",",
"get_params",
"=",
"get_params",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"len",
"(",
"lines",
")",
">",
"2",
":",
"if",
"self",
".",
"__get_status_code",
"(",
"lines",
"[",
"0",
"]",
")",
"!=",
"200",
"and",
"lines",
"[",
"2",
"]",
".",
"startswith",
"(",
"'Invalid query: '",
")",
":",
"raise",
"InvalidQueryError",
"(",
"lines",
"[",
"2",
"]",
")",
"if",
"lines",
"[",
"2",
"]",
".",
"startswith",
"(",
"'No matching results.'",
")",
":",
"return",
"[",
"]",
"if",
"Format",
"==",
"'l'",
":",
"msgs",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"split",
"(",
"'\\n'",
")",
",",
"msg",
".",
"split",
"(",
"'\\n--\\n'",
")",
")",
"items",
"=",
"[",
"]",
"for",
"msg",
"in",
"msgs",
":",
"pairs",
"=",
"{",
"}",
"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",
"pairs",
":",
"items",
".",
"append",
"(",
"pairs",
")",
"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",
"items",
"elif",
"Format",
"==",
"'s'",
":",
"items",
"=",
"[",
"]",
"msgs",
"=",
"lines",
"[",
"2",
":",
"]",
"for",
"msg",
"in",
"msgs",
":",
"if",
"\"\"",
"==",
"msg",
":",
"# Ignore blank line at the end",
"continue",
"ticket_id",
",",
"subject",
"=",
"self",
".",
"split_header",
"(",
"msg",
")",
"items",
".",
"append",
"(",
"{",
"'id'",
":",
"'ticket/'",
"+",
"ticket_id",
",",
"'numerical_id'",
":",
"ticket_id",
",",
"'Subject'",
":",
"subject",
"}",
")",
"return",
"items",
"elif",
"Format",
"==",
"'i'",
":",
"items",
"=",
"[",
"]",
"msgs",
"=",
"lines",
"[",
"2",
":",
"]",
"for",
"msg",
"in",
"msgs",
":",
"if",
"\"\"",
"==",
"msg",
":",
"# Ignore blank line at the end",
"continue",
"_",
",",
"ticket_id",
"=",
"msg",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"items",
".",
"append",
"(",
"{",
"'id'",
":",
"'ticket/'",
"+",
"ticket_id",
",",
"'numerical_id'",
":",
"ticket_id",
"}",
")",
"return",
"items"
]
| Search arbitrary needles in given fields and queue.
Example::
>>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret')
>>> tracker.login()
>>> tickets = tracker.search(CF_Domain='example.com', Subject__like='warning')
>>> tickets = tracker.search(Queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")
:keyword Queue: Queue where to search. If you wish to search across
all of your queues, pass the ALL_QUEUES object as the
argument.
:keyword order: Name of field sorting result list, for descending
order put - before the field name. E.g. -Created
will put the newest tickets at the beginning
:keyword raw_query: A raw query to provide to RT if you know what
you are doing. You may still pass Queue and order
kwargs, so use these instead of including them in
the raw query. You can refer to the RT query builder.
If passing raw_query, all other **kwargs will be ignored.
:keyword Format: Format of the query:
- i: only `id' fields are populated
- s: only `id' and `subject' fields are populated
- l: multi-line format, all fields are populated
:keyword kwargs: Other arguments possible to set if not passing raw_query:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
To alter lookup operators you can append one of the
following endings to each keyword:
__exact for operator = (default)
__notexact for operator !=
__gt for operator >
__lt for operator <
__like for operator LIKE
__notlike for operator NOT LIKE
Setting values to keywords constrain search
result to the tickets satisfying all of them.
:returns: List of matching tickets. Each ticket is the same dictionary
as in :py:meth:`~Rt.get_ticket`.
:raises: UnexpectedMessageFormat: Unexpected format of returned message.
InvalidQueryError: If raw query is malformed | [
"Search",
"arbitrary",
"needles",
"in",
"given",
"fields",
"and",
"queue",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L421-L568 |
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):
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",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L570-L640 |
CZ-NIC/python-rt | rt.py | Rt.create_ticket | def create_ticket(self, Queue=None, files=[], **kwargs):
""" Create new ticket and set given parameters.
Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::
content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: [email protected]
Subject: Ticket created through REST API
Text: Lorem Ipsum
In case of success returned message has this form::
RT/3.8.7 200 Ok
# Ticket 123456 created.
# Ticket 123456 updated.
Otherwise::
RT/3.8.7 200 Ok
# Required: id, Queue
+ list of some key, value pairs, probably default values.
:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed
"""
post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, )
for key in kwargs:
if key[:4] == 'Text':
post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key]))
elif key[:3] == 'CF_':
post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key])
else:
post_data += "{}: {}\n".format(key, kwargs[key])
for file_info in files:
post_data += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/new', post_data={'content': post_data}, files=files)
for line in msg.split('\n')[2:-1]:
res = self.RE_PATTERNS['ticket_created_pattern'].match(line)
if res is not None:
return int(res.group(1))
warnings.warn(line[2:])
return -1 | python | def create_ticket(self, Queue=None, files=[], **kwargs):
post_data = 'id: ticket/new\nQueue: {}\n'.format(Queue or self.default_queue, )
for key in kwargs:
if key[:4] == 'Text':
post_data += "{}: {}\n".format(key, re.sub(r'\n', r'\n ', kwargs[key]))
elif key[:3] == 'CF_':
post_data += "CF.{{{}}}: {}\n".format(key[3:], kwargs[key])
else:
post_data += "{}: {}\n".format(key, kwargs[key])
for file_info in files:
post_data += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/new', post_data={'content': post_data}, files=files)
for line in msg.split('\n')[2:-1]:
res = self.RE_PATTERNS['ticket_created_pattern'].match(line)
if res is not None:
return int(res.group(1))
warnings.warn(line[2:])
return -1 | [
"def",
"create_ticket",
"(",
"self",
",",
"Queue",
"=",
"None",
",",
"files",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"'id: ticket/new\\nQueue: {}\\n'",
".",
"format",
"(",
"Queue",
"or",
"self",
".",
"default_queue",
",",
")",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"[",
":",
"4",
"]",
"==",
"'Text'",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"re",
".",
"sub",
"(",
"r'\\n'",
",",
"r'\\n '",
",",
"kwargs",
"[",
"key",
"]",
")",
")",
"elif",
"key",
"[",
":",
"3",
"]",
"==",
"'CF_'",
":",
"post_data",
"+=",
"\"CF.{{{}}}: {}\\n\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"kwargs",
"[",
"key",
"]",
")",
"else",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"for",
"file_info",
"in",
"files",
":",
"post_data",
"+=",
"\"\\nAttachment: {}\"",
".",
"format",
"(",
"file_info",
"[",
"0",
"]",
",",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/new'",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
",",
"files",
"=",
"files",
")",
"for",
"line",
"in",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
":",
"-",
"1",
"]",
":",
"res",
"=",
"self",
".",
"RE_PATTERNS",
"[",
"'ticket_created_pattern'",
"]",
".",
"match",
"(",
"line",
")",
"if",
"res",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"res",
".",
"group",
"(",
"1",
")",
")",
"warnings",
".",
"warn",
"(",
"line",
"[",
"2",
":",
"]",
")",
"return",
"-",
"1"
]
| Create new ticket and set given parameters.
Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``::
content=id: ticket/new
Queue: General
Owner: Nobody
Requestors: [email protected]
Subject: Ticket created through REST API
Text: Lorem Ipsum
In case of success returned message has this form::
RT/3.8.7 200 Ok
# Ticket 123456 created.
# Ticket 123456 updated.
Otherwise::
RT/3.8.7 200 Ok
# Required: id, Queue
+ list of some key, value pairs, probably default values.
:keyword Queue: Queue where to create ticket
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ID of new ticket or ``-1``, if creating failed | [
"Create",
"new",
"ticket",
"and",
"set",
"given",
"parameters",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L642-L700 |
CZ-NIC/python-rt | rt.py | Rt.edit_ticket | def edit_ticket(self, ticket_id, **kwargs):
""" Edit ticket values.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key, value in iteritems(kwargs):
if isinstance(value, (list, tuple)):
value = ", ".join(value)
if key[:3] != 'CF_':
post_data += "{}: {}\n".format(key, value)
else:
post_data += "CF.{{{}}}: {}\n".format(key[3:], value)
msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['update_pattern'].match(state) is not None | python | def edit_ticket(self, ticket_id, **kwargs):
post_data = ''
for key, value in iteritems(kwargs):
if isinstance(value, (list, tuple)):
value = ", ".join(value)
if key[:3] != 'CF_':
post_data += "{}: {}\n".format(key, value)
else:
post_data += "CF.{{{}}}: {}\n".format(key[3:], value)
msg = self.__request('ticket/{}/edit'.format(str(ticket_id)), post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['update_pattern'].match(state) is not None | [
"def",
"edit_ticket",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"''",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"\", \"",
".",
"join",
"(",
"value",
")",
"if",
"key",
"[",
":",
"3",
"]",
"!=",
"'CF_'",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"else",
":",
"post_data",
"+=",
"\"CF.{{{}}}: {}\\n\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"value",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/edit'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
")",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'update_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
]
| Edit ticket values.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set:
Requestors, Subject, Cc, AdminCc, Owner, Status,
Priority, InitialPriority, FinalPriority,
TimeEstimated, Starts, Due, Text,... (according to RT
fields)
Custom fields CF.{<CustomFieldName>} could be set
with keywords CF_CustomFieldName.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed) | [
"Edit",
"ticket",
"values",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L702-L731 |
CZ-NIC/python-rt | rt.py | Rt.get_history | def get_history(self, ticket_id, transaction_id=None):
""" Get set of history items.
:param ticket_id: ID of ticket
:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned
:returns: List of history items ordered increasingly by time of event.
Each history item is dictionary with following keys:
Description, Creator, Data, Created, TimeTaken, NewValue,
Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).
Returns None if ticket or transaction does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
if transaction_id is None:
# We are using "long" format to get all history items at once.
# Each history item is then separated by double dash.
msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), ))
else:
msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id)))
lines = msgs.split('\n')
if (len(lines) > 2) and (
self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match(
lines[2])):
return None
msgs = msgs.split('\n--\n')
items = []
for msg in msgs:
pairs = {}
msg = msg.split('\n')
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_id:
raise UnexpectedMessageFormat('Unexpected history entry. \
Missing line starting with `Content:`.')
atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)]
atta_id = atta_matching[0] if atta_matching else None
if not atta_id:
raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \
Missing line starting with `Attachements:`.')
for i in range(cont_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
content = msg[cont_id][9:]
cont_id += 1
while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9):
content += '\n' + msg[cont_id][9:]
cont_id += 1
pairs['Content'] = content
for i in range(cont_id, atta_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
attachments = []
for i in range(atta_id + 1, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
attachments.append((int(header),
content.strip()))
pairs['Attachments'] = attachments
items.append(pairs)
return items | python | def get_history(self, ticket_id, transaction_id=None):
if transaction_id is None:
msgs = self.__request('ticket/{}/history?format=l'.format(str(ticket_id), ))
else:
msgs = self.__request('ticket/{}/history/id/{}'.format(str(ticket_id), str(transaction_id)))
lines = msgs.split('\n')
if (len(lines) > 2) and (
self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match(
lines[2])):
return None
msgs = msgs.split('\n--\n')
items = []
for msg in msgs:
pairs = {}
msg = msg.split('\n')
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_id:
raise UnexpectedMessageFormat('Unexpected history entry. \
Missing line starting with `Content:`.')
atta_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['attachments_pattern'].match(m)]
atta_id = atta_matching[0] if atta_matching else None
if not atta_id:
raise UnexpectedMessageFormat('Unexpected attachment part of history entry. \
Missing line starting with `Attachements:`.')
for i in range(cont_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
content = msg[cont_id][9:]
cont_id += 1
while (cont_id < len(msg)) and (msg[cont_id][:9] == ' ' * 9):
content += '\n' + msg[cont_id][9:]
cont_id += 1
pairs['Content'] = content
for i in range(cont_id, atta_id):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
pairs[header.strip()] = content.strip()
attachments = []
for i in range(atta_id + 1, len(msg)):
if ': ' in msg[i]:
header, content = self.split_header(msg[i])
attachments.append((int(header),
content.strip()))
pairs['Attachments'] = attachments
items.append(pairs)
return items | [
"def",
"get_history",
"(",
"self",
",",
"ticket_id",
",",
"transaction_id",
"=",
"None",
")",
":",
"if",
"transaction_id",
"is",
"None",
":",
"# We are using \"long\" format to get all history items at once.",
"# Each history item is then separated by double dash.",
"msgs",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history?format=l'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"else",
":",
"msgs",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history/id/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"transaction_id",
")",
")",
")",
"lines",
"=",
"msgs",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'not_related_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"msgs",
"=",
"msgs",
".",
"split",
"(",
"'\\n--\\n'",
")",
"items",
"=",
"[",
"]",
"for",
"msg",
"in",
"msgs",
":",
"pairs",
"=",
"{",
"}",
"msg",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"cont_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'content_pattern'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"cont_id",
"=",
"cont_matching",
"[",
"0",
"]",
"if",
"cont_matching",
"else",
"None",
"if",
"not",
"cont_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected history entry. \\\n Missing line starting with `Content:`.'",
")",
"atta_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'attachments_pattern'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"atta_id",
"=",
"atta_matching",
"[",
"0",
"]",
"if",
"atta_matching",
"else",
"None",
"if",
"not",
"atta_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected attachment part of history entry. \\\n Missing line starting with `Attachements:`.'",
")",
"for",
"i",
"in",
"range",
"(",
"cont_id",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"content",
"=",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"cont_id",
"+=",
"1",
"while",
"(",
"cont_id",
"<",
"len",
"(",
"msg",
")",
")",
"and",
"(",
"msg",
"[",
"cont_id",
"]",
"[",
":",
"9",
"]",
"==",
"' '",
"*",
"9",
")",
":",
"content",
"+=",
"'\\n'",
"+",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"cont_id",
"+=",
"1",
"pairs",
"[",
"'Content'",
"]",
"=",
"content",
"for",
"i",
"in",
"range",
"(",
"cont_id",
",",
"atta_id",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"attachments",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"atta_id",
"+",
"1",
",",
"len",
"(",
"msg",
")",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"attachments",
".",
"append",
"(",
"(",
"int",
"(",
"header",
")",
",",
"content",
".",
"strip",
"(",
")",
")",
")",
"pairs",
"[",
"'Attachments'",
"]",
"=",
"attachments",
"items",
".",
"append",
"(",
"pairs",
")",
"return",
"items"
]
| Get set of history items.
:param ticket_id: ID of ticket
:keyword transaction_id: If set to None, all history items are
returned, if set to ID of valid transaction
just one history item is returned
:returns: List of history items ordered increasingly by time of event.
Each history item is dictionary with following keys:
Description, Creator, Data, Created, TimeTaken, NewValue,
Content, Field, OldValue, Ticket, Type, id, Attachments
All these fields are strings, just 'Attachments' holds list
of pairs (attachment_id,filename_with_size).
Returns None if ticket or transaction does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message. | [
"Get",
"set",
"of",
"history",
"items",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L733-L801 |
CZ-NIC/python-rt | rt.py | Rt.get_short_history | def get_short_history(self, ticket_id):
""" Get set of short history items
:param ticket_id: ID of ticket
:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/history'.format(str(ticket_id), ))
items = []
lines = msg.split('\n')
multiline_buffer = ""
in_multiline = False
if self.__get_status_code(lines[0]) == 200:
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
if len(lines) >= 4:
for line in lines[4:]:
if line == "":
if not in_multiline:
# start of multiline block
in_multiline = True
else:
# end of multiline block
line = multiline_buffer
multiline_buffer = ""
in_multiline = False
else:
if in_multiline:
multiline_buffer += line
line = ""
if ': ' in line:
hist_id, desc = line.split(': ', 1)
items.append((int(hist_id), desc))
return items | python | def get_short_history(self, ticket_id):
msg = self.__request('ticket/{}/history'.format(str(ticket_id), ))
items = []
lines = msg.split('\n')
multiline_buffer = ""
in_multiline = False
if self.__get_status_code(lines[0]) == 200:
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
if len(lines) >= 4:
for line in lines[4:]:
if line == "":
if not in_multiline:
in_multiline = True
else:
line = multiline_buffer
multiline_buffer = ""
in_multiline = False
else:
if in_multiline:
multiline_buffer += line
line = ""
if ': ' in line:
hist_id, desc = line.split(': ', 1)
items.append((int(hist_id), desc))
return items | [
"def",
"get_short_history",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/history'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"items",
"=",
"[",
"]",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"multiline_buffer",
"=",
"\"\"",
"in_multiline",
"=",
"False",
"if",
"self",
".",
"__get_status_code",
"(",
"lines",
"[",
"0",
"]",
")",
"==",
"200",
":",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"if",
"len",
"(",
"lines",
")",
">=",
"4",
":",
"for",
"line",
"in",
"lines",
"[",
"4",
":",
"]",
":",
"if",
"line",
"==",
"\"\"",
":",
"if",
"not",
"in_multiline",
":",
"# start of multiline block",
"in_multiline",
"=",
"True",
"else",
":",
"# end of multiline block",
"line",
"=",
"multiline_buffer",
"multiline_buffer",
"=",
"\"\"",
"in_multiline",
"=",
"False",
"else",
":",
"if",
"in_multiline",
":",
"multiline_buffer",
"+=",
"line",
"line",
"=",
"\"\"",
"if",
"': '",
"in",
"line",
":",
"hist_id",
",",
"desc",
"=",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"items",
".",
"append",
"(",
"(",
"int",
"(",
"hist_id",
")",
",",
"desc",
")",
")",
"return",
"items"
]
| Get set of short history items
:param ticket_id: ID of ticket
:returns: List of history items ordered increasingly by time of event.
Each history item is a tuple containing (id, Description).
Returns None if ticket does not exist. | [
"Get",
"set",
"of",
"short",
"history",
"items"
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L803-L837 |
CZ-NIC/python-rt | rt.py | Rt.__correspond | def __correspond(self, ticket_id, text='', action='correspond', cc='', bcc='', content_type='text/plain', files=[]):
""" Sends out the correspondence
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword action: correspond or comment
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist
"""
post_data = {'content': """id: {}
Action: {}
Text: {}
Cc: {}
Bcc: {}
Content-Type: {}""".format(str(ticket_id), action, re.sub(r'\n', r'\n ', text), cc, bcc, content_type)}
for file_info in files:
post_data['content'] += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/{}/comment'.format(str(ticket_id), ),
post_data=post_data, files=files)
return self.__get_status_code(msg) == 200 | python | def __correspond(self, ticket_id, text='', action='correspond', cc='', bcc='', content_type='text/plain', files=[]):
post_data = {'content': .format(str(ticket_id), action, re.sub(r'\n', r'\n ', text), cc, bcc, content_type)}
for file_info in files:
post_data['content'] += "\nAttachment: {}".format(file_info[0], )
msg = self.__request('ticket/{}/comment'.format(str(ticket_id), ),
post_data=post_data, files=files)
return self.__get_status_code(msg) == 200 | [
"def",
"__correspond",
"(",
"self",
",",
"ticket_id",
",",
"text",
"=",
"''",
",",
"action",
"=",
"'correspond'",
",",
"cc",
"=",
"''",
",",
"bcc",
"=",
"''",
",",
"content_type",
"=",
"'text/plain'",
",",
"files",
"=",
"[",
"]",
")",
":",
"post_data",
"=",
"{",
"'content'",
":",
"\"\"\"id: {}\nAction: {}\nText: {}\nCc: {}\nBcc: {}\nContent-Type: {}\"\"\"",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"action",
",",
"re",
".",
"sub",
"(",
"r'\\n'",
",",
"r'\\n '",
",",
"text",
")",
",",
"cc",
",",
"bcc",
",",
"content_type",
")",
"}",
"for",
"file_info",
"in",
"files",
":",
"post_data",
"[",
"'content'",
"]",
"+=",
"\"\\nAttachment: {}\"",
".",
"format",
"(",
"file_info",
"[",
"0",
"]",
",",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/comment'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
",",
"post_data",
"=",
"post_data",
",",
"files",
"=",
"files",
")",
"return",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"==",
"200"
]
| Sends out the correspondence
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword action: correspond or comment
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist | [
"Sends",
"out",
"the",
"correspondence"
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L839-L866 |
CZ-NIC/python-rt | rt.py | Rt.reply | def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):
""" Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist
"""
return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) | python | def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):
return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) | [
"def",
"reply",
"(",
"self",
",",
"ticket_id",
",",
"text",
"=",
"''",
",",
"cc",
"=",
"''",
",",
"bcc",
"=",
"''",
",",
"content_type",
"=",
"'text/plain'",
",",
"files",
"=",
"[",
"]",
")",
":",
"return",
"self",
".",
"__correspond",
"(",
"ticket_id",
",",
"text",
",",
"'correspond'",
",",
"cc",
",",
"bcc",
",",
"content_type",
",",
"files",
")"
]
| Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path
:param ticket_id: ID of ticket to which message belongs
:keyword text: Content of email message
:keyword content_type: Content type of email message, default to text/plain
:keyword cc: Carbon copy just for this reply
:keyword bcc: Blind carbon copy just for this reply
:keyword files: Files to attach as multipart/form-data
List of 2/3 tuples: (filename, file-like object, [content type])
:returns: ``True``
Operation was successful
``False``
Sending failed (status code != 200)
:raises BadRequest: When ticket does not exist | [
"Sends",
"email",
"message",
"to",
"the",
"contacts",
"in",
"Requestors",
"field",
"of",
"given",
"ticket",
"with",
"subject",
"as",
"is",
"set",
"in",
"Subject",
"field",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L868-L896 |
CZ-NIC/python-rt | rt.py | Rt.get_attachments | def get_attachments(self, ticket_id):
""" Get attachment list for a given ticket
:param ticket_id: ID of ticket
:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist.
"""
msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), ))
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
attachment_infos = []
if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4):
for line in lines[4:]:
info = self.RE_PATTERNS['attachments_list_pattern'].match(line)
if info:
attachment_infos.append(info.groups())
return attachment_infos | python | def get_attachments(self, ticket_id):
msg = self.__request('ticket/{}/attachments'.format(str(ticket_id), ))
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
attachment_infos = []
if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4):
for line in lines[4:]:
info = self.RE_PATTERNS['attachments_list_pattern'].match(line)
if info:
attachment_infos.append(info.groups())
return attachment_infos | [
"def",
"get_attachments",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"attachment_infos",
"=",
"[",
"]",
"if",
"(",
"self",
".",
"__get_status_code",
"(",
"lines",
"[",
"0",
"]",
")",
"==",
"200",
")",
"and",
"(",
"len",
"(",
"lines",
")",
">=",
"4",
")",
":",
"for",
"line",
"in",
"lines",
"[",
"4",
":",
"]",
":",
"info",
"=",
"self",
".",
"RE_PATTERNS",
"[",
"'attachments_list_pattern'",
"]",
".",
"match",
"(",
"line",
")",
"if",
"info",
":",
"attachment_infos",
".",
"append",
"(",
"info",
".",
"groups",
"(",
")",
")",
"return",
"attachment_infos"
]
| Get attachment list for a given ticket
:param ticket_id: ID of ticket
:returns: List of tuples for attachments belonging to given ticket.
Tuple format: (id, name, content_type, size)
Returns None if ticket does not exist. | [
"Get",
"attachment",
"list",
"for",
"a",
"given",
"ticket"
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L933-L951 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.