本文整理汇总了Python中asyncio.Transport方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.Transport方法的具体用法?Python asyncio.Transport怎么用?Python asyncio.Transport使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.Transport方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def __init__(
self,
connection: Connection,
h2_connection: H2Connection,
transport: Transport,
*,
stream_id: Optional[int] = None,
wrapper: Optional[Wrapper] = None
) -> None:
self.connection = connection
self._h2_connection = h2_connection
self._transport = transport
self.wrapper = wrapper
if stream_id is not None:
self.init_stream(stream_id, self.connection)
self.window_updated = Event()
self.headers: Optional['_Headers'] = None
self.headers_received = Event()
self.trailers: Optional['_Headers'] = None
self.trailers_received = Event()
示例2: _connect_serial
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def _connect_serial(self):
try:
if self._hub_version == 1:
url = "socket://{}:{}".format(self._host, self._port)
_LOGGER.info("Connecting to Insteon Hub v1 on %s", url)
# pylint: disable=unused-variable
transport, protocol = await create_serial_connection(
self._loop, lambda: self.protocol, url, baudrate=19200
)
else:
_LOGGER.info("Connecting to PLM on %s", self._device)
# pylint: disable=unused-variable
transport, protocol = await create_serial_connection(
self._loop, lambda: self.protocol, self._device, baudrate=19200
)
self._closed = False
except OSError:
self._closed = True
return not self._closed
# Hub version 1 (2242) is untested using the HTTP Transport.
# It is tested using the PLM socket interface on port 9761.
# pylint: disable=too-many-instance-attributes
示例3: test_create_datagram_endpoint_sock
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def test_create_datagram_endpoint_sock(self):
sock = None
local_address = ('127.0.0.1', 0)
infos = self.loop.run_until_complete(
self.loop.getaddrinfo(
*local_address, type=socket.SOCK_DGRAM))
for family, type, proto, cname, address in infos:
try:
sock = socket.socket(family=family, type=type, proto=proto)
sock.setblocking(False)
sock.bind(address)
except:
pass
else:
break
else:
assert False, 'Can not create socket.'
f = self.loop.create_connection(
lambda: MyDatagramProto(loop=self.loop), sock=sock)
tr, pr = self.loop.run_until_complete(f)
self.assertIsInstance(tr, asyncio.Transport)
self.assertIsInstance(pr, MyDatagramProto)
tr.close()
self.loop.run_until_complete(pr.done)
示例4: test_flowcontrol_mixin_set_write_limits
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def test_flowcontrol_mixin_set_write_limits(self):
class MyTransport(transports._FlowControlMixin,
transports.Transport):
def get_write_buffer_size(self):
return 512
loop = mock.Mock()
transport = MyTransport(loop=loop)
transport._protocol = mock.Mock()
self.assertFalse(transport._protocol_paused)
with self.assertRaisesRegex(ValueError, 'high.*must be >= low'):
transport.set_write_buffer_limits(high=0, low=1)
transport.set_write_buffer_limits(high=1024, low=128)
self.assertFalse(transport._protocol_paused)
self.assertEqual(transport.get_write_buffer_limits(), (128, 1024))
transport.set_write_buffer_limits(high=256, low=128)
self.assertTrue(transport._protocol_paused)
self.assertEqual(transport.get_write_buffer_limits(), (128, 256))
示例5: test_ping_server
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def test_ping_server(*args, **kwargs):
test_transport = asyncio.Transport()
test_transport.get_extra_info = mock.Mock(return_value=mock_transport_extra_info())
test_transport.write = mock.Mock(return_value=return_send_data)
xmppclient = bumper.xmppserver.XMPPAsyncClient(test_transport)
xmppclient.state = xmppclient.READY # Set client state to READY
xmppclient.uid = "E0000000000000001234"
xmppclient.devclass = "159"
mock_send = xmppclient.send = mock.Mock(side_effect=return_send_data)
# Ping from bot
test_data = '<iq xmlns:ns0="urn:xmpp:ping" from="E000BVTNX18700260382@159.ecorobot.net/atom" id="2542" to="159.ecorobot.net" type="get"><ping /></iq>'.encode(
"utf-8"
)
xmppclient._parse_data(test_data)
assert (
mock_send.mock_calls[0].args[0]
== '<iq type="result" id="2542" from="159.ecorobot.net" />'
) # ping response
示例6: _wrap_create_connection
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def _wrap_create_connection(
self, *args: Any,
req: 'ClientRequest',
timeout: 'ClientTimeout',
client_error: Type[Exception]=ClientConnectorError,
**kwargs: Any) -> Tuple[asyncio.Transport, ResponseHandler]:
try:
with CeilTimeout(timeout.sock_connect):
return cast(
Tuple[asyncio.Transport, ResponseHandler],
await self._loop.create_connection(*args, **kwargs))
except cert_errors as exc:
raise ClientConnectorCertificateError(
req.connection_key, exc) from exc
except ssl_errors as exc:
raise ClientConnectorSSLError(req.connection_key, exc) from exc
except OSError as exc:
raise client_error(req.connection_key, exc) from exc
示例7: tcp_cork
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def tcp_cork(transport: asyncio.Transport, value: bool) -> None:
sock = transport.get_extra_info('socket')
if CORK is None:
return
if sock is None:
return
if sock.family not in (socket.AF_INET, socket.AF_INET6):
return
value = bool(value)
with suppress(OSError):
sock.setsockopt(
socket.IPPROTO_TCP, CORK, value)
示例8: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def __init__(self, loop: asyncio.AbstractEventLoop, peer_timeout: typing.Optional[float] = 10,
connection_manager: typing.Optional['ConnectionManager'] = None):
self.loop = loop
self.peer_port: typing.Optional[int] = None
self.peer_address: typing.Optional[str] = None
self.transport: typing.Optional[asyncio.Transport] = None
self.peer_timeout = peer_timeout
self.connection_manager = connection_manager
self.writer: typing.Optional['HashBlobWriter'] = None
self.blob: typing.Optional['AbstractBlob'] = None
self._blob_bytes_received = 0
self._response_fut: typing.Optional[asyncio.Future] = None
self.buf = b''
# this is here to handle the race when the downloader is closed right as response_fut gets a result
self.closed = asyncio.Event(loop=self.loop)
示例9: test_stream_response_writes_correct_content_to_transport_when_chunked
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def test_stream_response_writes_correct_content_to_transport_when_chunked(
streaming_app,
):
response = StreamingHTTPResponse(sample_streaming_fn)
response.protocol = MagicMock(HttpProtocol)
response.protocol.transport = MagicMock(asyncio.Transport)
async def mock_drain():
pass
async def mock_push_data(data):
response.protocol.transport.write(data)
response.protocol.push_data = mock_push_data
response.protocol.drain = mock_drain
@streaming_app.listener("after_server_start")
async def run_stream(app, loop):
await response.stream()
assert response.protocol.transport.write.call_args_list[1][0][0] == (
b"4\r\nfoo,\r\n"
)
assert response.protocol.transport.write.call_args_list[2][0][0] == (
b"3\r\nbar\r\n"
)
assert response.protocol.transport.write.call_args_list[3][0][0] == (
b"0\r\n\r\n"
)
assert len(response.protocol.transport.write.call_args_list) == 4
app.stop()
streaming_app.run(host=HOST, port=PORT)
示例10: test_stream_response_writes_correct_content_to_transport_when_not_chunked
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def test_stream_response_writes_correct_content_to_transport_when_not_chunked(
streaming_app,
):
response = StreamingHTTPResponse(sample_streaming_fn)
response.protocol = MagicMock(HttpProtocol)
response.protocol.transport = MagicMock(asyncio.Transport)
async def mock_drain():
pass
async def mock_push_data(data):
response.protocol.transport.write(data)
response.protocol.push_data = mock_push_data
response.protocol.drain = mock_drain
@streaming_app.listener("after_server_start")
async def run_stream(app, loop):
await response.stream(version="1.0")
assert response.protocol.transport.write.call_args_list[1][0][0] == (
b"foo,"
)
assert response.protocol.transport.write.call_args_list[2][0][0] == (
b"bar"
)
assert len(response.protocol.transport.write.call_args_list) == 3
app.stop()
streaming_app.run(host=HOST, port=PORT)
示例11: connection_made
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def connection_made(self, transport: asyncio.Transport):
self.transport = transport
self.conn.initiate_connection()
self.transport.write(self.conn.data_to_send())
示例12: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def __init__(self, node_name: str):
""" Create connection handler object. """
super().__init__()
self.node_name_ = node_name
""" Name of the running Erlang node. """
self.packet_len_size_ = 2
""" Packet size header is variable, 2 bytes before handshake is finished
and 4 bytes afterwards. """
self.addr_ = None # type: [None, Tuple[str, int]]
self.inbox_ = asyncio.Queue()
""" Inbox is used to ask the connection to do something. """
self.peer_distr_version_ = (None, None) # type: (int, int)
""" Protocol version range supported by the remote peer. Erlang/OTP
versions 19-20 supports protocol version 7, older Erlangs down to
R6B support version 5. """
self.peer_flags_ = 0
self.peer_name_ = None # type: Union[None, str]
self.my_challenge_ = None
self.state_ = self.DISCONNECTED
""" FSM state for the protocol state-machine. """
self.transport_ = None # type: [None, asyncio.Transport]
self.unconsumed_data_ = b''
self._last_interaction = time.time()
示例13: connection_made
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def connection_made(self, transport: asyncio.Transport):
""" Connection has been accepted and established (callback).
"""
# Ping the remote periodically if our state is CONNECTED
self._schedule_periodic_ping_remote()
# Check that there's been some activity between the nodes
self._schedule_periodic_alive_check()
sock = transport.get_extra_info('socket')
self.transport_ = transport
self.addr_ = sock.getpeername()
self.state_ = self.RECV_NAME
示例14: connection_made
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def connection_made(self, transport: asyncio.Transport):
super().connection_made(transport)
self._send_name()
self.state_ = self.RECV_STATUS
示例15: connection_made
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import Transport [as 别名]
def connection_made(self, transport: BaseTransport) -> None:
sock = transport.get_extra_info('socket')
if sock is not None:
_set_nodelay(sock)
h2_conn = H2Connection(config=self.h2_config)
h2_conn.initiate_connection()
initial = h2_conn.local_settings.initial_window_size
conn_delta = self.config.http2_connection_window_size - initial
stream_delta = self.config.http2_stream_window_size - initial
if conn_delta:
h2_conn.increment_flow_control_window(conn_delta)
if stream_delta:
h2_conn.update_settings({
SettingCodes.INITIAL_WINDOW_SIZE:
self.config.http2_stream_window_size,
})
self.connection = Connection(
h2_conn,
cast(Transport, transport),
config=self.config,
)
self.connection.flush()
self.connection.initialize()
self.processor = EventsProcessor(self.handler, self.connection)