本文整理匯總了Python中asyncio.StreamWriter方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.StreamWriter方法的具體用法?Python asyncio.StreamWriter怎麽用?Python asyncio.StreamWriter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.StreamWriter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handshake
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def handshake(
remote: kademlia.Node, privkey: datatypes.PrivateKey, token: CancelToken
) -> Tuple[
bytes, bytes, BasePreImage, BasePreImage, asyncio.StreamReader, asyncio.StreamWriter
]: # noqa: E501
"""
Perform the auth handshake with given remote.
Returns the established secrets and the StreamReader/StreamWriter pair already connected to
the remote.
"""
use_eip8 = False
initiator = HandshakeInitiator(remote, privkey, use_eip8, token)
reader, writer = await initiator.connect()
opened_connections[remote.__repr__()] = (reader, writer)
aes_secret, mac_secret, egress_mac, ingress_mac = await _handshake(
initiator, reader, writer, token
)
return aes_secret, mac_secret, egress_mac, ingress_mac, reader, writer
示例2: aclosing_multiple_writers
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def aclosing_multiple_writers(*writers: asyncio.StreamWriter):
"""Closes StreamWriters on clean exits, aborts them on exceptions.
The "as" clause returns a set, and more StreamWriters can be added to the
set.
"""
writers = set(writers)
try:
yield writers
except:
for w in writers:
w.transport.abort()
raise
else:
for w in writers:
w.close()
finally:
close_tasks, _ = await asyncio.wait([w.wait_closed() for w in writers])
for t in close_tasks:
if t.exception():
logger.debug(
'wait_closed() raised exception: %r', t.exception())
示例3: handle_ext_server_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def handle_ext_server_connection(
upstream_host: str,
upstream_port: int,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
info: adapters.ExtOrPortClientConnection,
) -> None:
handler_logger.info('Connection received from %r', info)
async with contexts.log_unhandled_exc(handler_logger), \
contexts.aclosing_multiple_writers(writer) as writers:
try:
ureader, uwriter = await asyncio.open_connection(
upstream_host, upstream_port)
except OSError as e:
handler_logger.warning(
'Error while connecting to upstream: %r', e)
return
writers.add(writer)
try:
await relays.relay(reader, writer, ureader, uwriter)
except OSError as e:
handler_logger.warning('Connection from %r caught %r', info, e)
示例4: __init__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def __init__(
self,
app: ASGIFramework,
loop: asyncio.AbstractEventLoop,
config: Config,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
) -> None:
self.app = app
self.config = config
self.loop = loop
self.protocol: ProtocolWrapper
self.reader = reader
self.writer = writer
self.send_lock = asyncio.Lock()
self.timeout_lock = asyncio.Lock()
self._keep_alive_timeout_handle: Optional[asyncio.Task] = None
示例5: __init__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def __init__(
self,
stream=None,
level: Union[str, int, LogLevel] = LogLevel.NOTSET,
formatter: Formatter = None,
filter: Filter = None,
*,
loop: Optional[AbstractEventLoop] = None,
) -> None:
super().__init__(loop=loop)
if stream is None:
stream = sys.stderr
self.stream = stream
self.level = level
if formatter is None:
formatter = Formatter()
self.formatter: Formatter = formatter
if filter:
self.add_filter(filter)
self.protocol_class = AiologgerProtocol
self._initialization_lock = asyncio.Lock(loop=self.loop)
self.writer: Optional[StreamWriter] = None
示例6: _init_writer
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def _init_writer(self) -> StreamWriter:
async with self._initialization_lock:
if self.writer is not None:
return self.writer
transport, protocol = await self.loop.connect_write_pipe(
self.protocol_class, self.stream
)
self.writer = StreamWriter( # type: ignore # https://github.com/python/typeshed/pull/2719
transport=transport,
protocol=protocol,
reader=None,
loop=self.loop,
)
return self.writer
示例7: test_init_writer_initializes_a_nonblocking_pipe_streamwriter
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def test_init_writer_initializes_a_nonblocking_pipe_streamwriter(
self
):
handler = AsyncStreamHandler(
stream=self.write_pipe, level=10, formatter=Mock()
)
self.assertFalse(handler.initialized)
await handler._init_writer()
self.assertIsInstance(handler.writer, asyncio.StreamWriter)
self.assertIsInstance(handler.writer._protocol, AiologgerProtocol)
self.assertEqual(handler.writer.transport._pipe, self.write_pipe)
self.assertTrue(handler.initialized)
await handler.close()
示例8: test_emit_writes_records_into_the_stream
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def test_emit_writes_records_into_the_stream(self):
msg = self.record.msg
formatter = Mock(format=Mock(return_value=msg))
writer = Mock(write=Mock(), drain=CoroutineMock())
with patch(
"aiologger.handlers.streams.StreamWriter", return_value=writer
):
handler = AsyncStreamHandler(
level=10, stream=self.write_pipe, formatter=formatter
)
await handler.emit(self.record)
writer.write.assert_called_once_with(
(msg + handler.terminator).encode()
)
writer.drain.assert_awaited_once()
await handler.close()
示例9: test_emit_calls_handle_error_if_an_error_occurs
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def test_emit_calls_handle_error_if_an_error_occurs(self):
writer = Mock(write=CoroutineMock(), drain=CoroutineMock())
with patch(
"aiologger.handlers.streams.StreamWriter", return_value=writer
):
exc = Exception("XABLAU")
handler = AsyncStreamHandler(
level=10,
stream=self.write_pipe,
formatter=Mock(format=Mock(side_effect=exc)),
)
with asynctest.patch.object(
handler, "handle_error"
) as handle_error:
await handler.emit(self.record)
handle_error.assert_awaited_once_with(self.record, exc)
writer.write.assert_not_awaited()
writer.drain.assert_not_awaited()
示例10: create_pipe_streams_pair
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def create_pipe_streams_pair():
path = tempfile.mktemp()
loop = asyncio.get_event_loop()
server_side = asyncio.Future()
def factory():
def client_connected_cb(reader, writer):
server_side.set_result((reader, writer))
reader = asyncio.StreamReader(loop=loop)
return asyncio.StreamReaderProtocol(reader, client_connected_cb, loop=loop)
server = yield from loop.create_unix_server(factory, path)
r1 = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(r1, loop=loop)
transport, _ = yield from loop.create_unix_connection(
lambda: protocol, path)
w1 = asyncio.StreamWriter(transport, protocol, r1, loop)
r2, w2 = yield from server_side
server.close()
return (r1, w1), (r2, w2)
示例11: __call__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def __call__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Main entry point for an interpreter session with a single client."""
self.reader = reader
self.writer = writer
self.running = True
if self.banner:
writer.write(self.banner)
await writer.drain()
while self.running:
try:
await self.handle_one_command()
except ConnectionResetError:
writer.close()
self.running = False
break
except Exception:
log.exception("Exception in manhole REPL")
self.writer.write(traceback.format_exc())
await self.writer.drain()
示例12: test_socks5_http_create_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def test_socks5_http_create_connection(event_loop):
reader = asyncio.StreamReader(loop=event_loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=event_loop)
transport, _ = await create_connection(
proxy_url=SOCKS5_IPV4_URL,
protocol_factory=lambda: protocol,
host=HTTP_TEST_HOST,
port=HTTP_TEST_PORT,
)
writer = asyncio.StreamWriter(transport, protocol, reader, event_loop)
request = ("GET /ip HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n\r\n" % HTTP_TEST_HOST)
writer.write(request.encode())
response = await reader.read(-1)
assert b'200 OK' in response
示例13: receive_handshake
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def receive_handshake(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
try:
await self._receive_handshake(reader, writer)
except BaseException:
if not reader.at_eof():
reader.feed_eof()
writer.close()
raise
except COMMON_RECEIVE_HANDSHAKE_EXCEPTIONS as e:
peername = writer.get_extra_info("peername")
self.logger.debug("Could not complete handshake with %s: %s", peername, e)
except asyncio.CancelledError:
# This exception should just bubble.
raise
except Exception:
peername = writer.get_extra_info("peername")
self.logger.exception("Unexpected error handling handshake with %s", peername)
示例14: get_directly_connected_streams
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def get_directly_connected_streams(alice_extra_info: Dict[str, Any] = None,
bob_extra_info: Dict[str, Any] = None,
loop: asyncio.AbstractEventLoop = None) -> TConnectedStreams:
if loop is None:
loop = asyncio.get_event_loop()
alice_reader = asyncio.StreamReader()
bob_reader = asyncio.StreamReader()
alice_transport = MemoryWriteTransport(bob_reader, extra=alice_extra_info)
bob_transport = MemoryWriteTransport(alice_reader, extra=bob_extra_info)
alice_protocol = MemoryProtocol()
bob_protocol = MemoryProtocol()
# Link the alice's writer to the bob's reader, and the bob's writer to the
# alice's reader.
bob_writer = asyncio.StreamWriter(bob_transport, bob_protocol, alice_reader, loop=loop)
alice_writer = asyncio.StreamWriter(alice_transport, alice_protocol, bob_reader, loop=loop)
return (
(alice_reader, alice_writer),
(bob_reader, bob_writer),
)
示例15: open_serial_connection
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import StreamWriter [as 別名]
def open_serial_connection(*,
loop=None,
limit=asyncio.streams._DEFAULT_LIMIT,
**kwargs):
"""A wrapper for create_serial_connection() returning a (reader,
writer) pair.
The reader returned is a StreamReader instance; the writer is a
StreamWriter instance.
The arguments are all the usual arguments to Serial(). Additional
optional keyword arguments are loop (to set the event loop instance
to use) and limit (to set the buffer limit passed to the
StreamReader.
This function is a coroutine.
"""
if loop is None:
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
transport, _ = yield from create_serial_connection(
loop=loop,
protocol_factory=lambda: protocol,
**kwargs)
writer = asyncio.StreamWriter(transport, protocol, reader, loop)
return reader, writer
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# test