__all__ = ('StreamReader', 'StreamWriter', 'StreamReaderProtocol','open_connection', 'start_server','IncompleteReadError', 'LimitOverrunError',)import socketif hasattr(socket, 'AF_UNIX'):__all__ += ('open_unix_connection', 'start_unix_server')from . import coroutinesfrom . import eventsfrom . import protocolsfrom .log import loggerfrom .tasks import sleep_DEFAULT_LIMIT = 2 ** 16 # 64 KiBclass IncompleteReadError(EOFError):"""Incomplete read error. Attributes:- partial: read bytes string before the end of stream was reached- expected: total number of expected bytes (or None if unknown)"""def __init__(self, partial, expected):super().__init__(f'{len(partial)} bytes read on a total of 'f'{expected!r} expected bytes')self.partial = partialself.expected = expecteddef __reduce__(self):return type(self), (self.partial, self.expected)class LimitOverrunError(Exception):"""Reached the buffer limit while looking for a separator.Attributes:- consumed: total number of to be consumed bytes."""def __init__(self, message, consumed):super().__init__(message)self.consumed = consumeddef __reduce__(self):return type(self), (self.args[0], self.consumed)async def open_connection(host=None, port=None, *,loop=None, limit=_DEFAULT_LIMIT, **kwds):"""A wrapper for create_connection() returning a (reader, writer) pair.The reader returned is a StreamReader instance; the writer is aStreamWriter instance.The arguments are all the usual arguments to create_connection()except protocol_factory; most common are positional host and port,with various optional keyword arguments following.Additional optional keyword arguments are loop (to set the event loopinstance to use) and limit (to set the buffer limit passed to theStreamReader).(If you want to customize the StreamReader and/orStreamReaderProtocol classes, just copy the code -- there'sreally nothing special here except some convenience.)"""if loop is None:loop = events.get_event_loop()reader = StreamReader(limit=limit, loop=loop)protocol = StreamReaderProtocol(reader, loop=loop)transport, _ = await loop.create_connection(lambda: protocol, host, port, **kwds)writer = StreamWriter(transport, protocol, reader, loop)return reader, writerasync def start_server(client_connected_cb, host=None, port=None, *,loop=None, limit=_DEFAULT_LIMIT, **kwds):"""Start a socket server, call back for each client connected.The first parameter, `client_connected_cb`, takes two parameters:client_reader, client_writer. client_reader is a StreamReaderobject, while client_writer is a StreamWriter object. Thisparameter can either be a plain callback function or a coroutine;if it is a coroutine, it will be automatically converted into aTask.The rest of the arguments are all the usual arguments toloop.create_server() except protocol_factory; most common arepositional host and port, with various optional keyword argumentsfollowing. The return value is the same as loop.create_server().Additional optional keyword arguments are loop (to set the event loopinstance to use) and limit (to set the buffer limit passed to theStreamReader).The return value is the same as loop.create_server(), i.e. aServer object which can be used to stop the service."""if loop is None:loop = events.get_event_loop()def factory():reader = StreamReader(limit=limit, loop=loop)protocol = StreamReaderProtocol(reader, client_connected_cb,loop=loop)return protocolreturn await loop.create_server(factory, host, port, **kwds)if hasattr(socket, 'AF_UNIX'):# UNIX Domain Sockets are supported on this platformasync def open_unix_connection(path=None, *,loop=None, limit=_DEFAULT_LIMIT, **kwds):"""Similar to `open_connection` but works with UNIX Domain Sockets."""if loop is None:loop = events.get_event_loop()reader = StreamReader(limit=limit, loop=loop)protocol = StreamReaderProtocol(reader, loop=loop)transport, _ = await loop.create_unix_connection(lambda: protocol, path, **kwds)writer = StreamWriter(transport, protocol, reader, loop)return reader, writerasync def start_unix_server(client_connected_cb, path=None, *,loop=None, limit=_DEFAULT_LIMIT, **kwds):"""Similar to `start_server` but works with UNIX Domain Sockets."""if loop is None:loop = events.get_event_loop()def factory():reader = StreamReader(limit=limit, loop=loop)protocol = StreamReaderProtocol(reader, client_connected_cb,loop=loop)return protocolreturn await loop.create_unix_server(factory, path, **kwds)class FlowControlMixin(protocols.Protocol):"""Reusable flow control logic for StreamWriter.drain().This implements the protocol methods pause_writing(),resume_writing() and connection_lost(). If the subclass overridesthese it must call the super methods.StreamWriter.drain() must wait for _drain_helper() coroutine."""def __init__(self, loop=None):if loop is None:self._loop = events.get_event_loop()else:self._loop = loopself._paused = Falseself._drain_waiter = Noneself._connection_lost = Falsedef pause_writing(self):assert not self._pausedself._paused = Trueif self._loop.get_debug():logger.debug("%r pauses writing", self)def resume_writing(self):assert self._pausedself._paused = Falseif self._loop.get_debug():logger.debug("%r resumes writing", self)waiter = self._drain_waiterif waiter is not None:self._drain_waiter = Noneif not waiter.done():waiter.set_result(None)def connection_lost(self, exc):self._connection_lost = True# Wake up the writer if currently paused.if not self._paused:returnwaiter = self._drain_waiterif waiter is None:returnself._drain_waiter = Noneif waiter.done():returnif exc is None:waiter.set_result(None)else:waiter.set_exception(exc)async def _drain_helper(self):if self._connection_lost:raise ConnectionResetError('Connection lost')if not self._paused:returnwaiter = self._drain_waiterassert waiter is None or waiter.cancelled()waiter = self._loop.create_future()self._drain_waiter = waiterawait waiterclass StreamReaderProtocol(FlowControlMixin, protocols.Protocol):"""Helper class to adapt between Protocol and StreamReader.(This is a helper class instead of making StreamReader itself aProtocol subclass, because the StreamReader has other potentialuses, and to prevent the user of the StreamReader to accidentallycall inappropriate methods of the protocol.)"""def __init__(self, stream_reader, client_connected_cb=None, loop=None):super().__init__(loop=loop)self._stream_reader = stream_readerself._stream_writer = Noneself._client_connected_cb = client_connected_cbself._over_ssl = Falseself._closed = self._loop.create_future()def connection_made(self, transport):self._stream_reader.set_transport(transport)self._over_ssl = transport.get_extra_info('sslcontext') is not Noneif self._client_connected_cb is not None:self._stream_writer = StreamWriter(transport, self,self._stream_reader,self._loop)res = self._client_connected_cb(self._stream_reader,self._stream_writer)if coroutines.iscoroutine(res):self._loop.create_task(res)def connection_lost(self, exc):if self._stream_reader is not None:if exc is None:self._stream_reader.feed_eof()else:self._stream_reader.set_exception(exc)if not self._closed.done():if exc is None:self._closed.set_result(None)else:self._closed.set_exception(exc)super().connection_lost(exc)self._stream_reader = Noneself._stream_writer = Nonedef data_received(self, data):self._stream_reader.feed_data(data)def eof_received(self):self._stream_reader.feed_eof()if self._over_ssl:# Prevent a warning in SSLProtocol.eof_received:# "returning true from eof_received()# has no effect when using ssl"return Falsereturn Truedef __del__(self):# Prevent reports about unhandled exceptions.# Better than self._closed._log_traceback = False hackclosed = self._closedif closed.done() and not closed.cancelled():closed.exception()class StreamWriter:"""Wraps a Transport.This exposes write(), writelines(), [can_]write_eof(),get_extra_info() and close(). It adds drain() which returns anoptional Future on which you can wait for flow control. It alsoadds a transport property which references the Transportdirectly."""def __init__(self, transport, protocol, reader, loop):self._transport = transportself._protocol = protocol# drain() expects that the reader has an exception() methodassert reader is None or isinstance(reader, StreamReader)self._reader = readerself._loop = loopdef __repr__(self):info = [self.__class__.__name__, f'transport={self._transport!r}']if self._reader is not None:info.append(f'reader={self._reader!r}')return '<{}>'.format(' '.join(info))@propertydef transport(self):return self._transportdef write(self, data):self._transport.write(data)def writelines(self, data):self._transport.writelines(data)def write_eof(self):return self._transport.write_eof()def can_write_eof(self):return self._transport.can_write_eof()def close(self):return self._transport.close()def is_closing(self):return self._transport.is_closing()async def wait_closed(self):await self._protocol._closeddef get_extra_info(self, name, default=None):return self._transport.get_extra_info(name, default)async def drain(self):"""Flush the write buffer.The intended use is to writew.write(data)await w.drain()"""if self._reader is not None:exc = self._reader.exception()if exc is not None:raise excif self._transport.is_closing():# Yield to the event loop so connection_lost() may be# called. Without this, _drain_helper() would return# immediately, and code that calls# write(...); await drain()# in a loop would never call connection_lost(), so it# would not see an error when the socket is closed.await sleep(0, loop=self._loop)await self._protocol._drain_helper()class StreamReader:def __init__(self, limit=_DEFAULT_LIMIT, loop=None):# The line length limit is a security feature;# it also doubles as half the buffer limit.if limit <= 0:raise ValueError('Limit cannot be <= 0')self._limit = limitif loop is None:self._loop = events.get_event_loop()else:self._loop = loopself._buffer = bytearray()self._eof = False # Whether we're done.self._waiter = None # A future used by _wait_for_data()self._exception = Noneself._transport = Noneself._paused = Falsedef __repr__(self):info = ['StreamReader']if self._buffer:info.append(f'{len(self._buffer)} bytes')if self._eof:info.append('eof')if self._limit != _DEFAULT_LIMIT:info.append(f'limit={self._limit}')if self._waiter:info.append(f'waiter={self._waiter!r}')if self._exception:info.append(f'exception={self._exception!r}')if self._transport:info.append(f'transport={self._transport!r}')if self._paused:info.append('paused')return '<{}>'.format(' '.join(info))def exception(self):return self._exceptiondef set_exception(self, exc):self._exception = excwaiter = self._waiterif waiter is not None:self._waiter = Noneif not waiter.cancelled():waiter.set_exception(exc)def _wakeup_waiter(self):"""Wakeup read*() functions waiting for data or EOF."""waiter = self._waiterif waiter is not None:self._waiter = Noneif not waiter.cancelled():waiter.set_result(None)def set_transport(self, transport):assert self._transport is None, 'Transport already set'self._transport = transportdef _maybe_resume_transport(self):if self._paused and len(self._buffer) <= self._limit:self._paused = Falseself._transport.resume_reading()def feed_eof(self):self._eof = Trueself._wakeup_waiter()def at_eof(self):"""Return True if the buffer is empty and 'feed_eof' was called."""return self._eof and not self._bufferdef feed_data(self, data):assert not self._eof, 'feed_data after feed_eof'if not data:returnself._buffer.extend(data)self._wakeup_waiter()if (self._transport is not None andnot self._paused andlen(self._buffer) > 2 * self._limit):try:self._transport.pause_reading()except NotImplementedError:# The transport can't be paused.# We'll just have to buffer all data.# Forget the transport so we don't keep trying.self._transport = Noneelse:self._paused = Trueasync def _wait_for_data(self, func_name):"""Wait until feed_data() or feed_eof() is called.If stream was paused, automatically resume it."""# StreamReader uses a future to link the protocol feed_data() method# to a read coroutine. Running two read coroutines at the same time# would have an unexpected behaviour. It would not possible to know# which coroutine would get the next data.if self._waiter is not None:raise RuntimeError(f'{func_name}() called while another coroutine is 'f'already waiting for incoming data')assert not self._eof, '_wait_for_data after EOF'# Waiting for data while paused will make deadlock, so prevent it.# This is essential for readexactly(n) for case when n > self._limit.if self._paused:self._paused = Falseself._transport.resume_reading()self._waiter = self._loop.create_future()try:await self._waiterfinally:self._waiter = Noneasync def readline(self):"""Read chunk of data from the stream until newline (b'\n') is found.On success, return chunk that ends with newline. If only partialline can be read due to EOF, return incomplete line withoutterminating newline. When EOF was reached while no bytes read, emptybytes object is returned.If limit is reached, ValueError will be raised. In that case, ifnewline was found, complete line including newline will be removedfrom internal buffer. Else, internal buffer will be cleared. Limit iscompared against part of the line without newline.If stream was paused, this function will automatically resume it ifneeded."""sep = b'\n'seplen = len(sep)try:line = await self.readuntil(sep)except IncompleteReadError as e:return e.partialexcept LimitOverrunError as e:if self._buffer.startswith(sep, e.consumed):del self._buffer[:e.consumed + seplen]else:self._buffer.clear()self._maybe_resume_transport()raise ValueError(e.args[0])return lineasync def readuntil(self, separator=b'\n'):"""Read data from the stream until ``separator`` is found.On success, the data and separator will be removed from theinternal buffer (consumed). Returned data will include theseparator at the end.Configured stream limit is used to check result. Limit sets themaximal length of data that can be returned, not counting theseparator.If an EOF occurs and the complete separator is still not found,an IncompleteReadError exception will be raised, and the internalbuffer will be reset. The IncompleteReadError.partial attributemay contain the separator partially.If the data cannot be read because of over limit, aLimitOverrunError exception will be raised, and the datawill be left in the internal buffer, so it can be read again."""seplen = len(separator)if seplen == 0:raise ValueError('Separator should be at least one-byte string')if self._exception is not None:raise self._exception# Consume whole buffer except last bytes, which length is# one less than seplen. Let's check corner cases with# separator='SEPARATOR':# * we have received almost complete separator (without last# byte). i.e buffer='some textSEPARATO'. In this case we# can safely consume len(separator) - 1 bytes.# * last byte of buffer is first byte of separator, i.e.# buffer='abcdefghijklmnopqrS'. We may safely consume# everything except that last byte, but this require to# analyze bytes of buffer that match partial separator.# This is slow and/or require FSM. For this case our# implementation is not optimal, since require rescanning# of data that is known to not belong to separator. In# real world, separator will not be so long to notice# performance problems. Even when reading MIME-encoded# messages :)# `offset` is the number of bytes from the beginning of the buffer# where there is no occurrence of `separator`.offset = 0# Loop until we find `separator` in the buffer, exceed the buffer size,# or an EOF has happened.while True:buflen = len(self._buffer)# Check if we now have enough data in the buffer for `separator` to# fit.if buflen - offset >= seplen:isep = self._buffer.find(separator, offset)if isep != -1:# `separator` is in the buffer. `isep` will be used later# to retrieve the data.break# see upper comment for explanation.offset = buflen + 1 - seplenif offset > self._limit:raise LimitOverrunError('Separator is not found, and chunk exceed the limit',offset)# Complete message (with full separator) may be present in buffer# even when EOF flag is set. This may happen when the last chunk# adds data which makes separator be found. That's why we check for# EOF *ater* inspecting the buffer.if self._eof:chunk = bytes(self._buffer)self._buffer.clear()raise IncompleteReadError(chunk, None)# _wait_for_data() will resume reading if stream was paused.await self._wait_for_data('readuntil')if isep > self._limit:raise LimitOverrunError('Separator is found, but chunk is longer than limit', isep)chunk = self._buffer[:isep + seplen]del self._buffer[:isep + seplen]self._maybe_resume_transport()return bytes(chunk)async def read(self, n=-1):"""Read up to `n` bytes from the stream.If n is not provided, or set to -1, read until EOF and return all readbytes. If the EOF was received and the internal buffer is empty, returnan empty bytes object.If n is zero, return empty bytes object immediately.If n is positive, this function try to read `n` bytes, and may returnless or equal bytes than requested, but at least one byte. If EOF wasreceived before any byte is read, this function returns empty byteobject.Returned value is not limited with limit, configured at streamcreation.If stream was paused, this function will automatically resume it ifneeded."""if self._exception is not None:raise self._exceptionif n == 0:return b''if n < 0:# This used to just loop creating a new waiter hoping to# collect everything in self._buffer, but that would# deadlock if the subprocess sends more than self.limit# bytes. So just call self.read(self._limit) until EOF.blocks = []while True:block = await self.read(self._limit)if not block:breakblocks.append(block)return b''.join(blocks)if not self._buffer and not self._eof:await self._wait_for_data('read')# This will work right even if buffer is less than n bytesdata = bytes(self._buffer[:n])del self._buffer[:n]self._maybe_resume_transport()return dataasync def readexactly(self, n):"""Read exactly `n` bytes.Raise an IncompleteReadError if EOF is reached before `n` bytes can beread. The IncompleteReadError.partial attribute of the exception willcontain the partial read bytes.if n is zero, return empty bytes object.Returned value is not limited with limit, configured at streamcreation.If stream was paused, this function will automatically resume it ifneeded."""if n < 0:raise ValueError('readexactly size can not be less than zero')if self._exception is not None:raise self._exceptionif n == 0:return b''while len(self._buffer) < n:if self._eof:incomplete = bytes(self._buffer)self._buffer.clear()raise IncompleteReadError(incomplete, n)await self._wait_for_data('readexactly')if len(self._buffer) == n:data = bytes(self._buffer)self._buffer.clear()else:data = bytes(self._buffer[:n])del self._buffer[:n]self._maybe_resume_transport()return datadef __aiter__(self):return selfasync def __anext__(self):val = await self.readline()if val == b'':raise StopAsyncIterationreturn val
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。