id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,800
tornadoweb/tornado
tornado/iostream.py
BaseIOStream._read_from_buffer
def _read_from_buffer(self, pos: int) -> None: """Attempts to complete the currently-pending read from the buffer. The argument is either a position in the read buffer or None, as returned by _find_read_pos. """ self._read_bytes = self._read_delimiter = self._read_regex = None self._read_partial = False self._finish_read(pos, False)
python
def _read_from_buffer(self, pos: int) -> None: """Attempts to complete the currently-pending read from the buffer. The argument is either a position in the read buffer or None, as returned by _find_read_pos. """ self._read_bytes = self._read_delimiter = self._read_regex = None self._read_partial = False self._finish_read(pos, False)
[ "def", "_read_from_buffer", "(", "self", ",", "pos", ":", "int", ")", "->", "None", ":", "self", ".", "_read_bytes", "=", "self", ".", "_read_delimiter", "=", "self", ".", "_read_regex", "=", "None", "self", ".", "_read_partial", "=", "False", "self", ".", "_finish_read", "(", "pos", ",", "False", ")" ]
Attempts to complete the currently-pending read from the buffer. The argument is either a position in the read buffer or None, as returned by _find_read_pos.
[ "Attempts", "to", "complete", "the", "currently", "-", "pending", "read", "from", "the", "buffer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L887-L895
26,801
tornadoweb/tornado
tornado/iostream.py
BaseIOStream._find_read_pos
def _find_read_pos(self) -> Optional[int]: """Attempts to find a position in the read buffer that satisfies the currently-pending read. Returns a position in the buffer if the current read can be satisfied, or None if it cannot. """ if self._read_bytes is not None and ( self._read_buffer_size >= self._read_bytes or (self._read_partial and self._read_buffer_size > 0) ): num_bytes = min(self._read_bytes, self._read_buffer_size) return num_bytes elif self._read_delimiter is not None: # Multi-byte delimiters (e.g. '\r\n') may straddle two # chunks in the read buffer, so we can't easily find them # without collapsing the buffer. However, since protocols # using delimited reads (as opposed to reads of a known # length) tend to be "line" oriented, the delimiter is likely # to be in the first few chunks. Merge the buffer gradually # since large merges are relatively expensive and get undone in # _consume(). if self._read_buffer: loc = self._read_buffer.find( self._read_delimiter, self._read_buffer_pos ) if loc != -1: loc -= self._read_buffer_pos delimiter_len = len(self._read_delimiter) self._check_max_bytes(self._read_delimiter, loc + delimiter_len) return loc + delimiter_len self._check_max_bytes(self._read_delimiter, self._read_buffer_size) elif self._read_regex is not None: if self._read_buffer: m = self._read_regex.search(self._read_buffer, self._read_buffer_pos) if m is not None: loc = m.end() - self._read_buffer_pos self._check_max_bytes(self._read_regex, loc) return loc self._check_max_bytes(self._read_regex, self._read_buffer_size) return None
python
def _find_read_pos(self) -> Optional[int]: """Attempts to find a position in the read buffer that satisfies the currently-pending read. Returns a position in the buffer if the current read can be satisfied, or None if it cannot. """ if self._read_bytes is not None and ( self._read_buffer_size >= self._read_bytes or (self._read_partial and self._read_buffer_size > 0) ): num_bytes = min(self._read_bytes, self._read_buffer_size) return num_bytes elif self._read_delimiter is not None: # Multi-byte delimiters (e.g. '\r\n') may straddle two # chunks in the read buffer, so we can't easily find them # without collapsing the buffer. However, since protocols # using delimited reads (as opposed to reads of a known # length) tend to be "line" oriented, the delimiter is likely # to be in the first few chunks. Merge the buffer gradually # since large merges are relatively expensive and get undone in # _consume(). if self._read_buffer: loc = self._read_buffer.find( self._read_delimiter, self._read_buffer_pos ) if loc != -1: loc -= self._read_buffer_pos delimiter_len = len(self._read_delimiter) self._check_max_bytes(self._read_delimiter, loc + delimiter_len) return loc + delimiter_len self._check_max_bytes(self._read_delimiter, self._read_buffer_size) elif self._read_regex is not None: if self._read_buffer: m = self._read_regex.search(self._read_buffer, self._read_buffer_pos) if m is not None: loc = m.end() - self._read_buffer_pos self._check_max_bytes(self._read_regex, loc) return loc self._check_max_bytes(self._read_regex, self._read_buffer_size) return None
[ "def", "_find_read_pos", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "if", "self", ".", "_read_bytes", "is", "not", "None", "and", "(", "self", ".", "_read_buffer_size", ">=", "self", ".", "_read_bytes", "or", "(", "self", ".", "_read_partial", "and", "self", ".", "_read_buffer_size", ">", "0", ")", ")", ":", "num_bytes", "=", "min", "(", "self", ".", "_read_bytes", ",", "self", ".", "_read_buffer_size", ")", "return", "num_bytes", "elif", "self", ".", "_read_delimiter", "is", "not", "None", ":", "# Multi-byte delimiters (e.g. '\\r\\n') may straddle two", "# chunks in the read buffer, so we can't easily find them", "# without collapsing the buffer. However, since protocols", "# using delimited reads (as opposed to reads of a known", "# length) tend to be \"line\" oriented, the delimiter is likely", "# to be in the first few chunks. Merge the buffer gradually", "# since large merges are relatively expensive and get undone in", "# _consume().", "if", "self", ".", "_read_buffer", ":", "loc", "=", "self", ".", "_read_buffer", ".", "find", "(", "self", ".", "_read_delimiter", ",", "self", ".", "_read_buffer_pos", ")", "if", "loc", "!=", "-", "1", ":", "loc", "-=", "self", ".", "_read_buffer_pos", "delimiter_len", "=", "len", "(", "self", ".", "_read_delimiter", ")", "self", ".", "_check_max_bytes", "(", "self", ".", "_read_delimiter", ",", "loc", "+", "delimiter_len", ")", "return", "loc", "+", "delimiter_len", "self", ".", "_check_max_bytes", "(", "self", ".", "_read_delimiter", ",", "self", ".", "_read_buffer_size", ")", "elif", "self", ".", "_read_regex", "is", "not", "None", ":", "if", "self", ".", "_read_buffer", ":", "m", "=", "self", ".", "_read_regex", ".", "search", "(", "self", ".", "_read_buffer", ",", "self", ".", "_read_buffer_pos", ")", "if", "m", "is", "not", "None", ":", "loc", "=", "m", ".", "end", "(", ")", "-", "self", ".", "_read_buffer_pos", "self", ".", "_check_max_bytes", "(", "self", ".", "_read_regex", ",", "loc", ")", "return", "loc", "self", ".", "_check_max_bytes", "(", "self", ".", "_read_regex", ",", "self", ".", "_read_buffer_size", ")", "return", "None" ]
Attempts to find a position in the read buffer that satisfies the currently-pending read. Returns a position in the buffer if the current read can be satisfied, or None if it cannot.
[ "Attempts", "to", "find", "a", "position", "in", "the", "read", "buffer", "that", "satisfies", "the", "currently", "-", "pending", "read", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L897-L937
26,802
tornadoweb/tornado
tornado/iostream.py
BaseIOStream._is_connreset
def _is_connreset(self, exc: BaseException) -> bool: """Return ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses. """ return ( isinstance(exc, (socket.error, IOError)) and errno_from_exception(exc) in _ERRNO_CONNRESET )
python
def _is_connreset(self, exc: BaseException) -> bool: """Return ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses. """ return ( isinstance(exc, (socket.error, IOError)) and errno_from_exception(exc) in _ERRNO_CONNRESET )
[ "def", "_is_connreset", "(", "self", ",", "exc", ":", "BaseException", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "exc", ",", "(", "socket", ".", "error", ",", "IOError", ")", ")", "and", "errno_from_exception", "(", "exc", ")", "in", "_ERRNO_CONNRESET", ")" ]
Return ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses.
[ "Return", "True", "if", "exc", "is", "ECONNRESET", "or", "equivalent", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L1054-L1062
26,803
tornadoweb/tornado
tornado/iostream.py
IOStream.connect
def connect( self: _IOStreamType, address: tuple, server_hostname: str = None ) -> "Future[_IOStreamType]": """Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ self._connecting = True future = Future() # type: Future[_IOStreamType] self._connect_future = typing.cast("Future[IOStream]", future) try: self.socket.connect(address) except socket.error as e: # In non-blocking mode we expect connect() to raise an # exception with EINPROGRESS or EWOULDBLOCK. # # On freebsd, other errors such as ECONNREFUSED may be # returned immediately when attempting to connect to # localhost, so handle them the same way as an error # reported later in _handle_connect. if ( errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK ): if future is None: gen_log.warning( "Connect error on fd %s: %s", self.socket.fileno(), e ) self.close(exc_info=e) return future self._add_io_state(self.io_loop.WRITE) return future
python
def connect( self: _IOStreamType, address: tuple, server_hostname: str = None ) -> "Future[_IOStreamType]": """Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ self._connecting = True future = Future() # type: Future[_IOStreamType] self._connect_future = typing.cast("Future[IOStream]", future) try: self.socket.connect(address) except socket.error as e: # In non-blocking mode we expect connect() to raise an # exception with EINPROGRESS or EWOULDBLOCK. # # On freebsd, other errors such as ECONNREFUSED may be # returned immediately when attempting to connect to # localhost, so handle them the same way as an error # reported later in _handle_connect. if ( errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK ): if future is None: gen_log.warning( "Connect error on fd %s: %s", self.socket.fileno(), e ) self.close(exc_info=e) return future self._add_io_state(self.io_loop.WRITE) return future
[ "def", "connect", "(", "self", ":", "_IOStreamType", ",", "address", ":", "tuple", ",", "server_hostname", ":", "str", "=", "None", ")", "->", "\"Future[_IOStreamType]\"", ":", "self", ".", "_connecting", "=", "True", "future", "=", "Future", "(", ")", "# type: Future[_IOStreamType]", "self", ".", "_connect_future", "=", "typing", ".", "cast", "(", "\"Future[IOStream]\"", ",", "future", ")", "try", ":", "self", ".", "socket", ".", "connect", "(", "address", ")", "except", "socket", ".", "error", "as", "e", ":", "# In non-blocking mode we expect connect() to raise an", "# exception with EINPROGRESS or EWOULDBLOCK.", "#", "# On freebsd, other errors such as ECONNREFUSED may be", "# returned immediately when attempting to connect to", "# localhost, so handle them the same way as an error", "# reported later in _handle_connect.", "if", "(", "errno_from_exception", "(", "e", ")", "not", "in", "_ERRNO_INPROGRESS", "and", "errno_from_exception", "(", "e", ")", "not", "in", "_ERRNO_WOULDBLOCK", ")", ":", "if", "future", "is", "None", ":", "gen_log", ".", "warning", "(", "\"Connect error on fd %s: %s\"", ",", "self", ".", "socket", ".", "fileno", "(", ")", ",", "e", ")", "self", ".", "close", "(", "exc_info", "=", "e", ")", "return", "future", "self", ".", "_add_io_state", "(", "self", ".", "io_loop", ".", "WRITE", ")", "return", "future" ]
Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)`` tuple. Hostnames are accepted here, but will be resolved synchronously and block the IOLoop. If you have a hostname instead of an IP address, the `.TCPClient` class is recommended instead of calling this method directly. `.TCPClient` will do asynchronous DNS resolution and handle both IPv4 and IPv6. If ``callback`` is specified, it will be called with no arguments when the connection is completed; if not this method returns a `.Future` (whose result after a successful connection will be the stream itself). In SSL mode, the ``server_hostname`` parameter will be used for certificate validation (unless disabled in the ``ssl_options``) and SNI (if supported; requires Python 2.7.9+). Note that it is safe to call `IOStream.write <BaseIOStream.write>` while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling `IOStream` read methods before the socket is connected works on some platforms but is non-portable. .. versionchanged:: 4.0 If no callback is given, returns a `.Future`. .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to the `SSLIOStream` constructor to disable. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
[ "Connects", "the", "socket", "to", "a", "remote", "address", "without", "blocking", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L1148-L1219
26,804
tornadoweb/tornado
tornado/iostream.py
IOStream.start_tls
def start_tls( self, server_side: bool, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, server_hostname: str = None, ) -> Awaitable["SSLIOStream"]: """Convert this `IOStream` to an `SSLIOStream`. This enables protocols that begin in clear-text mode and switch to SSL after some initial negotiation (such as the ``STARTTLS`` extension to SMTP and IMAP). This method cannot be used if there are outstanding reads or writes on the stream, or if there is any data in the IOStream's buffer (data in the operating system's socket buffer is allowed). This means it must generally be used immediately after reading or writing the last clear-text data. It can also be used immediately after connecting, before any reads or writes. The ``ssl_options`` argument may be either an `ssl.SSLContext` object or a dictionary of keyword arguments for the `ssl.wrap_socket` function. The ``server_hostname`` argument will be used for certificate validation unless disabled in the ``ssl_options``. This method returns a `.Future` whose result is the new `SSLIOStream`. After this method has been called, any other operation on the original stream is undefined. If a close callback is defined on this stream, it will be transferred to the new stream. .. versionadded:: 4.0 .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to disable. """ if ( self._read_future or self._write_futures or self._connect_future or self._closed or self._read_buffer or self._write_buffer ): raise ValueError("IOStream is not idle; cannot convert to SSL") if ssl_options is None: if server_side: ssl_options = _server_ssl_defaults else: ssl_options = _client_ssl_defaults socket = self.socket self.io_loop.remove_handler(socket) self.socket = None # type: ignore socket = ssl_wrap_socket( socket, ssl_options, server_hostname=server_hostname, server_side=server_side, do_handshake_on_connect=False, ) orig_close_callback = self._close_callback self._close_callback = None future = Future() # type: Future[SSLIOStream] ssl_stream = SSLIOStream(socket, ssl_options=ssl_options) ssl_stream.set_close_callback(orig_close_callback) ssl_stream._ssl_connect_future = future ssl_stream.max_buffer_size = self.max_buffer_size ssl_stream.read_chunk_size = self.read_chunk_size return future
python
def start_tls( self, server_side: bool, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, server_hostname: str = None, ) -> Awaitable["SSLIOStream"]: """Convert this `IOStream` to an `SSLIOStream`. This enables protocols that begin in clear-text mode and switch to SSL after some initial negotiation (such as the ``STARTTLS`` extension to SMTP and IMAP). This method cannot be used if there are outstanding reads or writes on the stream, or if there is any data in the IOStream's buffer (data in the operating system's socket buffer is allowed). This means it must generally be used immediately after reading or writing the last clear-text data. It can also be used immediately after connecting, before any reads or writes. The ``ssl_options`` argument may be either an `ssl.SSLContext` object or a dictionary of keyword arguments for the `ssl.wrap_socket` function. The ``server_hostname`` argument will be used for certificate validation unless disabled in the ``ssl_options``. This method returns a `.Future` whose result is the new `SSLIOStream`. After this method has been called, any other operation on the original stream is undefined. If a close callback is defined on this stream, it will be transferred to the new stream. .. versionadded:: 4.0 .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to disable. """ if ( self._read_future or self._write_futures or self._connect_future or self._closed or self._read_buffer or self._write_buffer ): raise ValueError("IOStream is not idle; cannot convert to SSL") if ssl_options is None: if server_side: ssl_options = _server_ssl_defaults else: ssl_options = _client_ssl_defaults socket = self.socket self.io_loop.remove_handler(socket) self.socket = None # type: ignore socket = ssl_wrap_socket( socket, ssl_options, server_hostname=server_hostname, server_side=server_side, do_handshake_on_connect=False, ) orig_close_callback = self._close_callback self._close_callback = None future = Future() # type: Future[SSLIOStream] ssl_stream = SSLIOStream(socket, ssl_options=ssl_options) ssl_stream.set_close_callback(orig_close_callback) ssl_stream._ssl_connect_future = future ssl_stream.max_buffer_size = self.max_buffer_size ssl_stream.read_chunk_size = self.read_chunk_size return future
[ "def", "start_tls", "(", "self", ",", "server_side", ":", "bool", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "ssl", ".", "SSLContext", "]", "=", "None", ",", "server_hostname", ":", "str", "=", "None", ",", ")", "->", "Awaitable", "[", "\"SSLIOStream\"", "]", ":", "if", "(", "self", ".", "_read_future", "or", "self", ".", "_write_futures", "or", "self", ".", "_connect_future", "or", "self", ".", "_closed", "or", "self", ".", "_read_buffer", "or", "self", ".", "_write_buffer", ")", ":", "raise", "ValueError", "(", "\"IOStream is not idle; cannot convert to SSL\"", ")", "if", "ssl_options", "is", "None", ":", "if", "server_side", ":", "ssl_options", "=", "_server_ssl_defaults", "else", ":", "ssl_options", "=", "_client_ssl_defaults", "socket", "=", "self", ".", "socket", "self", ".", "io_loop", ".", "remove_handler", "(", "socket", ")", "self", ".", "socket", "=", "None", "# type: ignore", "socket", "=", "ssl_wrap_socket", "(", "socket", ",", "ssl_options", ",", "server_hostname", "=", "server_hostname", ",", "server_side", "=", "server_side", ",", "do_handshake_on_connect", "=", "False", ",", ")", "orig_close_callback", "=", "self", ".", "_close_callback", "self", ".", "_close_callback", "=", "None", "future", "=", "Future", "(", ")", "# type: Future[SSLIOStream]", "ssl_stream", "=", "SSLIOStream", "(", "socket", ",", "ssl_options", "=", "ssl_options", ")", "ssl_stream", ".", "set_close_callback", "(", "orig_close_callback", ")", "ssl_stream", ".", "_ssl_connect_future", "=", "future", "ssl_stream", ".", "max_buffer_size", "=", "self", ".", "max_buffer_size", "ssl_stream", ".", "read_chunk_size", "=", "self", ".", "read_chunk_size", "return", "future" ]
Convert this `IOStream` to an `SSLIOStream`. This enables protocols that begin in clear-text mode and switch to SSL after some initial negotiation (such as the ``STARTTLS`` extension to SMTP and IMAP). This method cannot be used if there are outstanding reads or writes on the stream, or if there is any data in the IOStream's buffer (data in the operating system's socket buffer is allowed). This means it must generally be used immediately after reading or writing the last clear-text data. It can also be used immediately after connecting, before any reads or writes. The ``ssl_options`` argument may be either an `ssl.SSLContext` object or a dictionary of keyword arguments for the `ssl.wrap_socket` function. The ``server_hostname`` argument will be used for certificate validation unless disabled in the ``ssl_options``. This method returns a `.Future` whose result is the new `SSLIOStream`. After this method has been called, any other operation on the original stream is undefined. If a close callback is defined on this stream, it will be transferred to the new stream. .. versionadded:: 4.0 .. versionchanged:: 4.2 SSL certificates are validated by default; pass ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a suitably-configured `ssl.SSLContext` to disable.
[ "Convert", "this", "IOStream", "to", "an", "SSLIOStream", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L1221-L1295
26,805
tornadoweb/tornado
tornado/iostream.py
SSLIOStream._verify_cert
def _verify_cert(self, peercert: Any) -> bool: """Returns ``True`` if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname. """ if isinstance(self._ssl_options, dict): verify_mode = self._ssl_options.get("cert_reqs", ssl.CERT_NONE) elif isinstance(self._ssl_options, ssl.SSLContext): verify_mode = self._ssl_options.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) if verify_mode == ssl.CERT_NONE or self._server_hostname is None: return True cert = self.socket.getpeercert() if cert is None and verify_mode == ssl.CERT_REQUIRED: gen_log.warning("No SSL certificate given") return False try: ssl.match_hostname(peercert, self._server_hostname) except ssl.CertificateError as e: gen_log.warning("Invalid SSL certificate: %s" % e) return False else: return True
python
def _verify_cert(self, peercert: Any) -> bool: """Returns ``True`` if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname. """ if isinstance(self._ssl_options, dict): verify_mode = self._ssl_options.get("cert_reqs", ssl.CERT_NONE) elif isinstance(self._ssl_options, ssl.SSLContext): verify_mode = self._ssl_options.verify_mode assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL) if verify_mode == ssl.CERT_NONE or self._server_hostname is None: return True cert = self.socket.getpeercert() if cert is None and verify_mode == ssl.CERT_REQUIRED: gen_log.warning("No SSL certificate given") return False try: ssl.match_hostname(peercert, self._server_hostname) except ssl.CertificateError as e: gen_log.warning("Invalid SSL certificate: %s" % e) return False else: return True
[ "def", "_verify_cert", "(", "self", ",", "peercert", ":", "Any", ")", "->", "bool", ":", "if", "isinstance", "(", "self", ".", "_ssl_options", ",", "dict", ")", ":", "verify_mode", "=", "self", ".", "_ssl_options", ".", "get", "(", "\"cert_reqs\"", ",", "ssl", ".", "CERT_NONE", ")", "elif", "isinstance", "(", "self", ".", "_ssl_options", ",", "ssl", ".", "SSLContext", ")", ":", "verify_mode", "=", "self", ".", "_ssl_options", ".", "verify_mode", "assert", "verify_mode", "in", "(", "ssl", ".", "CERT_NONE", ",", "ssl", ".", "CERT_REQUIRED", ",", "ssl", ".", "CERT_OPTIONAL", ")", "if", "verify_mode", "==", "ssl", ".", "CERT_NONE", "or", "self", ".", "_server_hostname", "is", "None", ":", "return", "True", "cert", "=", "self", ".", "socket", ".", "getpeercert", "(", ")", "if", "cert", "is", "None", "and", "verify_mode", "==", "ssl", ".", "CERT_REQUIRED", ":", "gen_log", ".", "warning", "(", "\"No SSL certificate given\"", ")", "return", "False", "try", ":", "ssl", ".", "match_hostname", "(", "peercert", ",", "self", ".", "_server_hostname", ")", "except", "ssl", ".", "CertificateError", "as", "e", ":", "gen_log", ".", "warning", "(", "\"Invalid SSL certificate: %s\"", "%", "e", ")", "return", "False", "else", ":", "return", "True" ]
Returns ``True`` if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname.
[ "Returns", "True", "if", "peercert", "is", "valid", "according", "to", "the", "configured", "validation", "mode", "and", "hostname", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L1442-L1467
26,806
tornadoweb/tornado
tornado/iostream.py
SSLIOStream.wait_for_handshake
def wait_for_handshake(self) -> "Future[SSLIOStream]": """Wait for the initial SSL handshake to complete. If a ``callback`` is given, it will be called with no arguments once the handshake is complete; otherwise this method returns a `.Future` which will resolve to the stream itself after the handshake is complete. Once the handshake is complete, information such as the peer's certificate and NPN/ALPN selections may be accessed on ``self.socket``. This method is intended for use on server-side streams or after using `IOStream.start_tls`; it should not be used with `IOStream.connect` (which already waits for the handshake to complete). It may only be called once per stream. .. versionadded:: 4.2 .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ if self._ssl_connect_future is not None: raise RuntimeError("Already waiting") future = self._ssl_connect_future = Future() if not self._ssl_accepting: self._finish_ssl_connect() return future
python
def wait_for_handshake(self) -> "Future[SSLIOStream]": """Wait for the initial SSL handshake to complete. If a ``callback`` is given, it will be called with no arguments once the handshake is complete; otherwise this method returns a `.Future` which will resolve to the stream itself after the handshake is complete. Once the handshake is complete, information such as the peer's certificate and NPN/ALPN selections may be accessed on ``self.socket``. This method is intended for use on server-side streams or after using `IOStream.start_tls`; it should not be used with `IOStream.connect` (which already waits for the handshake to complete). It may only be called once per stream. .. versionadded:: 4.2 .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ if self._ssl_connect_future is not None: raise RuntimeError("Already waiting") future = self._ssl_connect_future = Future() if not self._ssl_accepting: self._finish_ssl_connect() return future
[ "def", "wait_for_handshake", "(", "self", ")", "->", "\"Future[SSLIOStream]\"", ":", "if", "self", ".", "_ssl_connect_future", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"Already waiting\"", ")", "future", "=", "self", ".", "_ssl_connect_future", "=", "Future", "(", ")", "if", "not", "self", ".", "_ssl_accepting", ":", "self", ".", "_finish_ssl_connect", "(", ")", "return", "future" ]
Wait for the initial SSL handshake to complete. If a ``callback`` is given, it will be called with no arguments once the handshake is complete; otherwise this method returns a `.Future` which will resolve to the stream itself after the handshake is complete. Once the handshake is complete, information such as the peer's certificate and NPN/ALPN selections may be accessed on ``self.socket``. This method is intended for use on server-side streams or after using `IOStream.start_tls`; it should not be used with `IOStream.connect` (which already waits for the handshake to complete). It may only be called once per stream. .. versionadded:: 4.2 .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
[ "Wait", "for", "the", "initial", "SSL", "handshake", "to", "complete", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L1527-L1557
26,807
tornadoweb/tornado
tornado/log.py
enable_pretty_logging
def enable_pretty_logging(options: Any = None, logger: logging.Logger = None) -> None: """Turns on formatted logging output as configured. This is called automatically by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`. """ if options is None: import tornado.options options = tornado.options.options if options.logging is None or options.logging.lower() == "none": return if logger is None: logger = logging.getLogger() logger.setLevel(getattr(logging, options.logging.upper())) if options.log_file_prefix: rotate_mode = options.log_rotate_mode if rotate_mode == "size": channel = logging.handlers.RotatingFileHandler( filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups, encoding="utf-8", ) # type: logging.Handler elif rotate_mode == "time": channel = logging.handlers.TimedRotatingFileHandler( filename=options.log_file_prefix, when=options.log_rotate_when, interval=options.log_rotate_interval, backupCount=options.log_file_num_backups, encoding="utf-8", ) else: error_message = ( "The value of log_rotate_mode option should be " + '"size" or "time", not "%s".' % rotate_mode ) raise ValueError(error_message) channel.setFormatter(LogFormatter(color=False)) logger.addHandler(channel) if options.log_to_stderr or (options.log_to_stderr is None and not logger.handlers): # Set up color if we are in a tty and curses is installed channel = logging.StreamHandler() channel.setFormatter(LogFormatter()) logger.addHandler(channel)
python
def enable_pretty_logging(options: Any = None, logger: logging.Logger = None) -> None: """Turns on formatted logging output as configured. This is called automatically by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`. """ if options is None: import tornado.options options = tornado.options.options if options.logging is None or options.logging.lower() == "none": return if logger is None: logger = logging.getLogger() logger.setLevel(getattr(logging, options.logging.upper())) if options.log_file_prefix: rotate_mode = options.log_rotate_mode if rotate_mode == "size": channel = logging.handlers.RotatingFileHandler( filename=options.log_file_prefix, maxBytes=options.log_file_max_size, backupCount=options.log_file_num_backups, encoding="utf-8", ) # type: logging.Handler elif rotate_mode == "time": channel = logging.handlers.TimedRotatingFileHandler( filename=options.log_file_prefix, when=options.log_rotate_when, interval=options.log_rotate_interval, backupCount=options.log_file_num_backups, encoding="utf-8", ) else: error_message = ( "The value of log_rotate_mode option should be " + '"size" or "time", not "%s".' % rotate_mode ) raise ValueError(error_message) channel.setFormatter(LogFormatter(color=False)) logger.addHandler(channel) if options.log_to_stderr or (options.log_to_stderr is None and not logger.handlers): # Set up color if we are in a tty and curses is installed channel = logging.StreamHandler() channel.setFormatter(LogFormatter()) logger.addHandler(channel)
[ "def", "enable_pretty_logging", "(", "options", ":", "Any", "=", "None", ",", "logger", ":", "logging", ".", "Logger", "=", "None", ")", "->", "None", ":", "if", "options", "is", "None", ":", "import", "tornado", ".", "options", "options", "=", "tornado", ".", "options", ".", "options", "if", "options", ".", "logging", "is", "None", "or", "options", ".", "logging", ".", "lower", "(", ")", "==", "\"none\"", ":", "return", "if", "logger", "is", "None", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "setLevel", "(", "getattr", "(", "logging", ",", "options", ".", "logging", ".", "upper", "(", ")", ")", ")", "if", "options", ".", "log_file_prefix", ":", "rotate_mode", "=", "options", ".", "log_rotate_mode", "if", "rotate_mode", "==", "\"size\"", ":", "channel", "=", "logging", ".", "handlers", ".", "RotatingFileHandler", "(", "filename", "=", "options", ".", "log_file_prefix", ",", "maxBytes", "=", "options", ".", "log_file_max_size", ",", "backupCount", "=", "options", ".", "log_file_num_backups", ",", "encoding", "=", "\"utf-8\"", ",", ")", "# type: logging.Handler", "elif", "rotate_mode", "==", "\"time\"", ":", "channel", "=", "logging", ".", "handlers", ".", "TimedRotatingFileHandler", "(", "filename", "=", "options", ".", "log_file_prefix", ",", "when", "=", "options", ".", "log_rotate_when", ",", "interval", "=", "options", ".", "log_rotate_interval", ",", "backupCount", "=", "options", ".", "log_file_num_backups", ",", "encoding", "=", "\"utf-8\"", ",", ")", "else", ":", "error_message", "=", "(", "\"The value of log_rotate_mode option should be \"", "+", "'\"size\" or \"time\", not \"%s\".'", "%", "rotate_mode", ")", "raise", "ValueError", "(", "error_message", ")", "channel", ".", "setFormatter", "(", "LogFormatter", "(", "color", "=", "False", ")", ")", "logger", ".", "addHandler", "(", "channel", ")", "if", "options", ".", "log_to_stderr", "or", "(", "options", ".", "log_to_stderr", "is", "None", "and", "not", "logger", ".", "handlers", ")", ":", "# Set up color if we are in a tty and curses is installed", "channel", "=", "logging", ".", "StreamHandler", "(", ")", "channel", ".", "setFormatter", "(", "LogFormatter", "(", ")", ")", "logger", ".", "addHandler", "(", "channel", ")" ]
Turns on formatted logging output as configured. This is called automatically by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`.
[ "Turns", "on", "formatted", "logging", "output", "as", "configured", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/log.py#L211-L256
26,808
tornadoweb/tornado
tornado/log.py
define_logging_options
def define_logging_options(options: Any = None) -> None: """Add logging-related flags to ``options``. These options are present automatically on the default options instance; this method is only necessary if you have created your own `.OptionParser`. .. versionadded:: 4.2 This function existed in prior versions but was broken and undocumented until 4.2. """ if options is None: # late import to prevent cycle import tornado.options options = tornado.options.options options.define( "logging", default="info", help=( "Set the Python log level. If 'none', tornado won't touch the " "logging configuration." ), metavar="debug|info|warning|error|none", ) options.define( "log_to_stderr", type=bool, default=None, help=( "Send log output to stderr (colorized if possible). " "By default use stderr if --log_file_prefix is not set and " "no other logging is configured." ), ) options.define( "log_file_prefix", type=str, default=None, metavar="PATH", help=( "Path prefix for log files. " "Note that if you are running multiple tornado processes, " "log_file_prefix must be different for each of them (e.g. " "include the port number)" ), ) options.define( "log_file_max_size", type=int, default=100 * 1000 * 1000, help="max size of log files before rollover", ) options.define( "log_file_num_backups", type=int, default=10, help="number of log files to keep" ) options.define( "log_rotate_when", type=str, default="midnight", help=( "specify the type of TimedRotatingFileHandler interval " "other options:('S', 'M', 'H', 'D', 'W0'-'W6')" ), ) options.define( "log_rotate_interval", type=int, default=1, help="The interval value of timed rotating", ) options.define( "log_rotate_mode", type=str, default="size", help="The mode of rotating files(time or size)", ) options.add_parse_callback(lambda: enable_pretty_logging(options))
python
def define_logging_options(options: Any = None) -> None: """Add logging-related flags to ``options``. These options are present automatically on the default options instance; this method is only necessary if you have created your own `.OptionParser`. .. versionadded:: 4.2 This function existed in prior versions but was broken and undocumented until 4.2. """ if options is None: # late import to prevent cycle import tornado.options options = tornado.options.options options.define( "logging", default="info", help=( "Set the Python log level. If 'none', tornado won't touch the " "logging configuration." ), metavar="debug|info|warning|error|none", ) options.define( "log_to_stderr", type=bool, default=None, help=( "Send log output to stderr (colorized if possible). " "By default use stderr if --log_file_prefix is not set and " "no other logging is configured." ), ) options.define( "log_file_prefix", type=str, default=None, metavar="PATH", help=( "Path prefix for log files. " "Note that if you are running multiple tornado processes, " "log_file_prefix must be different for each of them (e.g. " "include the port number)" ), ) options.define( "log_file_max_size", type=int, default=100 * 1000 * 1000, help="max size of log files before rollover", ) options.define( "log_file_num_backups", type=int, default=10, help="number of log files to keep" ) options.define( "log_rotate_when", type=str, default="midnight", help=( "specify the type of TimedRotatingFileHandler interval " "other options:('S', 'M', 'H', 'D', 'W0'-'W6')" ), ) options.define( "log_rotate_interval", type=int, default=1, help="The interval value of timed rotating", ) options.define( "log_rotate_mode", type=str, default="size", help="The mode of rotating files(time or size)", ) options.add_parse_callback(lambda: enable_pretty_logging(options))
[ "def", "define_logging_options", "(", "options", ":", "Any", "=", "None", ")", "->", "None", ":", "if", "options", "is", "None", ":", "# late import to prevent cycle", "import", "tornado", ".", "options", "options", "=", "tornado", ".", "options", ".", "options", "options", ".", "define", "(", "\"logging\"", ",", "default", "=", "\"info\"", ",", "help", "=", "(", "\"Set the Python log level. If 'none', tornado won't touch the \"", "\"logging configuration.\"", ")", ",", "metavar", "=", "\"debug|info|warning|error|none\"", ",", ")", "options", ".", "define", "(", "\"log_to_stderr\"", ",", "type", "=", "bool", ",", "default", "=", "None", ",", "help", "=", "(", "\"Send log output to stderr (colorized if possible). \"", "\"By default use stderr if --log_file_prefix is not set and \"", "\"no other logging is configured.\"", ")", ",", ")", "options", ".", "define", "(", "\"log_file_prefix\"", ",", "type", "=", "str", ",", "default", "=", "None", ",", "metavar", "=", "\"PATH\"", ",", "help", "=", "(", "\"Path prefix for log files. \"", "\"Note that if you are running multiple tornado processes, \"", "\"log_file_prefix must be different for each of them (e.g. \"", "\"include the port number)\"", ")", ",", ")", "options", ".", "define", "(", "\"log_file_max_size\"", ",", "type", "=", "int", ",", "default", "=", "100", "*", "1000", "*", "1000", ",", "help", "=", "\"max size of log files before rollover\"", ",", ")", "options", ".", "define", "(", "\"log_file_num_backups\"", ",", "type", "=", "int", ",", "default", "=", "10", ",", "help", "=", "\"number of log files to keep\"", ")", "options", ".", "define", "(", "\"log_rotate_when\"", ",", "type", "=", "str", ",", "default", "=", "\"midnight\"", ",", "help", "=", "(", "\"specify the type of TimedRotatingFileHandler interval \"", "\"other options:('S', 'M', 'H', 'D', 'W0'-'W6')\"", ")", ",", ")", "options", ".", "define", "(", "\"log_rotate_interval\"", ",", "type", "=", "int", ",", "default", "=", "1", ",", "help", "=", "\"The interval value of timed rotating\"", ",", ")", "options", ".", "define", "(", "\"log_rotate_mode\"", ",", "type", "=", "str", ",", "default", "=", "\"size\"", ",", "help", "=", "\"The mode of rotating files(time or size)\"", ",", ")", "options", ".", "add_parse_callback", "(", "lambda", ":", "enable_pretty_logging", "(", "options", ")", ")" ]
Add logging-related flags to ``options``. These options are present automatically on the default options instance; this method is only necessary if you have created your own `.OptionParser`. .. versionadded:: 4.2 This function existed in prior versions but was broken and undocumented until 4.2.
[ "Add", "logging", "-", "related", "flags", "to", "options", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/log.py#L259-L337
26,809
tornadoweb/tornado
tornado/simple_httpclient.py
SimpleAsyncHTTPClient.initialize
def initialize( # type: ignore self, max_clients: int = 10, hostname_mapping: Dict[str, str] = None, max_buffer_size: int = 104857600, resolver: Resolver = None, defaults: Dict[str, Any] = None, max_header_size: int = None, max_body_size: int = None, ) -> None: """Creates a AsyncHTTPClient. Only a single AsyncHTTPClient instance exists per IOLoop in order to provide limitations on the number of pending connections. ``force_instance=True`` may be used to suppress this behavior. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to the constructor actually uses its arguments. It is recommended to use the ``configure`` method instead of the constructor to ensure that arguments take effect. ``max_clients`` is the number of concurrent requests that can be in progress; when this limit is reached additional requests will be queued. Note that time spent waiting in this queue still counts against the ``request_timeout``. ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses. It can be used to make local DNS changes when modifying system-wide settings like ``/etc/hosts`` is not possible or desirable (e.g. in unittests). ``max_buffer_size`` (default 100MB) is the number of bytes that can be read into memory at once. ``max_body_size`` (defaults to ``max_buffer_size``) is the largest response body that the client will accept. Without a ``streaming_callback``, the smaller of these two limits applies; with a ``streaming_callback`` only ``max_body_size`` does. .. versionchanged:: 4.2 Added the ``max_body_size`` argument. """ super(SimpleAsyncHTTPClient, self).initialize(defaults=defaults) self.max_clients = max_clients self.queue = ( collections.deque() ) # type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]] self.active = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]] self.waiting = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]] self.max_buffer_size = max_buffer_size self.max_header_size = max_header_size self.max_body_size = max_body_size # TCPClient could create a Resolver for us, but we have to do it # ourselves to support hostname_mapping. if resolver: self.resolver = resolver self.own_resolver = False else: self.resolver = Resolver() self.own_resolver = True if hostname_mapping is not None: self.resolver = OverrideResolver( resolver=self.resolver, mapping=hostname_mapping ) self.tcp_client = TCPClient(resolver=self.resolver)
python
def initialize( # type: ignore self, max_clients: int = 10, hostname_mapping: Dict[str, str] = None, max_buffer_size: int = 104857600, resolver: Resolver = None, defaults: Dict[str, Any] = None, max_header_size: int = None, max_body_size: int = None, ) -> None: """Creates a AsyncHTTPClient. Only a single AsyncHTTPClient instance exists per IOLoop in order to provide limitations on the number of pending connections. ``force_instance=True`` may be used to suppress this behavior. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to the constructor actually uses its arguments. It is recommended to use the ``configure`` method instead of the constructor to ensure that arguments take effect. ``max_clients`` is the number of concurrent requests that can be in progress; when this limit is reached additional requests will be queued. Note that time spent waiting in this queue still counts against the ``request_timeout``. ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses. It can be used to make local DNS changes when modifying system-wide settings like ``/etc/hosts`` is not possible or desirable (e.g. in unittests). ``max_buffer_size`` (default 100MB) is the number of bytes that can be read into memory at once. ``max_body_size`` (defaults to ``max_buffer_size``) is the largest response body that the client will accept. Without a ``streaming_callback``, the smaller of these two limits applies; with a ``streaming_callback`` only ``max_body_size`` does. .. versionchanged:: 4.2 Added the ``max_body_size`` argument. """ super(SimpleAsyncHTTPClient, self).initialize(defaults=defaults) self.max_clients = max_clients self.queue = ( collections.deque() ) # type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]] self.active = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]] self.waiting = ( {} ) # type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]] self.max_buffer_size = max_buffer_size self.max_header_size = max_header_size self.max_body_size = max_body_size # TCPClient could create a Resolver for us, but we have to do it # ourselves to support hostname_mapping. if resolver: self.resolver = resolver self.own_resolver = False else: self.resolver = Resolver() self.own_resolver = True if hostname_mapping is not None: self.resolver = OverrideResolver( resolver=self.resolver, mapping=hostname_mapping ) self.tcp_client = TCPClient(resolver=self.resolver)
[ "def", "initialize", "(", "# type: ignore", "self", ",", "max_clients", ":", "int", "=", "10", ",", "hostname_mapping", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "max_buffer_size", ":", "int", "=", "104857600", ",", "resolver", ":", "Resolver", "=", "None", ",", "defaults", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "max_header_size", ":", "int", "=", "None", ",", "max_body_size", ":", "int", "=", "None", ",", ")", "->", "None", ":", "super", "(", "SimpleAsyncHTTPClient", ",", "self", ")", ".", "initialize", "(", "defaults", "=", "defaults", ")", "self", ".", "max_clients", "=", "max_clients", "self", ".", "queue", "=", "(", "collections", ".", "deque", "(", ")", ")", "# type: Deque[Tuple[object, HTTPRequest, Callable[[HTTPResponse], None]]]", "self", ".", "active", "=", "(", "{", "}", ")", "# type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None]]]", "self", ".", "waiting", "=", "(", "{", "}", ")", "# type: Dict[object, Tuple[HTTPRequest, Callable[[HTTPResponse], None], object]]", "self", ".", "max_buffer_size", "=", "max_buffer_size", "self", ".", "max_header_size", "=", "max_header_size", "self", ".", "max_body_size", "=", "max_body_size", "# TCPClient could create a Resolver for us, but we have to do it", "# ourselves to support hostname_mapping.", "if", "resolver", ":", "self", ".", "resolver", "=", "resolver", "self", ".", "own_resolver", "=", "False", "else", ":", "self", ".", "resolver", "=", "Resolver", "(", ")", "self", ".", "own_resolver", "=", "True", "if", "hostname_mapping", "is", "not", "None", ":", "self", ".", "resolver", "=", "OverrideResolver", "(", "resolver", "=", "self", ".", "resolver", ",", "mapping", "=", "hostname_mapping", ")", "self", ".", "tcp_client", "=", "TCPClient", "(", "resolver", "=", "self", ".", "resolver", ")" ]
Creates a AsyncHTTPClient. Only a single AsyncHTTPClient instance exists per IOLoop in order to provide limitations on the number of pending connections. ``force_instance=True`` may be used to suppress this behavior. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to the constructor actually uses its arguments. It is recommended to use the ``configure`` method instead of the constructor to ensure that arguments take effect. ``max_clients`` is the number of concurrent requests that can be in progress; when this limit is reached additional requests will be queued. Note that time spent waiting in this queue still counts against the ``request_timeout``. ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses. It can be used to make local DNS changes when modifying system-wide settings like ``/etc/hosts`` is not possible or desirable (e.g. in unittests). ``max_buffer_size`` (default 100MB) is the number of bytes that can be read into memory at once. ``max_body_size`` (defaults to ``max_buffer_size``) is the largest response body that the client will accept. Without a ``streaming_callback``, the smaller of these two limits applies; with a ``streaming_callback`` only ``max_body_size`` does. .. versionchanged:: 4.2 Added the ``max_body_size`` argument.
[ "Creates", "a", "AsyncHTTPClient", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/simple_httpclient.py#L89-L157
26,810
tornadoweb/tornado
tornado/simple_httpclient.py
SimpleAsyncHTTPClient._on_timeout
def _on_timeout(self, key: object, info: str = None) -> None: """Timeout callback of request. Construct a timeout HTTPResponse when a timeout occurs. :arg object key: A simple object to mark the request. :info string key: More detailed timeout information. """ request, callback, timeout_handle = self.waiting[key] self.queue.remove((key, request, callback)) error_message = "Timeout {0}".format(info) if info else "Timeout" timeout_response = HTTPResponse( request, 599, error=HTTPTimeoutError(error_message), request_time=self.io_loop.time() - request.start_time, ) self.io_loop.add_callback(callback, timeout_response) del self.waiting[key]
python
def _on_timeout(self, key: object, info: str = None) -> None: """Timeout callback of request. Construct a timeout HTTPResponse when a timeout occurs. :arg object key: A simple object to mark the request. :info string key: More detailed timeout information. """ request, callback, timeout_handle = self.waiting[key] self.queue.remove((key, request, callback)) error_message = "Timeout {0}".format(info) if info else "Timeout" timeout_response = HTTPResponse( request, 599, error=HTTPTimeoutError(error_message), request_time=self.io_loop.time() - request.start_time, ) self.io_loop.add_callback(callback, timeout_response) del self.waiting[key]
[ "def", "_on_timeout", "(", "self", ",", "key", ":", "object", ",", "info", ":", "str", "=", "None", ")", "->", "None", ":", "request", ",", "callback", ",", "timeout_handle", "=", "self", ".", "waiting", "[", "key", "]", "self", ".", "queue", ".", "remove", "(", "(", "key", ",", "request", ",", "callback", ")", ")", "error_message", "=", "\"Timeout {0}\"", ".", "format", "(", "info", ")", "if", "info", "else", "\"Timeout\"", "timeout_response", "=", "HTTPResponse", "(", "request", ",", "599", ",", "error", "=", "HTTPTimeoutError", "(", "error_message", ")", ",", "request_time", "=", "self", ".", "io_loop", ".", "time", "(", ")", "-", "request", ".", "start_time", ",", ")", "self", ".", "io_loop", ".", "add_callback", "(", "callback", ",", "timeout_response", ")", "del", "self", ".", "waiting", "[", "key", "]" ]
Timeout callback of request. Construct a timeout HTTPResponse when a timeout occurs. :arg object key: A simple object to mark the request. :info string key: More detailed timeout information.
[ "Timeout", "callback", "of", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/simple_httpclient.py#L229-L248
26,811
tornadoweb/tornado
tornado/simple_httpclient.py
_HTTPConnection._on_timeout
def _on_timeout(self, info: str = None) -> None: """Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information. """ self._timeout = None error_message = "Timeout {0}".format(info) if info else "Timeout" if self.final_callback is not None: self._handle_exception( HTTPTimeoutError, HTTPTimeoutError(error_message), None )
python
def _on_timeout(self, info: str = None) -> None: """Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information. """ self._timeout = None error_message = "Timeout {0}".format(info) if info else "Timeout" if self.final_callback is not None: self._handle_exception( HTTPTimeoutError, HTTPTimeoutError(error_message), None )
[ "def", "_on_timeout", "(", "self", ",", "info", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "_timeout", "=", "None", "error_message", "=", "\"Timeout {0}\"", ".", "format", "(", "info", ")", "if", "info", "else", "\"Timeout\"", "if", "self", ".", "final_callback", "is", "not", "None", ":", "self", ".", "_handle_exception", "(", "HTTPTimeoutError", ",", "HTTPTimeoutError", "(", "error_message", ")", ",", "None", ")" ]
Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information.
[ "Timeout", "callback", "of", "_HTTPConnection", "instance", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/simple_httpclient.py#L474-L486
26,812
tornadoweb/tornado
tornado/auth.py
_oauth10a_signature
def _oauth10a_signature( consumer_token: Dict[str, Any], method: str, url: str, parameters: Dict[str, Any] = {}, token: Dict[str, Any] = None, ) -> bytes: """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process """ parts = urllib.parse.urlparse(url) scheme, netloc, path = parts[:3] normalized_url = scheme.lower() + "://" + netloc.lower() + path base_elems = [] base_elems.append(method.upper()) base_elems.append(normalized_url) base_elems.append( "&".join( "%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items()) ) ) base_string = "&".join(_oauth_escape(e) for e in base_elems) key_elems = [escape.utf8(urllib.parse.quote(consumer_token["secret"], safe="~"))] key_elems.append( escape.utf8(urllib.parse.quote(token["secret"], safe="~") if token else "") ) key = b"&".join(key_elems) hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1) return binascii.b2a_base64(hash.digest())[:-1]
python
def _oauth10a_signature( consumer_token: Dict[str, Any], method: str, url: str, parameters: Dict[str, Any] = {}, token: Dict[str, Any] = None, ) -> bytes: """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process """ parts = urllib.parse.urlparse(url) scheme, netloc, path = parts[:3] normalized_url = scheme.lower() + "://" + netloc.lower() + path base_elems = [] base_elems.append(method.upper()) base_elems.append(normalized_url) base_elems.append( "&".join( "%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items()) ) ) base_string = "&".join(_oauth_escape(e) for e in base_elems) key_elems = [escape.utf8(urllib.parse.quote(consumer_token["secret"], safe="~"))] key_elems.append( escape.utf8(urllib.parse.quote(token["secret"], safe="~") if token else "") ) key = b"&".join(key_elems) hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1) return binascii.b2a_base64(hash.digest())[:-1]
[ "def", "_oauth10a_signature", "(", "consumer_token", ":", "Dict", "[", "str", ",", "Any", "]", ",", "method", ":", "str", ",", "url", ":", "str", ",", "parameters", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", ",", "token", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", ")", "->", "bytes", ":", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "scheme", ",", "netloc", ",", "path", "=", "parts", "[", ":", "3", "]", "normalized_url", "=", "scheme", ".", "lower", "(", ")", "+", "\"://\"", "+", "netloc", ".", "lower", "(", ")", "+", "path", "base_elems", "=", "[", "]", "base_elems", ".", "append", "(", "method", ".", "upper", "(", ")", ")", "base_elems", ".", "append", "(", "normalized_url", ")", "base_elems", ".", "append", "(", "\"&\"", ".", "join", "(", "\"%s=%s\"", "%", "(", "k", ",", "_oauth_escape", "(", "str", "(", "v", ")", ")", ")", "for", "k", ",", "v", "in", "sorted", "(", "parameters", ".", "items", "(", ")", ")", ")", ")", "base_string", "=", "\"&\"", ".", "join", "(", "_oauth_escape", "(", "e", ")", "for", "e", "in", "base_elems", ")", "key_elems", "=", "[", "escape", ".", "utf8", "(", "urllib", ".", "parse", ".", "quote", "(", "consumer_token", "[", "\"secret\"", "]", ",", "safe", "=", "\"~\"", ")", ")", "]", "key_elems", ".", "append", "(", "escape", ".", "utf8", "(", "urllib", ".", "parse", ".", "quote", "(", "token", "[", "\"secret\"", "]", ",", "safe", "=", "\"~\"", ")", "if", "token", "else", "\"\"", ")", ")", "key", "=", "b\"&\"", ".", "join", "(", "key_elems", ")", "hash", "=", "hmac", ".", "new", "(", "key", ",", "escape", ".", "utf8", "(", "base_string", ")", ",", "hashlib", ".", "sha1", ")", "return", "binascii", ".", "b2a_base64", "(", "hash", ".", "digest", "(", ")", ")", "[", ":", "-", "1", "]" ]
Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process
[ "Calculates", "the", "HMAC", "-", "SHA1", "OAuth", "1", ".", "0a", "signature", "for", "the", "given", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L1130-L1162
26,813
tornadoweb/tornado
tornado/auth.py
OpenIdMixin.authenticate_redirect
def authenticate_redirect( self, callback_uri: str = None, ax_attrs: List[str] = ["name", "email", "language", "username"], ) -> None: """Redirects to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI with additional parameters including ``openid.mode``. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don't need all those attributes for your app, you can request fewer with the ax_attrs keyword argument. .. versionchanged:: 6.0 The ``callback`` argument was removed and this method no longer returns an awaitable object. It is now an ordinary synchronous function. """ handler = cast(RequestHandler, self) callback_uri = callback_uri or handler.request.uri assert callback_uri is not None args = self._openid_args(callback_uri, ax_attrs=ax_attrs) endpoint = self._OPENID_ENDPOINT # type: ignore handler.redirect(endpoint + "?" + urllib.parse.urlencode(args))
python
def authenticate_redirect( self, callback_uri: str = None, ax_attrs: List[str] = ["name", "email", "language", "username"], ) -> None: """Redirects to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI with additional parameters including ``openid.mode``. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don't need all those attributes for your app, you can request fewer with the ax_attrs keyword argument. .. versionchanged:: 6.0 The ``callback`` argument was removed and this method no longer returns an awaitable object. It is now an ordinary synchronous function. """ handler = cast(RequestHandler, self) callback_uri = callback_uri or handler.request.uri assert callback_uri is not None args = self._openid_args(callback_uri, ax_attrs=ax_attrs) endpoint = self._OPENID_ENDPOINT # type: ignore handler.redirect(endpoint + "?" + urllib.parse.urlencode(args))
[ "def", "authenticate_redirect", "(", "self", ",", "callback_uri", ":", "str", "=", "None", ",", "ax_attrs", ":", "List", "[", "str", "]", "=", "[", "\"name\"", ",", "\"email\"", ",", "\"language\"", ",", "\"username\"", "]", ",", ")", "->", "None", ":", "handler", "=", "cast", "(", "RequestHandler", ",", "self", ")", "callback_uri", "=", "callback_uri", "or", "handler", ".", "request", ".", "uri", "assert", "callback_uri", "is", "not", "None", "args", "=", "self", ".", "_openid_args", "(", "callback_uri", ",", "ax_attrs", "=", "ax_attrs", ")", "endpoint", "=", "self", ".", "_OPENID_ENDPOINT", "# type: ignore", "handler", ".", "redirect", "(", "endpoint", "+", "\"?\"", "+", "urllib", ".", "parse", ".", "urlencode", "(", "args", ")", ")" ]
Redirects to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI with additional parameters including ``openid.mode``. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don't need all those attributes for your app, you can request fewer with the ax_attrs keyword argument. .. versionchanged:: 6.0 The ``callback`` argument was removed and this method no longer returns an awaitable object. It is now an ordinary synchronous function.
[ "Redirects", "to", "the", "authentication", "URL", "for", "this", "service", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L88-L114
26,814
tornadoweb/tornado
tornado/auth.py
OAuthMixin.get_authenticated_user
async def get_authenticated_user( self, http_client: httpclient.AsyncHTTPClient = None ) -> Dict[str, Any]: """Gets the OAuth authorized user and access token. This method should be called from the handler for your OAuth callback URL to complete the registration process. We run the callback with the authenticated user dictionary. This dictionary will contain an ``access_key`` which can be used to make authorized requests to this service on behalf of the user. The dictionary will also contain other fields such as ``name``, depending on the service used. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ handler = cast(RequestHandler, self) request_key = escape.utf8(handler.get_argument("oauth_token")) oauth_verifier = handler.get_argument("oauth_verifier", None) request_cookie = handler.get_cookie("_oauth_request_token") if not request_cookie: raise AuthError("Missing OAuth request token cookie") handler.clear_cookie("_oauth_request_token") cookie_key, cookie_secret = [ base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|") ] if cookie_key != request_key: raise AuthError("Request token does not match cookie") token = dict( key=cookie_key, secret=cookie_secret ) # type: Dict[str, Union[str, bytes]] if oauth_verifier: token["verifier"] = oauth_verifier if http_client is None: http_client = self.get_auth_http_client() assert http_client is not None response = await http_client.fetch(self._oauth_access_token_url(token)) access_token = _oauth_parse_response(response.body) user = await self._oauth_get_user_future(access_token) if not user: raise AuthError("Error getting user") user["access_token"] = access_token return user
python
async def get_authenticated_user( self, http_client: httpclient.AsyncHTTPClient = None ) -> Dict[str, Any]: """Gets the OAuth authorized user and access token. This method should be called from the handler for your OAuth callback URL to complete the registration process. We run the callback with the authenticated user dictionary. This dictionary will contain an ``access_key`` which can be used to make authorized requests to this service on behalf of the user. The dictionary will also contain other fields such as ``name``, depending on the service used. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ handler = cast(RequestHandler, self) request_key = escape.utf8(handler.get_argument("oauth_token")) oauth_verifier = handler.get_argument("oauth_verifier", None) request_cookie = handler.get_cookie("_oauth_request_token") if not request_cookie: raise AuthError("Missing OAuth request token cookie") handler.clear_cookie("_oauth_request_token") cookie_key, cookie_secret = [ base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|") ] if cookie_key != request_key: raise AuthError("Request token does not match cookie") token = dict( key=cookie_key, secret=cookie_secret ) # type: Dict[str, Union[str, bytes]] if oauth_verifier: token["verifier"] = oauth_verifier if http_client is None: http_client = self.get_auth_http_client() assert http_client is not None response = await http_client.fetch(self._oauth_access_token_url(token)) access_token = _oauth_parse_response(response.body) user = await self._oauth_get_user_future(access_token) if not user: raise AuthError("Error getting user") user["access_token"] = access_token return user
[ "async", "def", "get_authenticated_user", "(", "self", ",", "http_client", ":", "httpclient", ".", "AsyncHTTPClient", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "handler", "=", "cast", "(", "RequestHandler", ",", "self", ")", "request_key", "=", "escape", ".", "utf8", "(", "handler", ".", "get_argument", "(", "\"oauth_token\"", ")", ")", "oauth_verifier", "=", "handler", ".", "get_argument", "(", "\"oauth_verifier\"", ",", "None", ")", "request_cookie", "=", "handler", ".", "get_cookie", "(", "\"_oauth_request_token\"", ")", "if", "not", "request_cookie", ":", "raise", "AuthError", "(", "\"Missing OAuth request token cookie\"", ")", "handler", ".", "clear_cookie", "(", "\"_oauth_request_token\"", ")", "cookie_key", ",", "cookie_secret", "=", "[", "base64", ".", "b64decode", "(", "escape", ".", "utf8", "(", "i", ")", ")", "for", "i", "in", "request_cookie", ".", "split", "(", "\"|\"", ")", "]", "if", "cookie_key", "!=", "request_key", ":", "raise", "AuthError", "(", "\"Request token does not match cookie\"", ")", "token", "=", "dict", "(", "key", "=", "cookie_key", ",", "secret", "=", "cookie_secret", ")", "# type: Dict[str, Union[str, bytes]]", "if", "oauth_verifier", ":", "token", "[", "\"verifier\"", "]", "=", "oauth_verifier", "if", "http_client", "is", "None", ":", "http_client", "=", "self", ".", "get_auth_http_client", "(", ")", "assert", "http_client", "is", "not", "None", "response", "=", "await", "http_client", ".", "fetch", "(", "self", ".", "_oauth_access_token_url", "(", "token", ")", ")", "access_token", "=", "_oauth_parse_response", "(", "response", ".", "body", ")", "user", "=", "await", "self", ".", "_oauth_get_user_future", "(", "access_token", ")", "if", "not", "user", ":", "raise", "AuthError", "(", "\"Error getting user\"", ")", "user", "[", "\"access_token\"", "]", "=", "access_token", "return", "user" ]
Gets the OAuth authorized user and access token. This method should be called from the handler for your OAuth callback URL to complete the registration process. We run the callback with the authenticated user dictionary. This dictionary will contain an ``access_key`` which can be used to make authorized requests to this service on behalf of the user. The dictionary will also contain other fields such as ``name``, depending on the service used. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Gets", "the", "OAuth", "authorized", "user", "and", "access", "token", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L336-L380
26,815
tornadoweb/tornado
tornado/auth.py
OAuthMixin._oauth_get_user_future
async def _oauth_get_user_future( self, access_token: Dict[str, Any] ) -> Dict[str, Any]: """Subclasses must override this to get basic information about the user. Should be a coroutine whose result is a dictionary containing information about the user, which may have been retrieved by using ``access_token`` to make a request to the service. The access token will be added to the returned dictionary to make the result of `get_authenticated_user`. .. versionchanged:: 5.1 Subclasses may also define this method with ``async def``. .. versionchanged:: 6.0 A synchronous fallback to ``_oauth_get_user`` was removed. """ raise NotImplementedError()
python
async def _oauth_get_user_future( self, access_token: Dict[str, Any] ) -> Dict[str, Any]: """Subclasses must override this to get basic information about the user. Should be a coroutine whose result is a dictionary containing information about the user, which may have been retrieved by using ``access_token`` to make a request to the service. The access token will be added to the returned dictionary to make the result of `get_authenticated_user`. .. versionchanged:: 5.1 Subclasses may also define this method with ``async def``. .. versionchanged:: 6.0 A synchronous fallback to ``_oauth_get_user`` was removed. """ raise NotImplementedError()
[ "async", "def", "_oauth_get_user_future", "(", "self", ",", "access_token", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Subclasses must override this to get basic information about the user. Should be a coroutine whose result is a dictionary containing information about the user, which may have been retrieved by using ``access_token`` to make a request to the service. The access token will be added to the returned dictionary to make the result of `get_authenticated_user`. .. versionchanged:: 5.1 Subclasses may also define this method with ``async def``. .. versionchanged:: 6.0 A synchronous fallback to ``_oauth_get_user`` was removed.
[ "Subclasses", "must", "override", "this", "to", "get", "basic", "information", "about", "the", "user", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L468-L490
26,816
tornadoweb/tornado
tornado/auth.py
OAuth2Mixin.oauth2_request
async def oauth2_request( self, url: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any ) -> Any: """Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. Example usage: ..testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.oauth2_request( "https://graph.facebook.com/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? await self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: .. versionadded:: 4.3 .. versionchanged::: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(args) if all_args: url += "?" + urllib.parse.urlencode(all_args) http = self.get_auth_http_client() if post_args is not None: response = await http.fetch( url, method="POST", body=urllib.parse.urlencode(post_args) ) else: response = await http.fetch(url) return escape.json_decode(response.body)
python
async def oauth2_request( self, url: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any ) -> Any: """Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. Example usage: ..testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.oauth2_request( "https://graph.facebook.com/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? await self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: .. versionadded:: 4.3 .. versionchanged::: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(args) if all_args: url += "?" + urllib.parse.urlencode(all_args) http = self.get_auth_http_client() if post_args is not None: response = await http.fetch( url, method="POST", body=urllib.parse.urlencode(post_args) ) else: response = await http.fetch(url) return escape.json_decode(response.body)
[ "async", "def", "oauth2_request", "(", "self", ",", "url", ":", "str", ",", "access_token", ":", "str", "=", "None", ",", "post_args", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "*", "*", "args", ":", "Any", ")", "->", "Any", ":", "all_args", "=", "{", "}", "if", "access_token", ":", "all_args", "[", "\"access_token\"", "]", "=", "access_token", "all_args", ".", "update", "(", "args", ")", "if", "all_args", ":", "url", "+=", "\"?\"", "+", "urllib", ".", "parse", ".", "urlencode", "(", "all_args", ")", "http", "=", "self", ".", "get_auth_http_client", "(", ")", "if", "post_args", "is", "not", "None", ":", "response", "=", "await", "http", ".", "fetch", "(", "url", ",", "method", "=", "\"POST\"", ",", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "post_args", ")", ")", "else", ":", "response", "=", "await", "http", ".", "fetch", "(", "url", ")", "return", "escape", ".", "json_decode", "(", "response", ".", "body", ")" ]
Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. Example usage: ..testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.oauth2_request( "https://graph.facebook.com/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? await self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: .. versionadded:: 4.3 .. versionchanged::: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Fetches", "the", "given", "URL", "auth", "an", "OAuth2", "access", "token", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L605-L659
26,817
tornadoweb/tornado
tornado/auth.py
TwitterMixin.authenticate_redirect
async def authenticate_redirect(self, callback_uri: str = None) -> None: """Just like `~OAuthMixin.authorize_redirect`, but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. .. versionchanged:: 3.1 Now returns a `.Future` and takes an optional callback, for compatibility with `.gen.coroutine`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ http = self.get_auth_http_client() response = await http.fetch( self._oauth_request_token_url(callback_uri=callback_uri) ) self._on_request_token(self._OAUTH_AUTHENTICATE_URL, None, response)
python
async def authenticate_redirect(self, callback_uri: str = None) -> None: """Just like `~OAuthMixin.authorize_redirect`, but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. .. versionchanged:: 3.1 Now returns a `.Future` and takes an optional callback, for compatibility with `.gen.coroutine`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ http = self.get_auth_http_client() response = await http.fetch( self._oauth_request_token_url(callback_uri=callback_uri) ) self._on_request_token(self._OAUTH_AUTHENTICATE_URL, None, response)
[ "async", "def", "authenticate_redirect", "(", "self", ",", "callback_uri", ":", "str", "=", "None", ")", "->", "None", ":", "http", "=", "self", ".", "get_auth_http_client", "(", ")", "response", "=", "await", "http", ".", "fetch", "(", "self", ".", "_oauth_request_token_url", "(", "callback_uri", "=", "callback_uri", ")", ")", "self", ".", "_on_request_token", "(", "self", ".", "_OAUTH_AUTHENTICATE_URL", ",", "None", ",", "response", ")" ]
Just like `~OAuthMixin.authorize_redirect`, but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. .. versionchanged:: 3.1 Now returns a `.Future` and takes an optional callback, for compatibility with `.gen.coroutine`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Just", "like", "~OAuthMixin", ".", "authorize_redirect", "but", "auto", "-", "redirects", "if", "authorized", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L712-L732
26,818
tornadoweb/tornado
tornado/auth.py
GoogleOAuth2Mixin.get_authenticated_user
async def get_authenticated_user( self, redirect_uri: str, code: str ) -> Dict[str, Any]: """Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not return any additional information about the user. The returned access token can be used with `OAuth2Mixin.oauth2_request` to request additional information (perhaps from ``https://www.googleapis.com/oauth2/v2/userinfo``) Example usage: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ # noqa: E501 handler = cast(RequestHandler, self) http = self.get_auth_http_client() body = urllib.parse.urlencode( { "redirect_uri": redirect_uri, "code": code, "client_id": handler.settings[self._OAUTH_SETTINGS_KEY]["key"], "client_secret": handler.settings[self._OAUTH_SETTINGS_KEY]["secret"], "grant_type": "authorization_code", } ) response = await http.fetch( self._OAUTH_ACCESS_TOKEN_URL, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"}, body=body, ) return escape.json_decode(response.body)
python
async def get_authenticated_user( self, redirect_uri: str, code: str ) -> Dict[str, Any]: """Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not return any additional information about the user. The returned access token can be used with `OAuth2Mixin.oauth2_request` to request additional information (perhaps from ``https://www.googleapis.com/oauth2/v2/userinfo``) Example usage: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ # noqa: E501 handler = cast(RequestHandler, self) http = self.get_auth_http_client() body = urllib.parse.urlencode( { "redirect_uri": redirect_uri, "code": code, "client_id": handler.settings[self._OAUTH_SETTINGS_KEY]["key"], "client_secret": handler.settings[self._OAUTH_SETTINGS_KEY]["secret"], "grant_type": "authorization_code", } ) response = await http.fetch( self._OAUTH_ACCESS_TOKEN_URL, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"}, body=body, ) return escape.json_decode(response.body)
[ "async", "def", "get_authenticated_user", "(", "self", ",", "redirect_uri", ":", "str", ",", "code", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# noqa: E501", "handler", "=", "cast", "(", "RequestHandler", ",", "self", ")", "http", "=", "self", ".", "get_auth_http_client", "(", ")", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "\"redirect_uri\"", ":", "redirect_uri", ",", "\"code\"", ":", "code", ",", "\"client_id\"", ":", "handler", ".", "settings", "[", "self", ".", "_OAUTH_SETTINGS_KEY", "]", "[", "\"key\"", "]", ",", "\"client_secret\"", ":", "handler", ".", "settings", "[", "self", ".", "_OAUTH_SETTINGS_KEY", "]", "[", "\"secret\"", "]", ",", "\"grant_type\"", ":", "\"authorization_code\"", ",", "}", ")", "response", "=", "await", "http", ".", "fetch", "(", "self", ".", "_OAUTH_ACCESS_TOKEN_URL", ",", "method", "=", "\"POST\"", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", "}", ",", "body", "=", "body", ",", ")", "return", "escape", ".", "json_decode", "(", "response", ".", "body", ")" ]
Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not return any additional information about the user. The returned access token can be used with `OAuth2Mixin.oauth2_request` to request additional information (perhaps from ``https://www.googleapis.com/oauth2/v2/userinfo``) Example usage: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Handles", "the", "login", "for", "the", "Google", "user", "returning", "an", "access", "token", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L854-L916
26,819
tornadoweb/tornado
tornado/auth.py
FacebookGraphMixin.get_authenticated_user
async def get_authenticated_user( self, redirect_uri: str, client_id: str, client_secret: str, code: str, extra_fields: Dict[str, Any] = None, ) -> Optional[Dict[str, Any]]: """Handles the login for the Facebook user, returning a user object. Example usage: .. testcode:: class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): async def get(self): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code")) # Save the user with e.g. set_secure_cookie else: await self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) .. testoutput:: :hide: This method returns a dictionary which may contain the following fields: * ``access_token``, a string which may be passed to `facebook_request` * ``session_expires``, an integer encoded as a string representing the time until the access token expires in seconds. This field should be used like ``int(user['session_expires'])``; in a future version of Tornado it will change from a string to an integer. * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``, ``link``, plus any fields named in the ``extra_fields`` argument. These fields are copied from the Facebook graph API `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_ .. versionchanged:: 4.5 The ``session_expires`` field was updated to support changes made to the Facebook API in March 2017. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ http = self.get_auth_http_client() args = { "redirect_uri": redirect_uri, "code": code, "client_id": client_id, "client_secret": client_secret, } fields = set( ["id", "name", "first_name", "last_name", "locale", "picture", "link"] ) if extra_fields: fields.update(extra_fields) response = await http.fetch( self._oauth_request_token_url(**args) # type: ignore ) args = escape.json_decode(response.body) session = { "access_token": args.get("access_token"), "expires_in": args.get("expires_in"), } assert session["access_token"] is not None user = await self.facebook_request( path="/me", access_token=session["access_token"], appsecret_proof=hmac.new( key=client_secret.encode("utf8"), msg=session["access_token"].encode("utf8"), digestmod=hashlib.sha256, ).hexdigest(), fields=",".join(fields), ) if user is None: return None fieldmap = {} for field in fields: fieldmap[field] = user.get(field) # session_expires is converted to str for compatibility with # older versions in which the server used url-encoding and # this code simply returned the string verbatim. # This should change in Tornado 5.0. fieldmap.update( { "access_token": session["access_token"], "session_expires": str(session.get("expires_in")), } ) return fieldmap
python
async def get_authenticated_user( self, redirect_uri: str, client_id: str, client_secret: str, code: str, extra_fields: Dict[str, Any] = None, ) -> Optional[Dict[str, Any]]: """Handles the login for the Facebook user, returning a user object. Example usage: .. testcode:: class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): async def get(self): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code")) # Save the user with e.g. set_secure_cookie else: await self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) .. testoutput:: :hide: This method returns a dictionary which may contain the following fields: * ``access_token``, a string which may be passed to `facebook_request` * ``session_expires``, an integer encoded as a string representing the time until the access token expires in seconds. This field should be used like ``int(user['session_expires'])``; in a future version of Tornado it will change from a string to an integer. * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``, ``link``, plus any fields named in the ``extra_fields`` argument. These fields are copied from the Facebook graph API `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_ .. versionchanged:: 4.5 The ``session_expires`` field was updated to support changes made to the Facebook API in March 2017. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ http = self.get_auth_http_client() args = { "redirect_uri": redirect_uri, "code": code, "client_id": client_id, "client_secret": client_secret, } fields = set( ["id", "name", "first_name", "last_name", "locale", "picture", "link"] ) if extra_fields: fields.update(extra_fields) response = await http.fetch( self._oauth_request_token_url(**args) # type: ignore ) args = escape.json_decode(response.body) session = { "access_token": args.get("access_token"), "expires_in": args.get("expires_in"), } assert session["access_token"] is not None user = await self.facebook_request( path="/me", access_token=session["access_token"], appsecret_proof=hmac.new( key=client_secret.encode("utf8"), msg=session["access_token"].encode("utf8"), digestmod=hashlib.sha256, ).hexdigest(), fields=",".join(fields), ) if user is None: return None fieldmap = {} for field in fields: fieldmap[field] = user.get(field) # session_expires is converted to str for compatibility with # older versions in which the server used url-encoding and # this code simply returned the string verbatim. # This should change in Tornado 5.0. fieldmap.update( { "access_token": session["access_token"], "session_expires": str(session.get("expires_in")), } ) return fieldmap
[ "async", "def", "get_authenticated_user", "(", "self", ",", "redirect_uri", ":", "str", ",", "client_id", ":", "str", ",", "client_secret", ":", "str", ",", "code", ":", "str", ",", "extra_fields", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "http", "=", "self", ".", "get_auth_http_client", "(", ")", "args", "=", "{", "\"redirect_uri\"", ":", "redirect_uri", ",", "\"code\"", ":", "code", ",", "\"client_id\"", ":", "client_id", ",", "\"client_secret\"", ":", "client_secret", ",", "}", "fields", "=", "set", "(", "[", "\"id\"", ",", "\"name\"", ",", "\"first_name\"", ",", "\"last_name\"", ",", "\"locale\"", ",", "\"picture\"", ",", "\"link\"", "]", ")", "if", "extra_fields", ":", "fields", ".", "update", "(", "extra_fields", ")", "response", "=", "await", "http", ".", "fetch", "(", "self", ".", "_oauth_request_token_url", "(", "*", "*", "args", ")", "# type: ignore", ")", "args", "=", "escape", ".", "json_decode", "(", "response", ".", "body", ")", "session", "=", "{", "\"access_token\"", ":", "args", ".", "get", "(", "\"access_token\"", ")", ",", "\"expires_in\"", ":", "args", ".", "get", "(", "\"expires_in\"", ")", ",", "}", "assert", "session", "[", "\"access_token\"", "]", "is", "not", "None", "user", "=", "await", "self", ".", "facebook_request", "(", "path", "=", "\"/me\"", ",", "access_token", "=", "session", "[", "\"access_token\"", "]", ",", "appsecret_proof", "=", "hmac", ".", "new", "(", "key", "=", "client_secret", ".", "encode", "(", "\"utf8\"", ")", ",", "msg", "=", "session", "[", "\"access_token\"", "]", ".", "encode", "(", "\"utf8\"", ")", ",", "digestmod", "=", "hashlib", ".", "sha256", ",", ")", ".", "hexdigest", "(", ")", ",", "fields", "=", "\",\"", ".", "join", "(", "fields", ")", ",", ")", "if", "user", "is", "None", ":", "return", "None", "fieldmap", "=", "{", "}", "for", "field", "in", "fields", ":", "fieldmap", "[", "field", "]", "=", "user", ".", "get", "(", "field", ")", "# session_expires is converted to str for compatibility with", "# older versions in which the server used url-encoding and", "# this code simply returned the string verbatim.", "# This should change in Tornado 5.0.", "fieldmap", ".", "update", "(", "{", "\"access_token\"", ":", "session", "[", "\"access_token\"", "]", ",", "\"session_expires\"", ":", "str", "(", "session", ".", "get", "(", "\"expires_in\"", ")", ")", ",", "}", ")", "return", "fieldmap" ]
Handles the login for the Facebook user, returning a user object. Example usage: .. testcode:: class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): async def get(self): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code")) # Save the user with e.g. set_secure_cookie else: await self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) .. testoutput:: :hide: This method returns a dictionary which may contain the following fields: * ``access_token``, a string which may be passed to `facebook_request` * ``session_expires``, an integer encoded as a string representing the time until the access token expires in seconds. This field should be used like ``int(user['session_expires'])``; in a future version of Tornado it will change from a string to an integer. * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``, ``link``, plus any fields named in the ``extra_fields`` argument. These fields are copied from the Facebook graph API `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_ .. versionchanged:: 4.5 The ``session_expires`` field was updated to support changes made to the Facebook API in March 2017. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Handles", "the", "login", "for", "the", "Facebook", "user", "returning", "a", "user", "object", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/auth.py#L927-L1032
26,820
tornadoweb/tornado
tornado/locks.py
Condition.wait
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]: """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() # type: Future[bool] self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): future_set_result_unless_cancelled(waiter, False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
python
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]: """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() # type: Future[bool] self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): future_set_result_unless_cancelled(waiter, False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
[ "def", "wait", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "bool", "]", ":", "waiter", "=", "Future", "(", ")", "# type: Future[bool]", "self", ".", "_waiters", ".", "append", "(", "waiter", ")", "if", "timeout", ":", "def", "on_timeout", "(", ")", "->", "None", ":", "if", "not", "waiter", ".", "done", "(", ")", ":", "future_set_result_unless_cancelled", "(", "waiter", ",", "False", ")", "self", ".", "_garbage_collect", "(", ")", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "timeout_handle", "=", "io_loop", ".", "add_timeout", "(", "timeout", ",", "on_timeout", ")", "waiter", ".", "add_done_callback", "(", "lambda", "_", ":", "io_loop", ".", "remove_timeout", "(", "timeout_handle", ")", ")", "return", "waiter" ]
Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout.
[ "Wait", "for", ".", "notify", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L124-L142
26,821
tornadoweb/tornado
tornado/locks.py
Condition.notify
def notify(self, n: int = 1) -> None: """Wake ``n`` waiters.""" waiters = [] # Waiters we plan to run right now. while n and self._waiters: waiter = self._waiters.popleft() if not waiter.done(): # Might have timed out. n -= 1 waiters.append(waiter) for waiter in waiters: future_set_result_unless_cancelled(waiter, True)
python
def notify(self, n: int = 1) -> None: """Wake ``n`` waiters.""" waiters = [] # Waiters we plan to run right now. while n and self._waiters: waiter = self._waiters.popleft() if not waiter.done(): # Might have timed out. n -= 1 waiters.append(waiter) for waiter in waiters: future_set_result_unless_cancelled(waiter, True)
[ "def", "notify", "(", "self", ",", "n", ":", "int", "=", "1", ")", "->", "None", ":", "waiters", "=", "[", "]", "# Waiters we plan to run right now.", "while", "n", "and", "self", ".", "_waiters", ":", "waiter", "=", "self", ".", "_waiters", ".", "popleft", "(", ")", "if", "not", "waiter", ".", "done", "(", ")", ":", "# Might have timed out.", "n", "-=", "1", "waiters", ".", "append", "(", "waiter", ")", "for", "waiter", "in", "waiters", ":", "future_set_result_unless_cancelled", "(", "waiter", ",", "True", ")" ]
Wake ``n`` waiters.
[ "Wake", "n", "waiters", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L144-L154
26,822
tornadoweb/tornado
tornado/locks.py
Event.set
def set(self) -> None: """Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block. """ if not self._value: self._value = True for fut in self._waiters: if not fut.done(): fut.set_result(None)
python
def set(self) -> None: """Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block. """ if not self._value: self._value = True for fut in self._waiters: if not fut.done(): fut.set_result(None)
[ "def", "set", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_value", ":", "self", ".", "_value", "=", "True", "for", "fut", "in", "self", ".", "_waiters", ":", "if", "not", "fut", ".", "done", "(", ")", ":", "fut", ".", "set_result", "(", "None", ")" ]
Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block.
[ "Set", "the", "internal", "flag", "to", "True", ".", "All", "waiters", "are", "awakened", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L215-L225
26,823
tornadoweb/tornado
tornado/locks.py
Event.wait
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ fut = Future() # type: Future[None] if self._value: fut.set_result(None) return fut self._waiters.add(fut) fut.add_done_callback(lambda fut: self._waiters.remove(fut)) if timeout is None: return fut else: timeout_fut = gen.with_timeout( timeout, fut, quiet_exceptions=(CancelledError,) ) # This is a slightly clumsy workaround for the fact that # gen.with_timeout doesn't cancel its futures. Cancelling # fut will remove it from the waiters list. timeout_fut.add_done_callback( lambda tf: fut.cancel() if not fut.done() else None ) return timeout_fut
python
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ fut = Future() # type: Future[None] if self._value: fut.set_result(None) return fut self._waiters.add(fut) fut.add_done_callback(lambda fut: self._waiters.remove(fut)) if timeout is None: return fut else: timeout_fut = gen.with_timeout( timeout, fut, quiet_exceptions=(CancelledError,) ) # This is a slightly clumsy workaround for the fact that # gen.with_timeout doesn't cancel its futures. Cancelling # fut will remove it from the waiters list. timeout_fut.add_done_callback( lambda tf: fut.cancel() if not fut.done() else None ) return timeout_fut
[ "def", "wait", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "None", "]", ":", "fut", "=", "Future", "(", ")", "# type: Future[None]", "if", "self", ".", "_value", ":", "fut", ".", "set_result", "(", "None", ")", "return", "fut", "self", ".", "_waiters", ".", "add", "(", "fut", ")", "fut", ".", "add_done_callback", "(", "lambda", "fut", ":", "self", ".", "_waiters", ".", "remove", "(", "fut", ")", ")", "if", "timeout", "is", "None", ":", "return", "fut", "else", ":", "timeout_fut", "=", "gen", ".", "with_timeout", "(", "timeout", ",", "fut", ",", "quiet_exceptions", "=", "(", "CancelledError", ",", ")", ")", "# This is a slightly clumsy workaround for the fact that", "# gen.with_timeout doesn't cancel its futures. Cancelling", "# fut will remove it from the waiters list.", "timeout_fut", ".", "add_done_callback", "(", "lambda", "tf", ":", "fut", ".", "cancel", "(", ")", "if", "not", "fut", ".", "done", "(", ")", "else", "None", ")", "return", "timeout_fut" ]
Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout.
[ "Block", "until", "the", "internal", "flag", "is", "true", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L234-L258
26,824
tornadoweb/tornado
tornado/locks.py
Semaphore.acquire
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline. """ waiter = Future() # type: Future[_ReleasingContextManager] if self._value > 0: self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): waiter.set_exception(gen.TimeoutError()) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle) ) return waiter
python
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline. """ waiter = Future() # type: Future[_ReleasingContextManager] if self._value > 0: self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): waiter.set_exception(gen.TimeoutError()) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle) ) return waiter
[ "def", "acquire", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "_ReleasingContextManager", "]", ":", "waiter", "=", "Future", "(", ")", "# type: Future[_ReleasingContextManager]", "if", "self", ".", "_value", ">", "0", ":", "self", ".", "_value", "-=", "1", "waiter", ".", "set_result", "(", "_ReleasingContextManager", "(", "self", ")", ")", "else", ":", "self", ".", "_waiters", ".", "append", "(", "waiter", ")", "if", "timeout", ":", "def", "on_timeout", "(", ")", "->", "None", ":", "if", "not", "waiter", ".", "done", "(", ")", ":", "waiter", ".", "set_exception", "(", "gen", ".", "TimeoutError", "(", ")", ")", "self", ".", "_garbage_collect", "(", ")", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "timeout_handle", "=", "io_loop", ".", "add_timeout", "(", "timeout", ",", "on_timeout", ")", "waiter", ".", "add_done_callback", "(", "lambda", "_", ":", "io_loop", ".", "remove_timeout", "(", "timeout_handle", ")", ")", "return", "waiter" ]
Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline.
[ "Decrement", "the", "counter", ".", "Returns", "an", "awaitable", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L414-L440
26,825
tornadoweb/tornado
tornado/locks.py
Lock.acquire
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._block.acquire(timeout)
python
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._block.acquire(timeout)
[ "def", "acquire", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "_ReleasingContextManager", "]", ":", "return", "self", ".", "_block", ".", "acquire", "(", "timeout", ")" ]
Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout.
[ "Attempt", "to", "lock", ".", "Returns", "an", "awaitable", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locks.py#L528-L536
26,826
tornadoweb/tornado
tornado/http1connection.py
HTTP1Connection.read_response
def read_response(self, delegate: httputil.HTTPMessageDelegate) -> Awaitable[bool]: """Read a single HTTP response. Typical client-mode usage is to write a request using `write_headers`, `write`, and `finish`, and then call ``read_response``. :arg delegate: a `.HTTPMessageDelegate` Returns a `.Future` that resolves to a bool after the full response has been read. The result is true if the stream is still open. """ if self.params.decompress: delegate = _GzipMessageDelegate(delegate, self.params.chunk_size) return self._read_message(delegate)
python
def read_response(self, delegate: httputil.HTTPMessageDelegate) -> Awaitable[bool]: """Read a single HTTP response. Typical client-mode usage is to write a request using `write_headers`, `write`, and `finish`, and then call ``read_response``. :arg delegate: a `.HTTPMessageDelegate` Returns a `.Future` that resolves to a bool after the full response has been read. The result is true if the stream is still open. """ if self.params.decompress: delegate = _GzipMessageDelegate(delegate, self.params.chunk_size) return self._read_message(delegate)
[ "def", "read_response", "(", "self", ",", "delegate", ":", "httputil", ".", "HTTPMessageDelegate", ")", "->", "Awaitable", "[", "bool", "]", ":", "if", "self", ".", "params", ".", "decompress", ":", "delegate", "=", "_GzipMessageDelegate", "(", "delegate", ",", "self", ".", "params", ".", "chunk_size", ")", "return", "self", ".", "_read_message", "(", "delegate", ")" ]
Read a single HTTP response. Typical client-mode usage is to write a request using `write_headers`, `write`, and `finish`, and then call ``read_response``. :arg delegate: a `.HTTPMessageDelegate` Returns a `.Future` that resolves to a bool after the full response has been read. The result is true if the stream is still open.
[ "Read", "a", "single", "HTTP", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L165-L178
26,827
tornadoweb/tornado
tornado/http1connection.py
HTTP1Connection._clear_callbacks
def _clear_callbacks(self) -> None: """Clears the callback attributes. This allows the request handler to be garbage collected more quickly in CPython by breaking up reference cycles. """ self._write_callback = None self._write_future = None # type: Optional[Future[None]] self._close_callback = None # type: Optional[Callable[[], None]] if self.stream is not None: self.stream.set_close_callback(None)
python
def _clear_callbacks(self) -> None: """Clears the callback attributes. This allows the request handler to be garbage collected more quickly in CPython by breaking up reference cycles. """ self._write_callback = None self._write_future = None # type: Optional[Future[None]] self._close_callback = None # type: Optional[Callable[[], None]] if self.stream is not None: self.stream.set_close_callback(None)
[ "def", "_clear_callbacks", "(", "self", ")", "->", "None", ":", "self", ".", "_write_callback", "=", "None", "self", ".", "_write_future", "=", "None", "# type: Optional[Future[None]]", "self", ".", "_close_callback", "=", "None", "# type: Optional[Callable[[], None]]", "if", "self", ".", "stream", "is", "not", "None", ":", "self", ".", "stream", ".", "set_close_callback", "(", "None", ")" ]
Clears the callback attributes. This allows the request handler to be garbage collected more quickly in CPython by breaking up reference cycles.
[ "Clears", "the", "callback", "attributes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L302-L312
26,828
tornadoweb/tornado
tornado/http1connection.py
HTTP1Connection.write_headers
def write_headers( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Implements `.HTTPConnection.write_headers`.""" lines = [] if self.is_client: assert isinstance(start_line, httputil.RequestStartLine) self._request_start_line = start_line lines.append(utf8("%s %s HTTP/1.1" % (start_line[0], start_line[1]))) # Client requests with a non-empty body must have either a # Content-Length or a Transfer-Encoding. self._chunking_output = ( start_line.method in ("POST", "PUT", "PATCH") and "Content-Length" not in headers and ( "Transfer-Encoding" not in headers or headers["Transfer-Encoding"] == "chunked" ) ) else: assert isinstance(start_line, httputil.ResponseStartLine) assert self._request_start_line is not None assert self._request_headers is not None self._response_start_line = start_line lines.append(utf8("HTTP/1.1 %d %s" % (start_line[1], start_line[2]))) self._chunking_output = ( # TODO: should this use # self._request_start_line.version or # start_line.version? self._request_start_line.version == "HTTP/1.1" # 1xx, 204 and 304 responses have no body (not even a zero-length # body), and so should not have either Content-Length or # Transfer-Encoding headers. and start_line.code not in (204, 304) and (start_line.code < 100 or start_line.code >= 200) # No need to chunk the output if a Content-Length is specified. and "Content-Length" not in headers # Applications are discouraged from touching Transfer-Encoding, # but if they do, leave it alone. and "Transfer-Encoding" not in headers ) # If connection to a 1.1 client will be closed, inform client if ( self._request_start_line.version == "HTTP/1.1" and self._disconnect_on_finish ): headers["Connection"] = "close" # If a 1.0 client asked for keep-alive, add the header. if ( self._request_start_line.version == "HTTP/1.0" and self._request_headers.get("Connection", "").lower() == "keep-alive" ): headers["Connection"] = "Keep-Alive" if self._chunking_output: headers["Transfer-Encoding"] = "chunked" if not self.is_client and ( self._request_start_line.method == "HEAD" or cast(httputil.ResponseStartLine, start_line).code == 304 ): self._expected_content_remaining = 0 elif "Content-Length" in headers: self._expected_content_remaining = int(headers["Content-Length"]) else: self._expected_content_remaining = None # TODO: headers are supposed to be of type str, but we still have some # cases that let bytes slip through. Remove these native_str calls when those # are fixed. header_lines = ( native_str(n) + ": " + native_str(v) for n, v in headers.get_all() ) lines.extend(l.encode("latin1") for l in header_lines) for line in lines: if b"\n" in line: raise ValueError("Newline in header: " + repr(line)) future = None if self.stream.closed(): future = self._write_future = Future() future.set_exception(iostream.StreamClosedError()) future.exception() else: future = self._write_future = Future() data = b"\r\n".join(lines) + b"\r\n\r\n" if chunk: data += self._format_chunk(chunk) self._pending_write = self.stream.write(data) future_add_done_callback(self._pending_write, self._on_write_complete) return future
python
def write_headers( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Implements `.HTTPConnection.write_headers`.""" lines = [] if self.is_client: assert isinstance(start_line, httputil.RequestStartLine) self._request_start_line = start_line lines.append(utf8("%s %s HTTP/1.1" % (start_line[0], start_line[1]))) # Client requests with a non-empty body must have either a # Content-Length or a Transfer-Encoding. self._chunking_output = ( start_line.method in ("POST", "PUT", "PATCH") and "Content-Length" not in headers and ( "Transfer-Encoding" not in headers or headers["Transfer-Encoding"] == "chunked" ) ) else: assert isinstance(start_line, httputil.ResponseStartLine) assert self._request_start_line is not None assert self._request_headers is not None self._response_start_line = start_line lines.append(utf8("HTTP/1.1 %d %s" % (start_line[1], start_line[2]))) self._chunking_output = ( # TODO: should this use # self._request_start_line.version or # start_line.version? self._request_start_line.version == "HTTP/1.1" # 1xx, 204 and 304 responses have no body (not even a zero-length # body), and so should not have either Content-Length or # Transfer-Encoding headers. and start_line.code not in (204, 304) and (start_line.code < 100 or start_line.code >= 200) # No need to chunk the output if a Content-Length is specified. and "Content-Length" not in headers # Applications are discouraged from touching Transfer-Encoding, # but if they do, leave it alone. and "Transfer-Encoding" not in headers ) # If connection to a 1.1 client will be closed, inform client if ( self._request_start_line.version == "HTTP/1.1" and self._disconnect_on_finish ): headers["Connection"] = "close" # If a 1.0 client asked for keep-alive, add the header. if ( self._request_start_line.version == "HTTP/1.0" and self._request_headers.get("Connection", "").lower() == "keep-alive" ): headers["Connection"] = "Keep-Alive" if self._chunking_output: headers["Transfer-Encoding"] = "chunked" if not self.is_client and ( self._request_start_line.method == "HEAD" or cast(httputil.ResponseStartLine, start_line).code == 304 ): self._expected_content_remaining = 0 elif "Content-Length" in headers: self._expected_content_remaining = int(headers["Content-Length"]) else: self._expected_content_remaining = None # TODO: headers are supposed to be of type str, but we still have some # cases that let bytes slip through. Remove these native_str calls when those # are fixed. header_lines = ( native_str(n) + ": " + native_str(v) for n, v in headers.get_all() ) lines.extend(l.encode("latin1") for l in header_lines) for line in lines: if b"\n" in line: raise ValueError("Newline in header: " + repr(line)) future = None if self.stream.closed(): future = self._write_future = Future() future.set_exception(iostream.StreamClosedError()) future.exception() else: future = self._write_future = Future() data = b"\r\n".join(lines) + b"\r\n\r\n" if chunk: data += self._format_chunk(chunk) self._pending_write = self.stream.write(data) future_add_done_callback(self._pending_write, self._on_write_complete) return future
[ "def", "write_headers", "(", "self", ",", "start_line", ":", "Union", "[", "httputil", ".", "RequestStartLine", ",", "httputil", ".", "ResponseStartLine", "]", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ",", "chunk", ":", "bytes", "=", "None", ",", ")", "->", "\"Future[None]\"", ":", "lines", "=", "[", "]", "if", "self", ".", "is_client", ":", "assert", "isinstance", "(", "start_line", ",", "httputil", ".", "RequestStartLine", ")", "self", ".", "_request_start_line", "=", "start_line", "lines", ".", "append", "(", "utf8", "(", "\"%s %s HTTP/1.1\"", "%", "(", "start_line", "[", "0", "]", ",", "start_line", "[", "1", "]", ")", ")", ")", "# Client requests with a non-empty body must have either a", "# Content-Length or a Transfer-Encoding.", "self", ".", "_chunking_output", "=", "(", "start_line", ".", "method", "in", "(", "\"POST\"", ",", "\"PUT\"", ",", "\"PATCH\"", ")", "and", "\"Content-Length\"", "not", "in", "headers", "and", "(", "\"Transfer-Encoding\"", "not", "in", "headers", "or", "headers", "[", "\"Transfer-Encoding\"", "]", "==", "\"chunked\"", ")", ")", "else", ":", "assert", "isinstance", "(", "start_line", ",", "httputil", ".", "ResponseStartLine", ")", "assert", "self", ".", "_request_start_line", "is", "not", "None", "assert", "self", ".", "_request_headers", "is", "not", "None", "self", ".", "_response_start_line", "=", "start_line", "lines", ".", "append", "(", "utf8", "(", "\"HTTP/1.1 %d %s\"", "%", "(", "start_line", "[", "1", "]", ",", "start_line", "[", "2", "]", ")", ")", ")", "self", ".", "_chunking_output", "=", "(", "# TODO: should this use", "# self._request_start_line.version or", "# start_line.version?", "self", ".", "_request_start_line", ".", "version", "==", "\"HTTP/1.1\"", "# 1xx, 204 and 304 responses have no body (not even a zero-length", "# body), and so should not have either Content-Length or", "# Transfer-Encoding headers.", "and", "start_line", ".", "code", "not", "in", "(", "204", ",", "304", ")", "and", "(", "start_line", ".", "code", "<", "100", "or", "start_line", ".", "code", ">=", "200", ")", "# No need to chunk the output if a Content-Length is specified.", "and", "\"Content-Length\"", "not", "in", "headers", "# Applications are discouraged from touching Transfer-Encoding,", "# but if they do, leave it alone.", "and", "\"Transfer-Encoding\"", "not", "in", "headers", ")", "# If connection to a 1.1 client will be closed, inform client", "if", "(", "self", ".", "_request_start_line", ".", "version", "==", "\"HTTP/1.1\"", "and", "self", ".", "_disconnect_on_finish", ")", ":", "headers", "[", "\"Connection\"", "]", "=", "\"close\"", "# If a 1.0 client asked for keep-alive, add the header.", "if", "(", "self", ".", "_request_start_line", ".", "version", "==", "\"HTTP/1.0\"", "and", "self", ".", "_request_headers", ".", "get", "(", "\"Connection\"", ",", "\"\"", ")", ".", "lower", "(", ")", "==", "\"keep-alive\"", ")", ":", "headers", "[", "\"Connection\"", "]", "=", "\"Keep-Alive\"", "if", "self", ".", "_chunking_output", ":", "headers", "[", "\"Transfer-Encoding\"", "]", "=", "\"chunked\"", "if", "not", "self", ".", "is_client", "and", "(", "self", ".", "_request_start_line", ".", "method", "==", "\"HEAD\"", "or", "cast", "(", "httputil", ".", "ResponseStartLine", ",", "start_line", ")", ".", "code", "==", "304", ")", ":", "self", ".", "_expected_content_remaining", "=", "0", "elif", "\"Content-Length\"", "in", "headers", ":", "self", ".", "_expected_content_remaining", "=", "int", "(", "headers", "[", "\"Content-Length\"", "]", ")", "else", ":", "self", ".", "_expected_content_remaining", "=", "None", "# TODO: headers are supposed to be of type str, but we still have some", "# cases that let bytes slip through. Remove these native_str calls when those", "# are fixed.", "header_lines", "=", "(", "native_str", "(", "n", ")", "+", "\": \"", "+", "native_str", "(", "v", ")", "for", "n", ",", "v", "in", "headers", ".", "get_all", "(", ")", ")", "lines", ".", "extend", "(", "l", ".", "encode", "(", "\"latin1\"", ")", "for", "l", "in", "header_lines", ")", "for", "line", "in", "lines", ":", "if", "b\"\\n\"", "in", "line", ":", "raise", "ValueError", "(", "\"Newline in header: \"", "+", "repr", "(", "line", ")", ")", "future", "=", "None", "if", "self", ".", "stream", ".", "closed", "(", ")", ":", "future", "=", "self", ".", "_write_future", "=", "Future", "(", ")", "future", ".", "set_exception", "(", "iostream", ".", "StreamClosedError", "(", ")", ")", "future", ".", "exception", "(", ")", "else", ":", "future", "=", "self", ".", "_write_future", "=", "Future", "(", ")", "data", "=", "b\"\\r\\n\"", ".", "join", "(", "lines", ")", "+", "b\"\\r\\n\\r\\n\"", "if", "chunk", ":", "data", "+=", "self", ".", "_format_chunk", "(", "chunk", ")", "self", ".", "_pending_write", "=", "self", ".", "stream", ".", "write", "(", "data", ")", "future_add_done_callback", "(", "self", ".", "_pending_write", ",", "self", ".", "_on_write_complete", ")", "return", "future" ]
Implements `.HTTPConnection.write_headers`.
[ "Implements", ".", "HTTPConnection", ".", "write_headers", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L376-L465
26,829
tornadoweb/tornado
tornado/http1connection.py
HTTP1Connection.write
def write(self, chunk: bytes) -> "Future[None]": """Implements `.HTTPConnection.write`. For backwards compatibility it is allowed but deprecated to skip `write_headers` and instead call `write()` with a pre-encoded header block. """ future = None if self.stream.closed(): future = self._write_future = Future() self._write_future.set_exception(iostream.StreamClosedError()) self._write_future.exception() else: future = self._write_future = Future() self._pending_write = self.stream.write(self._format_chunk(chunk)) future_add_done_callback(self._pending_write, self._on_write_complete) return future
python
def write(self, chunk: bytes) -> "Future[None]": """Implements `.HTTPConnection.write`. For backwards compatibility it is allowed but deprecated to skip `write_headers` and instead call `write()` with a pre-encoded header block. """ future = None if self.stream.closed(): future = self._write_future = Future() self._write_future.set_exception(iostream.StreamClosedError()) self._write_future.exception() else: future = self._write_future = Future() self._pending_write = self.stream.write(self._format_chunk(chunk)) future_add_done_callback(self._pending_write, self._on_write_complete) return future
[ "def", "write", "(", "self", ",", "chunk", ":", "bytes", ")", "->", "\"Future[None]\"", ":", "future", "=", "None", "if", "self", ".", "stream", ".", "closed", "(", ")", ":", "future", "=", "self", ".", "_write_future", "=", "Future", "(", ")", "self", ".", "_write_future", ".", "set_exception", "(", "iostream", ".", "StreamClosedError", "(", ")", ")", "self", ".", "_write_future", ".", "exception", "(", ")", "else", ":", "future", "=", "self", ".", "_write_future", "=", "Future", "(", ")", "self", ".", "_pending_write", "=", "self", ".", "stream", ".", "write", "(", "self", ".", "_format_chunk", "(", "chunk", ")", ")", "future_add_done_callback", "(", "self", ".", "_pending_write", ",", "self", ".", "_on_write_complete", ")", "return", "future" ]
Implements `.HTTPConnection.write`. For backwards compatibility it is allowed but deprecated to skip `write_headers` and instead call `write()` with a pre-encoded header block.
[ "Implements", ".", "HTTPConnection", ".", "write", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L483-L499
26,830
tornadoweb/tornado
tornado/http1connection.py
HTTP1Connection.finish
def finish(self) -> None: """Implements `.HTTPConnection.finish`.""" if ( self._expected_content_remaining is not None and self._expected_content_remaining != 0 and not self.stream.closed() ): self.stream.close() raise httputil.HTTPOutputError( "Tried to write %d bytes less than Content-Length" % self._expected_content_remaining ) if self._chunking_output: if not self.stream.closed(): self._pending_write = self.stream.write(b"0\r\n\r\n") self._pending_write.add_done_callback(self._on_write_complete) self._write_finished = True # If the app finished the request while we're still reading, # divert any remaining data away from the delegate and # close the connection when we're done sending our response. # Closing the connection is the only way to avoid reading the # whole input body. if not self._read_finished: self._disconnect_on_finish = True # No more data is coming, so instruct TCP to send any remaining # data immediately instead of waiting for a full packet or ack. self.stream.set_nodelay(True) if self._pending_write is None: self._finish_request(None) else: future_add_done_callback(self._pending_write, self._finish_request)
python
def finish(self) -> None: """Implements `.HTTPConnection.finish`.""" if ( self._expected_content_remaining is not None and self._expected_content_remaining != 0 and not self.stream.closed() ): self.stream.close() raise httputil.HTTPOutputError( "Tried to write %d bytes less than Content-Length" % self._expected_content_remaining ) if self._chunking_output: if not self.stream.closed(): self._pending_write = self.stream.write(b"0\r\n\r\n") self._pending_write.add_done_callback(self._on_write_complete) self._write_finished = True # If the app finished the request while we're still reading, # divert any remaining data away from the delegate and # close the connection when we're done sending our response. # Closing the connection is the only way to avoid reading the # whole input body. if not self._read_finished: self._disconnect_on_finish = True # No more data is coming, so instruct TCP to send any remaining # data immediately instead of waiting for a full packet or ack. self.stream.set_nodelay(True) if self._pending_write is None: self._finish_request(None) else: future_add_done_callback(self._pending_write, self._finish_request)
[ "def", "finish", "(", "self", ")", "->", "None", ":", "if", "(", "self", ".", "_expected_content_remaining", "is", "not", "None", "and", "self", ".", "_expected_content_remaining", "!=", "0", "and", "not", "self", ".", "stream", ".", "closed", "(", ")", ")", ":", "self", ".", "stream", ".", "close", "(", ")", "raise", "httputil", ".", "HTTPOutputError", "(", "\"Tried to write %d bytes less than Content-Length\"", "%", "self", ".", "_expected_content_remaining", ")", "if", "self", ".", "_chunking_output", ":", "if", "not", "self", ".", "stream", ".", "closed", "(", ")", ":", "self", ".", "_pending_write", "=", "self", ".", "stream", ".", "write", "(", "b\"0\\r\\n\\r\\n\"", ")", "self", ".", "_pending_write", ".", "add_done_callback", "(", "self", ".", "_on_write_complete", ")", "self", ".", "_write_finished", "=", "True", "# If the app finished the request while we're still reading,", "# divert any remaining data away from the delegate and", "# close the connection when we're done sending our response.", "# Closing the connection is the only way to avoid reading the", "# whole input body.", "if", "not", "self", ".", "_read_finished", ":", "self", ".", "_disconnect_on_finish", "=", "True", "# No more data is coming, so instruct TCP to send any remaining", "# data immediately instead of waiting for a full packet or ack.", "self", ".", "stream", ".", "set_nodelay", "(", "True", ")", "if", "self", ".", "_pending_write", "is", "None", ":", "self", ".", "_finish_request", "(", "None", ")", "else", ":", "future_add_done_callback", "(", "self", ".", "_pending_write", ",", "self", ".", "_finish_request", ")" ]
Implements `.HTTPConnection.finish`.
[ "Implements", ".", "HTTPConnection", ".", "finish", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L501-L531
26,831
tornadoweb/tornado
tornado/http1connection.py
HTTP1ServerConnection.start_serving
def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None: """Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate` """ assert isinstance(delegate, httputil.HTTPServerConnectionDelegate) fut = gen.convert_yielded(self._server_request_loop(delegate)) self._serving_future = fut # Register the future on the IOLoop so its errors get logged. self.stream.io_loop.add_future(fut, lambda f: f.result())
python
def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None: """Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate` """ assert isinstance(delegate, httputil.HTTPServerConnectionDelegate) fut = gen.convert_yielded(self._server_request_loop(delegate)) self._serving_future = fut # Register the future on the IOLoop so its errors get logged. self.stream.io_loop.add_future(fut, lambda f: f.result())
[ "def", "start_serving", "(", "self", ",", "delegate", ":", "httputil", ".", "HTTPServerConnectionDelegate", ")", "->", "None", ":", "assert", "isinstance", "(", "delegate", ",", "httputil", ".", "HTTPServerConnectionDelegate", ")", "fut", "=", "gen", ".", "convert_yielded", "(", "self", ".", "_server_request_loop", "(", "delegate", ")", ")", "self", ".", "_serving_future", "=", "fut", "# Register the future on the IOLoop so its errors get logged.", "self", ".", "stream", ".", "io_loop", ".", "add_future", "(", "fut", ",", "lambda", "f", ":", "f", ".", "result", "(", ")", ")" ]
Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate`
[ "Starts", "serving", "requests", "on", "this", "connection", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L798-L807
26,832
tornadoweb/tornado
tornado/websocket.py
websocket_connect
def websocket_connect( url: Union[str, httpclient.HTTPRequest], callback: Callable[["Future[WebSocketClientConnection]"], None] = None, connect_timeout: float = None, on_message_callback: Callable[[Union[None, str, bytes]], None] = None, compression_options: Dict[str, Any] = None, ping_interval: float = None, ping_timeout: float = None, max_message_size: int = _default_max_message_size, subprotocols: List[str] = None, ) -> "Awaitable[WebSocketClientConnection]": """Client-side websocket support. Takes a url and returns a Future whose result is a `WebSocketClientConnection`. ``compression_options`` is interpreted in the same way as the return value of `.WebSocketHandler.get_compression_options`. The connection supports two styles of operation. In the coroutine style, the application typically calls `~.WebSocketClientConnection.read_message` in a loop:: conn = yield websocket_connect(url) while True: msg = yield conn.read_message() if msg is None: break # Do something with msg In the callback style, pass an ``on_message_callback`` to ``websocket_connect``. In both styles, a message of ``None`` indicates that the connection has been closed. ``subprotocols`` may be a list of strings specifying proposed subprotocols. The selected protocol may be found on the ``selected_subprotocol`` attribute of the connection object when the connection is complete. .. versionchanged:: 3.2 Also accepts ``HTTPRequest`` objects in place of urls. .. versionchanged:: 4.1 Added ``compression_options`` and ``on_message_callback``. .. versionchanged:: 4.5 Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size`` arguments, which have the same meaning as in `WebSocketHandler`. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.1 Added the ``subprotocols`` argument. """ if isinstance(url, httpclient.HTTPRequest): assert connect_timeout is None request = url # Copy and convert the headers dict/object (see comments in # AsyncHTTPClient.fetch) request.headers = httputil.HTTPHeaders(request.headers) else: request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout) request = cast( httpclient.HTTPRequest, httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS), ) conn = WebSocketClientConnection( request, on_message_callback=on_message_callback, compression_options=compression_options, ping_interval=ping_interval, ping_timeout=ping_timeout, max_message_size=max_message_size, subprotocols=subprotocols, ) if callback is not None: IOLoop.current().add_future(conn.connect_future, callback) return conn.connect_future
python
def websocket_connect( url: Union[str, httpclient.HTTPRequest], callback: Callable[["Future[WebSocketClientConnection]"], None] = None, connect_timeout: float = None, on_message_callback: Callable[[Union[None, str, bytes]], None] = None, compression_options: Dict[str, Any] = None, ping_interval: float = None, ping_timeout: float = None, max_message_size: int = _default_max_message_size, subprotocols: List[str] = None, ) -> "Awaitable[WebSocketClientConnection]": """Client-side websocket support. Takes a url and returns a Future whose result is a `WebSocketClientConnection`. ``compression_options`` is interpreted in the same way as the return value of `.WebSocketHandler.get_compression_options`. The connection supports two styles of operation. In the coroutine style, the application typically calls `~.WebSocketClientConnection.read_message` in a loop:: conn = yield websocket_connect(url) while True: msg = yield conn.read_message() if msg is None: break # Do something with msg In the callback style, pass an ``on_message_callback`` to ``websocket_connect``. In both styles, a message of ``None`` indicates that the connection has been closed. ``subprotocols`` may be a list of strings specifying proposed subprotocols. The selected protocol may be found on the ``selected_subprotocol`` attribute of the connection object when the connection is complete. .. versionchanged:: 3.2 Also accepts ``HTTPRequest`` objects in place of urls. .. versionchanged:: 4.1 Added ``compression_options`` and ``on_message_callback``. .. versionchanged:: 4.5 Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size`` arguments, which have the same meaning as in `WebSocketHandler`. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.1 Added the ``subprotocols`` argument. """ if isinstance(url, httpclient.HTTPRequest): assert connect_timeout is None request = url # Copy and convert the headers dict/object (see comments in # AsyncHTTPClient.fetch) request.headers = httputil.HTTPHeaders(request.headers) else: request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout) request = cast( httpclient.HTTPRequest, httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS), ) conn = WebSocketClientConnection( request, on_message_callback=on_message_callback, compression_options=compression_options, ping_interval=ping_interval, ping_timeout=ping_timeout, max_message_size=max_message_size, subprotocols=subprotocols, ) if callback is not None: IOLoop.current().add_future(conn.connect_future, callback) return conn.connect_future
[ "def", "websocket_connect", "(", "url", ":", "Union", "[", "str", ",", "httpclient", ".", "HTTPRequest", "]", ",", "callback", ":", "Callable", "[", "[", "\"Future[WebSocketClientConnection]\"", "]", ",", "None", "]", "=", "None", ",", "connect_timeout", ":", "float", "=", "None", ",", "on_message_callback", ":", "Callable", "[", "[", "Union", "[", "None", ",", "str", ",", "bytes", "]", "]", ",", "None", "]", "=", "None", ",", "compression_options", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "ping_interval", ":", "float", "=", "None", ",", "ping_timeout", ":", "float", "=", "None", ",", "max_message_size", ":", "int", "=", "_default_max_message_size", ",", "subprotocols", ":", "List", "[", "str", "]", "=", "None", ",", ")", "->", "\"Awaitable[WebSocketClientConnection]\"", ":", "if", "isinstance", "(", "url", ",", "httpclient", ".", "HTTPRequest", ")", ":", "assert", "connect_timeout", "is", "None", "request", "=", "url", "# Copy and convert the headers dict/object (see comments in", "# AsyncHTTPClient.fetch)", "request", ".", "headers", "=", "httputil", ".", "HTTPHeaders", "(", "request", ".", "headers", ")", "else", ":", "request", "=", "httpclient", ".", "HTTPRequest", "(", "url", ",", "connect_timeout", "=", "connect_timeout", ")", "request", "=", "cast", "(", "httpclient", ".", "HTTPRequest", ",", "httpclient", ".", "_RequestProxy", "(", "request", ",", "httpclient", ".", "HTTPRequest", ".", "_DEFAULTS", ")", ",", ")", "conn", "=", "WebSocketClientConnection", "(", "request", ",", "on_message_callback", "=", "on_message_callback", ",", "compression_options", "=", "compression_options", ",", "ping_interval", "=", "ping_interval", ",", "ping_timeout", "=", "ping_timeout", ",", "max_message_size", "=", "max_message_size", ",", "subprotocols", "=", "subprotocols", ",", ")", "if", "callback", "is", "not", "None", ":", "IOLoop", ".", "current", "(", ")", ".", "add_future", "(", "conn", ".", "connect_future", ",", "callback", ")", "return", "conn", ".", "connect_future" ]
Client-side websocket support. Takes a url and returns a Future whose result is a `WebSocketClientConnection`. ``compression_options`` is interpreted in the same way as the return value of `.WebSocketHandler.get_compression_options`. The connection supports two styles of operation. In the coroutine style, the application typically calls `~.WebSocketClientConnection.read_message` in a loop:: conn = yield websocket_connect(url) while True: msg = yield conn.read_message() if msg is None: break # Do something with msg In the callback style, pass an ``on_message_callback`` to ``websocket_connect``. In both styles, a message of ``None`` indicates that the connection has been closed. ``subprotocols`` may be a list of strings specifying proposed subprotocols. The selected protocol may be found on the ``selected_subprotocol`` attribute of the connection object when the connection is complete. .. versionchanged:: 3.2 Also accepts ``HTTPRequest`` objects in place of urls. .. versionchanged:: 4.1 Added ``compression_options`` and ``on_message_callback``. .. versionchanged:: 4.5 Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size`` arguments, which have the same meaning as in `WebSocketHandler`. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.1 Added the ``subprotocols`` argument.
[ "Client", "-", "side", "websocket", "support", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1586-L1663
26,833
tornadoweb/tornado
tornado/websocket.py
WebSocketHandler.close
def close(self, code: int = None, reason: str = None) -> None: """Closes this Web Socket. Once the close handshake is successful the socket will be closed. ``code`` may be a numeric status code, taken from the values defined in `RFC 6455 section 7.4.1 <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_. ``reason`` may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol. .. versionchanged:: 4.0 Added the ``code`` and ``reason`` arguments. """ if self.ws_connection: self.ws_connection.close(code, reason) self.ws_connection = None
python
def close(self, code: int = None, reason: str = None) -> None: """Closes this Web Socket. Once the close handshake is successful the socket will be closed. ``code`` may be a numeric status code, taken from the values defined in `RFC 6455 section 7.4.1 <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_. ``reason`` may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol. .. versionchanged:: 4.0 Added the ``code`` and ``reason`` arguments. """ if self.ws_connection: self.ws_connection.close(code, reason) self.ws_connection = None
[ "def", "close", "(", "self", ",", "code", ":", "int", "=", "None", ",", "reason", ":", "str", "=", "None", ")", "->", "None", ":", "if", "self", ".", "ws_connection", ":", "self", ".", "ws_connection", ".", "close", "(", "code", ",", "reason", ")", "self", ".", "ws_connection", "=", "None" ]
Closes this Web Socket. Once the close handshake is successful the socket will be closed. ``code`` may be a numeric status code, taken from the values defined in `RFC 6455 section 7.4.1 <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_. ``reason`` may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol. .. versionchanged:: 4.0 Added the ``code`` and ``reason`` arguments.
[ "Closes", "this", "Web", "Socket", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L471-L489
26,834
tornadoweb/tornado
tornado/websocket.py
WebSocketHandler.check_origin
def check_origin(self, origin: str) -> bool: """Override to enable support for allowing alternate origins. The ``origin`` argument is the value of the ``Origin`` HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebSockets support this header, and non-browser clients do not have the same cross-site security concerns). Should return ``True`` to accept the request or ``False`` to reject it. By default, rejects all requests with an origin on a host other than this one. This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don't use CORS headers. .. warning:: This is an important security measure; don't disable it without understanding the security implications. In particular, if your authentication is cookie-based, you must either restrict the origins allowed by ``check_origin()`` or implement your own XSRF-like protection for websocket connections. See `these <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_ `articles <https://devcenter.heroku.com/articles/websocket-security>`_ for more. To accept all cross-origin traffic (which was the default prior to Tornado 4.0), simply override this method to always return ``True``:: def check_origin(self, origin): return True To allow connections from any subdomain of your site, you might do something like:: def check_origin(self, origin): parsed_origin = urllib.parse.urlparse(origin) return parsed_origin.netloc.endswith(".mydomain.com") .. versionadded:: 4.0 """ parsed_origin = urlparse(origin) origin = parsed_origin.netloc origin = origin.lower() host = self.request.headers.get("Host") # Check to see that origin matches host directly, including ports return origin == host
python
def check_origin(self, origin: str) -> bool: """Override to enable support for allowing alternate origins. The ``origin`` argument is the value of the ``Origin`` HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebSockets support this header, and non-browser clients do not have the same cross-site security concerns). Should return ``True`` to accept the request or ``False`` to reject it. By default, rejects all requests with an origin on a host other than this one. This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don't use CORS headers. .. warning:: This is an important security measure; don't disable it without understanding the security implications. In particular, if your authentication is cookie-based, you must either restrict the origins allowed by ``check_origin()`` or implement your own XSRF-like protection for websocket connections. See `these <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_ `articles <https://devcenter.heroku.com/articles/websocket-security>`_ for more. To accept all cross-origin traffic (which was the default prior to Tornado 4.0), simply override this method to always return ``True``:: def check_origin(self, origin): return True To allow connections from any subdomain of your site, you might do something like:: def check_origin(self, origin): parsed_origin = urllib.parse.urlparse(origin) return parsed_origin.netloc.endswith(".mydomain.com") .. versionadded:: 4.0 """ parsed_origin = urlparse(origin) origin = parsed_origin.netloc origin = origin.lower() host = self.request.headers.get("Host") # Check to see that origin matches host directly, including ports return origin == host
[ "def", "check_origin", "(", "self", ",", "origin", ":", "str", ")", "->", "bool", ":", "parsed_origin", "=", "urlparse", "(", "origin", ")", "origin", "=", "parsed_origin", ".", "netloc", "origin", "=", "origin", ".", "lower", "(", ")", "host", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "\"Host\"", ")", "# Check to see that origin matches host directly, including ports", "return", "origin", "==", "host" ]
Override to enable support for allowing alternate origins. The ``origin`` argument is the value of the ``Origin`` HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebSockets support this header, and non-browser clients do not have the same cross-site security concerns). Should return ``True`` to accept the request or ``False`` to reject it. By default, rejects all requests with an origin on a host other than this one. This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don't use CORS headers. .. warning:: This is an important security measure; don't disable it without understanding the security implications. In particular, if your authentication is cookie-based, you must either restrict the origins allowed by ``check_origin()`` or implement your own XSRF-like protection for websocket connections. See `these <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_ `articles <https://devcenter.heroku.com/articles/websocket-security>`_ for more. To accept all cross-origin traffic (which was the default prior to Tornado 4.0), simply override this method to always return ``True``:: def check_origin(self, origin): return True To allow connections from any subdomain of your site, you might do something like:: def check_origin(self, origin): parsed_origin = urllib.parse.urlparse(origin) return parsed_origin.netloc.endswith(".mydomain.com") .. versionadded:: 4.0
[ "Override", "to", "enable", "support", "for", "allowing", "alternate", "origins", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L491-L545
26,835
tornadoweb/tornado
tornado/websocket.py
WebSocketHandler.set_nodelay
def set_nodelay(self, value: bool) -> None: """Set the no-delay flag for this stream. By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle's algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call ``self.set_nodelay(True)`` once the websocket connection is established. See `.BaseIOStream.set_nodelay` for additional details. .. versionadded:: 3.1 """ assert self.ws_connection is not None self.ws_connection.set_nodelay(value)
python
def set_nodelay(self, value: bool) -> None: """Set the no-delay flag for this stream. By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle's algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call ``self.set_nodelay(True)`` once the websocket connection is established. See `.BaseIOStream.set_nodelay` for additional details. .. versionadded:: 3.1 """ assert self.ws_connection is not None self.ws_connection.set_nodelay(value)
[ "def", "set_nodelay", "(", "self", ",", "value", ":", "bool", ")", "->", "None", ":", "assert", "self", ".", "ws_connection", "is", "not", "None", "self", ".", "ws_connection", ".", "set_nodelay", "(", "value", ")" ]
Set the no-delay flag for this stream. By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle's algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call ``self.set_nodelay(True)`` once the websocket connection is established. See `.BaseIOStream.set_nodelay` for additional details. .. versionadded:: 3.1
[ "Set", "the", "no", "-", "delay", "flag", "for", "this", "stream", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L547-L562
26,836
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol._run_callback
def _run_callback( self, callback: Callable, *args: Any, **kwargs: Any ) -> "Optional[Future[Any]]": """Runs the given callback with exception handling. If the callback is a coroutine, returns its Future. On error, aborts the websocket connection and returns None. """ try: result = callback(*args, **kwargs) except Exception: self.handler.log_exception(*sys.exc_info()) self._abort() return None else: if result is not None: result = gen.convert_yielded(result) assert self.stream is not None self.stream.io_loop.add_future(result, lambda f: f.result()) return result
python
def _run_callback( self, callback: Callable, *args: Any, **kwargs: Any ) -> "Optional[Future[Any]]": """Runs the given callback with exception handling. If the callback is a coroutine, returns its Future. On error, aborts the websocket connection and returns None. """ try: result = callback(*args, **kwargs) except Exception: self.handler.log_exception(*sys.exc_info()) self._abort() return None else: if result is not None: result = gen.convert_yielded(result) assert self.stream is not None self.stream.io_loop.add_future(result, lambda f: f.result()) return result
[ "def", "_run_callback", "(", "self", ",", "callback", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"Optional[Future[Any]]\"", ":", "try", ":", "result", "=", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "self", ".", "handler", ".", "log_exception", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "self", ".", "_abort", "(", ")", "return", "None", "else", ":", "if", "result", "is", "not", "None", ":", "result", "=", "gen", ".", "convert_yielded", "(", "result", ")", "assert", "self", ".", "stream", "is", "not", "None", "self", ".", "stream", ".", "io_loop", ".", "add_future", "(", "result", ",", "lambda", "f", ":", "f", ".", "result", "(", ")", ")", "return", "result" ]
Runs the given callback with exception handling. If the callback is a coroutine, returns its Future. On error, aborts the websocket connection and returns None.
[ "Runs", "the", "given", "callback", "with", "exception", "handling", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L640-L659
26,837
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol._abort
def _abort(self) -> None: """Instantly aborts the WebSocket connection by closing the socket""" self.client_terminated = True self.server_terminated = True if self.stream is not None: self.stream.close() # forcibly tear down the connection self.close()
python
def _abort(self) -> None: """Instantly aborts the WebSocket connection by closing the socket""" self.client_terminated = True self.server_terminated = True if self.stream is not None: self.stream.close() # forcibly tear down the connection self.close()
[ "def", "_abort", "(", "self", ")", "->", "None", ":", "self", ".", "client_terminated", "=", "True", "self", ".", "server_terminated", "=", "True", "if", "self", ".", "stream", "is", "not", "None", ":", "self", ".", "stream", ".", "close", "(", ")", "# forcibly tear down the connection", "self", ".", "close", "(", ")" ]
Instantly aborts the WebSocket connection by closing the socket
[ "Instantly", "aborts", "the", "WebSocket", "connection", "by", "closing", "the", "socket" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L664-L670
26,838
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13._handle_websocket_headers
def _handle_websocket_headers(self, handler: WebSocketHandler) -> None: """Verifies all invariant- and required headers If a header is missing or have an incorrect value ValueError will be raised """ fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version") if not all(map(lambda f: handler.request.headers.get(f), fields)): raise ValueError("Missing/Invalid WebSocket headers")
python
def _handle_websocket_headers(self, handler: WebSocketHandler) -> None: """Verifies all invariant- and required headers If a header is missing or have an incorrect value ValueError will be raised """ fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version") if not all(map(lambda f: handler.request.headers.get(f), fields)): raise ValueError("Missing/Invalid WebSocket headers")
[ "def", "_handle_websocket_headers", "(", "self", ",", "handler", ":", "WebSocketHandler", ")", "->", "None", ":", "fields", "=", "(", "\"Host\"", ",", "\"Sec-Websocket-Key\"", ",", "\"Sec-Websocket-Version\"", ")", "if", "not", "all", "(", "map", "(", "lambda", "f", ":", "handler", ".", "request", ".", "headers", ".", "get", "(", "f", ")", ",", "fields", ")", ")", ":", "raise", "ValueError", "(", "\"Missing/Invalid WebSocket headers\"", ")" ]
Verifies all invariant- and required headers If a header is missing or have an incorrect value ValueError will be raised
[ "Verifies", "all", "invariant", "-", "and", "required", "headers" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L890-L898
26,839
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.compute_accept_value
def compute_accept_value(key: Union[str, bytes]) -> str: """Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key. """ sha1 = hashlib.sha1() sha1.update(utf8(key)) sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value return native_str(base64.b64encode(sha1.digest()))
python
def compute_accept_value(key: Union[str, bytes]) -> str: """Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key. """ sha1 = hashlib.sha1() sha1.update(utf8(key)) sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value return native_str(base64.b64encode(sha1.digest()))
[ "def", "compute_accept_value", "(", "key", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "str", ":", "sha1", "=", "hashlib", ".", "sha1", "(", ")", "sha1", ".", "update", "(", "utf8", "(", "key", ")", ")", "sha1", ".", "update", "(", "b\"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"", ")", "# Magic value", "return", "native_str", "(", "base64", ".", "b64encode", "(", "sha1", ".", "digest", "(", ")", ")", ")" ]
Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key.
[ "Computes", "the", "value", "for", "the", "Sec", "-", "WebSocket", "-", "Accept", "header", "given", "the", "value", "for", "Sec", "-", "WebSocket", "-", "Key", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L901-L908
26,840
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13._process_server_headers
def _process_server_headers( self, key: Union[str, bytes], headers: httputil.HTTPHeaders ) -> None: """Process the headers sent by the server to this client connection. 'key' is the websocket handshake challenge/response key. """ assert headers["Upgrade"].lower() == "websocket" assert headers["Connection"].lower() == "upgrade" accept = self.compute_accept_value(key) assert headers["Sec-Websocket-Accept"] == accept extensions = self._parse_extensions_header(headers) for ext in extensions: if ext[0] == "permessage-deflate" and self._compression_options is not None: self._create_compressors("client", ext[1]) else: raise ValueError("unsupported extension %r", ext) self.selected_subprotocol = headers.get("Sec-WebSocket-Protocol", None)
python
def _process_server_headers( self, key: Union[str, bytes], headers: httputil.HTTPHeaders ) -> None: """Process the headers sent by the server to this client connection. 'key' is the websocket handshake challenge/response key. """ assert headers["Upgrade"].lower() == "websocket" assert headers["Connection"].lower() == "upgrade" accept = self.compute_accept_value(key) assert headers["Sec-Websocket-Accept"] == accept extensions = self._parse_extensions_header(headers) for ext in extensions: if ext[0] == "permessage-deflate" and self._compression_options is not None: self._create_compressors("client", ext[1]) else: raise ValueError("unsupported extension %r", ext) self.selected_subprotocol = headers.get("Sec-WebSocket-Protocol", None)
[ "def", "_process_server_headers", "(", "self", ",", "key", ":", "Union", "[", "str", ",", "bytes", "]", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ")", "->", "None", ":", "assert", "headers", "[", "\"Upgrade\"", "]", ".", "lower", "(", ")", "==", "\"websocket\"", "assert", "headers", "[", "\"Connection\"", "]", ".", "lower", "(", ")", "==", "\"upgrade\"", "accept", "=", "self", ".", "compute_accept_value", "(", "key", ")", "assert", "headers", "[", "\"Sec-Websocket-Accept\"", "]", "==", "accept", "extensions", "=", "self", ".", "_parse_extensions_header", "(", "headers", ")", "for", "ext", "in", "extensions", ":", "if", "ext", "[", "0", "]", "==", "\"permessage-deflate\"", "and", "self", ".", "_compression_options", "is", "not", "None", ":", "self", ".", "_create_compressors", "(", "\"client\"", ",", "ext", "[", "1", "]", ")", "else", ":", "raise", "ValueError", "(", "\"unsupported extension %r\"", ",", "ext", ")", "self", ".", "selected_subprotocol", "=", "headers", ".", "get", "(", "\"Sec-WebSocket-Protocol\"", ",", "None", ")" ]
Process the headers sent by the server to this client connection. 'key' is the websocket handshake challenge/response key.
[ "Process", "the", "headers", "sent", "by", "the", "server", "to", "this", "client", "connection", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L974-L993
26,841
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13._get_compressor_options
def _get_compressor_options( self, side: str, agreed_parameters: Dict[str, Any], compression_options: Dict[str, Any] = None, ) -> Dict[str, Any]: """Converts a websocket agreed_parameters set to keyword arguments for our compressor objects. """ options = dict( persistent=(side + "_no_context_takeover") not in agreed_parameters ) # type: Dict[str, Any] wbits_header = agreed_parameters.get(side + "_max_window_bits", None) if wbits_header is None: options["max_wbits"] = zlib.MAX_WBITS else: options["max_wbits"] = int(wbits_header) options["compression_options"] = compression_options return options
python
def _get_compressor_options( self, side: str, agreed_parameters: Dict[str, Any], compression_options: Dict[str, Any] = None, ) -> Dict[str, Any]: """Converts a websocket agreed_parameters set to keyword arguments for our compressor objects. """ options = dict( persistent=(side + "_no_context_takeover") not in agreed_parameters ) # type: Dict[str, Any] wbits_header = agreed_parameters.get(side + "_max_window_bits", None) if wbits_header is None: options["max_wbits"] = zlib.MAX_WBITS else: options["max_wbits"] = int(wbits_header) options["compression_options"] = compression_options return options
[ "def", "_get_compressor_options", "(", "self", ",", "side", ":", "str", ",", "agreed_parameters", ":", "Dict", "[", "str", ",", "Any", "]", ",", "compression_options", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "options", "=", "dict", "(", "persistent", "=", "(", "side", "+", "\"_no_context_takeover\"", ")", "not", "in", "agreed_parameters", ")", "# type: Dict[str, Any]", "wbits_header", "=", "agreed_parameters", ".", "get", "(", "side", "+", "\"_max_window_bits\"", ",", "None", ")", "if", "wbits_header", "is", "None", ":", "options", "[", "\"max_wbits\"", "]", "=", "zlib", ".", "MAX_WBITS", "else", ":", "options", "[", "\"max_wbits\"", "]", "=", "int", "(", "wbits_header", ")", "options", "[", "\"compression_options\"", "]", "=", "compression_options", "return", "options" ]
Converts a websocket agreed_parameters set to keyword arguments for our compressor objects.
[ "Converts", "a", "websocket", "agreed_parameters", "set", "to", "keyword", "arguments", "for", "our", "compressor", "objects", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L995-L1013
26,842
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.write_ping
def write_ping(self, data: bytes) -> None: """Send ping frame.""" assert isinstance(data, bytes) self._write_frame(True, 0x9, data)
python
def write_ping(self, data: bytes) -> None: """Send ping frame.""" assert isinstance(data, bytes) self._write_frame(True, 0x9, data)
[ "def", "write_ping", "(", "self", ",", "data", ":", "bytes", ")", "->", "None", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", "self", ".", "_write_frame", "(", "True", ",", "0x9", ",", "data", ")" ]
Send ping frame.
[ "Send", "ping", "frame", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1110-L1113
26,843
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13._handle_message
def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]": """Execute on_message, returning its Future if it is a coroutine.""" if self.client_terminated: return None if self._frame_compressed: assert self._decompressor is not None try: data = self._decompressor.decompress(data) except _DecompressTooLargeError: self.close(1009, "message too big after decompression") self._abort() return None if opcode == 0x1: # UTF-8 data self._message_bytes_in += len(data) try: decoded = data.decode("utf-8") except UnicodeDecodeError: self._abort() return None return self._run_callback(self.handler.on_message, decoded) elif opcode == 0x2: # Binary data self._message_bytes_in += len(data) return self._run_callback(self.handler.on_message, data) elif opcode == 0x8: # Close self.client_terminated = True if len(data) >= 2: self.close_code = struct.unpack(">H", data[:2])[0] if len(data) > 2: self.close_reason = to_unicode(data[2:]) # Echo the received close code, if any (RFC 6455 section 5.5.1). self.close(self.close_code) elif opcode == 0x9: # Ping try: self._write_frame(True, 0xA, data) except StreamClosedError: self._abort() self._run_callback(self.handler.on_ping, data) elif opcode == 0xA: # Pong self.last_pong = IOLoop.current().time() return self._run_callback(self.handler.on_pong, data) else: self._abort() return None
python
def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]": """Execute on_message, returning its Future if it is a coroutine.""" if self.client_terminated: return None if self._frame_compressed: assert self._decompressor is not None try: data = self._decompressor.decompress(data) except _DecompressTooLargeError: self.close(1009, "message too big after decompression") self._abort() return None if opcode == 0x1: # UTF-8 data self._message_bytes_in += len(data) try: decoded = data.decode("utf-8") except UnicodeDecodeError: self._abort() return None return self._run_callback(self.handler.on_message, decoded) elif opcode == 0x2: # Binary data self._message_bytes_in += len(data) return self._run_callback(self.handler.on_message, data) elif opcode == 0x8: # Close self.client_terminated = True if len(data) >= 2: self.close_code = struct.unpack(">H", data[:2])[0] if len(data) > 2: self.close_reason = to_unicode(data[2:]) # Echo the received close code, if any (RFC 6455 section 5.5.1). self.close(self.close_code) elif opcode == 0x9: # Ping try: self._write_frame(True, 0xA, data) except StreamClosedError: self._abort() self._run_callback(self.handler.on_ping, data) elif opcode == 0xA: # Pong self.last_pong = IOLoop.current().time() return self._run_callback(self.handler.on_pong, data) else: self._abort() return None
[ "def", "_handle_message", "(", "self", ",", "opcode", ":", "int", ",", "data", ":", "bytes", ")", "->", "\"Optional[Future[None]]\"", ":", "if", "self", ".", "client_terminated", ":", "return", "None", "if", "self", ".", "_frame_compressed", ":", "assert", "self", ".", "_decompressor", "is", "not", "None", "try", ":", "data", "=", "self", ".", "_decompressor", ".", "decompress", "(", "data", ")", "except", "_DecompressTooLargeError", ":", "self", ".", "close", "(", "1009", ",", "\"message too big after decompression\"", ")", "self", ".", "_abort", "(", ")", "return", "None", "if", "opcode", "==", "0x1", ":", "# UTF-8 data", "self", ".", "_message_bytes_in", "+=", "len", "(", "data", ")", "try", ":", "decoded", "=", "data", ".", "decode", "(", "\"utf-8\"", ")", "except", "UnicodeDecodeError", ":", "self", ".", "_abort", "(", ")", "return", "None", "return", "self", ".", "_run_callback", "(", "self", ".", "handler", ".", "on_message", ",", "decoded", ")", "elif", "opcode", "==", "0x2", ":", "# Binary data", "self", ".", "_message_bytes_in", "+=", "len", "(", "data", ")", "return", "self", ".", "_run_callback", "(", "self", ".", "handler", ".", "on_message", ",", "data", ")", "elif", "opcode", "==", "0x8", ":", "# Close", "self", ".", "client_terminated", "=", "True", "if", "len", "(", "data", ")", ">=", "2", ":", "self", ".", "close_code", "=", "struct", ".", "unpack", "(", "\">H\"", ",", "data", "[", ":", "2", "]", ")", "[", "0", "]", "if", "len", "(", "data", ")", ">", "2", ":", "self", ".", "close_reason", "=", "to_unicode", "(", "data", "[", "2", ":", "]", ")", "# Echo the received close code, if any (RFC 6455 section 5.5.1).", "self", ".", "close", "(", "self", ".", "close_code", ")", "elif", "opcode", "==", "0x9", ":", "# Ping", "try", ":", "self", ".", "_write_frame", "(", "True", ",", "0xA", ",", "data", ")", "except", "StreamClosedError", ":", "self", ".", "_abort", "(", ")", "self", ".", "_run_callback", "(", "self", ".", "handler", ".", "on_ping", ",", "data", ")", "elif", "opcode", "==", "0xA", ":", "# Pong", "self", ".", "last_pong", "=", "IOLoop", ".", "current", "(", ")", ".", "time", "(", ")", "return", "self", ".", "_run_callback", "(", "self", ".", "handler", ".", "on_pong", ",", "data", ")", "else", ":", "self", ".", "_abort", "(", ")", "return", "None" ]
Execute on_message, returning its Future if it is a coroutine.
[ "Execute", "on_message", "returning", "its", "Future", "if", "it", "is", "a", "coroutine", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1211-L1260
26,844
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.close
def close(self, code: int = None, reason: str = None) -> None: """Closes the WebSocket connection.""" if not self.server_terminated: if not self.stream.closed(): if code is None and reason is not None: code = 1000 # "normal closure" status code if code is None: close_data = b"" else: close_data = struct.pack(">H", code) if reason is not None: close_data += utf8(reason) try: self._write_frame(True, 0x8, close_data) except StreamClosedError: self._abort() self.server_terminated = True if self.client_terminated: if self._waiting is not None: self.stream.io_loop.remove_timeout(self._waiting) self._waiting = None self.stream.close() elif self._waiting is None: # Give the client a few seconds to complete a clean shutdown, # otherwise just close the connection. self._waiting = self.stream.io_loop.add_timeout( self.stream.io_loop.time() + 5, self._abort )
python
def close(self, code: int = None, reason: str = None) -> None: """Closes the WebSocket connection.""" if not self.server_terminated: if not self.stream.closed(): if code is None and reason is not None: code = 1000 # "normal closure" status code if code is None: close_data = b"" else: close_data = struct.pack(">H", code) if reason is not None: close_data += utf8(reason) try: self._write_frame(True, 0x8, close_data) except StreamClosedError: self._abort() self.server_terminated = True if self.client_terminated: if self._waiting is not None: self.stream.io_loop.remove_timeout(self._waiting) self._waiting = None self.stream.close() elif self._waiting is None: # Give the client a few seconds to complete a clean shutdown, # otherwise just close the connection. self._waiting = self.stream.io_loop.add_timeout( self.stream.io_loop.time() + 5, self._abort )
[ "def", "close", "(", "self", ",", "code", ":", "int", "=", "None", ",", "reason", ":", "str", "=", "None", ")", "->", "None", ":", "if", "not", "self", ".", "server_terminated", ":", "if", "not", "self", ".", "stream", ".", "closed", "(", ")", ":", "if", "code", "is", "None", "and", "reason", "is", "not", "None", ":", "code", "=", "1000", "# \"normal closure\" status code", "if", "code", "is", "None", ":", "close_data", "=", "b\"\"", "else", ":", "close_data", "=", "struct", ".", "pack", "(", "\">H\"", ",", "code", ")", "if", "reason", "is", "not", "None", ":", "close_data", "+=", "utf8", "(", "reason", ")", "try", ":", "self", ".", "_write_frame", "(", "True", ",", "0x8", ",", "close_data", ")", "except", "StreamClosedError", ":", "self", ".", "_abort", "(", ")", "self", ".", "server_terminated", "=", "True", "if", "self", ".", "client_terminated", ":", "if", "self", ".", "_waiting", "is", "not", "None", ":", "self", ".", "stream", ".", "io_loop", ".", "remove_timeout", "(", "self", ".", "_waiting", ")", "self", ".", "_waiting", "=", "None", "self", ".", "stream", ".", "close", "(", ")", "elif", "self", ".", "_waiting", "is", "None", ":", "# Give the client a few seconds to complete a clean shutdown,", "# otherwise just close the connection.", "self", ".", "_waiting", "=", "self", ".", "stream", ".", "io_loop", ".", "add_timeout", "(", "self", ".", "stream", ".", "io_loop", ".", "time", "(", ")", "+", "5", ",", "self", ".", "_abort", ")" ]
Closes the WebSocket connection.
[ "Closes", "the", "WebSocket", "connection", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1262-L1289
26,845
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.is_closing
def is_closing(self) -> bool: """Return ``True`` if this connection is closing. The connection is considered closing if either side has initiated its closing handshake or if the stream has been shut down uncleanly. """ return self.stream.closed() or self.client_terminated or self.server_terminated
python
def is_closing(self) -> bool: """Return ``True`` if this connection is closing. The connection is considered closing if either side has initiated its closing handshake or if the stream has been shut down uncleanly. """ return self.stream.closed() or self.client_terminated or self.server_terminated
[ "def", "is_closing", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "stream", ".", "closed", "(", ")", "or", "self", ".", "client_terminated", "or", "self", ".", "server_terminated" ]
Return ``True`` if this connection is closing. The connection is considered closing if either side has initiated its closing handshake or if the stream has been shut down uncleanly.
[ "Return", "True", "if", "this", "connection", "is", "closing", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1291-L1298
26,846
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.start_pinging
def start_pinging(self) -> None: """Start sending periodic pings to keep the connection alive""" assert self.ping_interval is not None if self.ping_interval > 0: self.last_ping = self.last_pong = IOLoop.current().time() self.ping_callback = PeriodicCallback( self.periodic_ping, self.ping_interval * 1000 ) self.ping_callback.start()
python
def start_pinging(self) -> None: """Start sending periodic pings to keep the connection alive""" assert self.ping_interval is not None if self.ping_interval > 0: self.last_ping = self.last_pong = IOLoop.current().time() self.ping_callback = PeriodicCallback( self.periodic_ping, self.ping_interval * 1000 ) self.ping_callback.start()
[ "def", "start_pinging", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "ping_interval", "is", "not", "None", "if", "self", ".", "ping_interval", ">", "0", ":", "self", ".", "last_ping", "=", "self", ".", "last_pong", "=", "IOLoop", ".", "current", "(", ")", ".", "time", "(", ")", "self", ".", "ping_callback", "=", "PeriodicCallback", "(", "self", ".", "periodic_ping", ",", "self", ".", "ping_interval", "*", "1000", ")", "self", ".", "ping_callback", ".", "start", "(", ")" ]
Start sending periodic pings to keep the connection alive
[ "Start", "sending", "periodic", "pings", "to", "keep", "the", "connection", "alive" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1315-L1323
26,847
tornadoweb/tornado
tornado/websocket.py
WebSocketProtocol13.periodic_ping
def periodic_ping(self) -> None: """Send a ping to keep the websocket alive Called periodically if the websocket_ping_interval is set and non-zero. """ if self.is_closing() and self.ping_callback is not None: self.ping_callback.stop() return # Check for timeout on pong. Make sure that we really have # sent a recent ping in case the machine with both server and # client has been suspended since the last ping. now = IOLoop.current().time() since_last_pong = now - self.last_pong since_last_ping = now - self.last_ping assert self.ping_interval is not None assert self.ping_timeout is not None if ( since_last_ping < 2 * self.ping_interval and since_last_pong > self.ping_timeout ): self.close() return self.write_ping(b"") self.last_ping = now
python
def periodic_ping(self) -> None: """Send a ping to keep the websocket alive Called periodically if the websocket_ping_interval is set and non-zero. """ if self.is_closing() and self.ping_callback is not None: self.ping_callback.stop() return # Check for timeout on pong. Make sure that we really have # sent a recent ping in case the machine with both server and # client has been suspended since the last ping. now = IOLoop.current().time() since_last_pong = now - self.last_pong since_last_ping = now - self.last_ping assert self.ping_interval is not None assert self.ping_timeout is not None if ( since_last_ping < 2 * self.ping_interval and since_last_pong > self.ping_timeout ): self.close() return self.write_ping(b"") self.last_ping = now
[ "def", "periodic_ping", "(", "self", ")", "->", "None", ":", "if", "self", ".", "is_closing", "(", ")", "and", "self", ".", "ping_callback", "is", "not", "None", ":", "self", ".", "ping_callback", ".", "stop", "(", ")", "return", "# Check for timeout on pong. Make sure that we really have", "# sent a recent ping in case the machine with both server and", "# client has been suspended since the last ping.", "now", "=", "IOLoop", ".", "current", "(", ")", ".", "time", "(", ")", "since_last_pong", "=", "now", "-", "self", ".", "last_pong", "since_last_ping", "=", "now", "-", "self", ".", "last_ping", "assert", "self", ".", "ping_interval", "is", "not", "None", "assert", "self", ".", "ping_timeout", "is", "not", "None", "if", "(", "since_last_ping", "<", "2", "*", "self", ".", "ping_interval", "and", "since_last_pong", ">", "self", ".", "ping_timeout", ")", ":", "self", ".", "close", "(", ")", "return", "self", ".", "write_ping", "(", "b\"\"", ")", "self", ".", "last_ping", "=", "now" ]
Send a ping to keep the websocket alive Called periodically if the websocket_ping_interval is set and non-zero.
[ "Send", "a", "ping", "to", "keep", "the", "websocket", "alive" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1325-L1350
26,848
tornadoweb/tornado
tornado/websocket.py
WebSocketClientConnection.write_message
def write_message( self, message: Union[str, bytes], binary: bool = False ) -> "Future[None]": """Sends a message to the WebSocket server. If the stream is closed, raises `WebSocketClosedError`. Returns a `.Future` which can be used for flow control. .. versionchanged:: 5.0 Exception raised on a closed stream changed from `.StreamClosedError` to `WebSocketClosedError`. """ return self.protocol.write_message(message, binary=binary)
python
def write_message( self, message: Union[str, bytes], binary: bool = False ) -> "Future[None]": """Sends a message to the WebSocket server. If the stream is closed, raises `WebSocketClosedError`. Returns a `.Future` which can be used for flow control. .. versionchanged:: 5.0 Exception raised on a closed stream changed from `.StreamClosedError` to `WebSocketClosedError`. """ return self.protocol.write_message(message, binary=binary)
[ "def", "write_message", "(", "self", ",", "message", ":", "Union", "[", "str", ",", "bytes", "]", ",", "binary", ":", "bool", "=", "False", ")", "->", "\"Future[None]\"", ":", "return", "self", ".", "protocol", ".", "write_message", "(", "message", ",", "binary", "=", "binary", ")" ]
Sends a message to the WebSocket server. If the stream is closed, raises `WebSocketClosedError`. Returns a `.Future` which can be used for flow control. .. versionchanged:: 5.0 Exception raised on a closed stream changed from `.StreamClosedError` to `WebSocketClosedError`.
[ "Sends", "a", "message", "to", "the", "WebSocket", "server", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1494-L1506
26,849
tornadoweb/tornado
tornado/websocket.py
WebSocketClientConnection.read_message
def read_message( self, callback: Callable[["Future[Union[None, str, bytes]]"], None] = None ) -> Awaitable[Union[None, str, bytes]]: """Reads a message from the WebSocket server. If on_message_callback was specified at WebSocket initialization, this function will never return messages Returns a future whose result is the message, or None if the connection is closed. If a callback argument is given it will be called with the future when it is ready. """ awaitable = self.read_queue.get() if callback is not None: self.io_loop.add_future(asyncio.ensure_future(awaitable), callback) return awaitable
python
def read_message( self, callback: Callable[["Future[Union[None, str, bytes]]"], None] = None ) -> Awaitable[Union[None, str, bytes]]: """Reads a message from the WebSocket server. If on_message_callback was specified at WebSocket initialization, this function will never return messages Returns a future whose result is the message, or None if the connection is closed. If a callback argument is given it will be called with the future when it is ready. """ awaitable = self.read_queue.get() if callback is not None: self.io_loop.add_future(asyncio.ensure_future(awaitable), callback) return awaitable
[ "def", "read_message", "(", "self", ",", "callback", ":", "Callable", "[", "[", "\"Future[Union[None, str, bytes]]\"", "]", ",", "None", "]", "=", "None", ")", "->", "Awaitable", "[", "Union", "[", "None", ",", "str", ",", "bytes", "]", "]", ":", "awaitable", "=", "self", ".", "read_queue", ".", "get", "(", ")", "if", "callback", "is", "not", "None", ":", "self", ".", "io_loop", ".", "add_future", "(", "asyncio", ".", "ensure_future", "(", "awaitable", ")", ",", "callback", ")", "return", "awaitable" ]
Reads a message from the WebSocket server. If on_message_callback was specified at WebSocket initialization, this function will never return messages Returns a future whose result is the message, or None if the connection is closed. If a callback argument is given it will be called with the future when it is ready.
[ "Reads", "a", "message", "from", "the", "WebSocket", "server", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L1508-L1525
26,850
tornadoweb/tornado
tornado/options.py
define
def define( name: str, default: Any = None, type: type = None, help: str = None, metavar: str = None, multiple: bool = False, group: str = None, callback: Callable[[Any], None] = None, ) -> None: """Defines an option in the global namespace. See `OptionParser.define`. """ return options.define( name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group=group, callback=callback, )
python
def define( name: str, default: Any = None, type: type = None, help: str = None, metavar: str = None, multiple: bool = False, group: str = None, callback: Callable[[Any], None] = None, ) -> None: """Defines an option in the global namespace. See `OptionParser.define`. """ return options.define( name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group=group, callback=callback, )
[ "def", "define", "(", "name", ":", "str", ",", "default", ":", "Any", "=", "None", ",", "type", ":", "type", "=", "None", ",", "help", ":", "str", "=", "None", ",", "metavar", ":", "str", "=", "None", ",", "multiple", ":", "bool", "=", "False", ",", "group", ":", "str", "=", "None", ",", "callback", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", "=", "None", ",", ")", "->", "None", ":", "return", "options", ".", "define", "(", "name", ",", "default", "=", "default", ",", "type", "=", "type", ",", "help", "=", "help", ",", "metavar", "=", "metavar", ",", "multiple", "=", "multiple", ",", "group", "=", "group", ",", "callback", "=", "callback", ",", ")" ]
Defines an option in the global namespace. See `OptionParser.define`.
[ "Defines", "an", "option", "in", "the", "global", "namespace", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L667-L690
26,851
tornadoweb/tornado
tornado/options.py
parse_command_line
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]: """Parses global options from the command line. See `OptionParser.parse_command_line`. """ return options.parse_command_line(args, final=final)
python
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]: """Parses global options from the command line. See `OptionParser.parse_command_line`. """ return options.parse_command_line(args, final=final)
[ "def", "parse_command_line", "(", "args", ":", "List", "[", "str", "]", "=", "None", ",", "final", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "options", ".", "parse_command_line", "(", "args", ",", "final", "=", "final", ")" ]
Parses global options from the command line. See `OptionParser.parse_command_line`.
[ "Parses", "global", "options", "from", "the", "command", "line", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L693-L698
26,852
tornadoweb/tornado
tornado/options.py
parse_config_file
def parse_config_file(path: str, final: bool = True) -> None: """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final)
python
def parse_config_file(path: str, final: bool = True) -> None: """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final)
[ "def", "parse_config_file", "(", "path", ":", "str", ",", "final", ":", "bool", "=", "True", ")", "->", "None", ":", "return", "options", ".", "parse_config_file", "(", "path", ",", "final", "=", "final", ")" ]
Parses global options from a config file. See `OptionParser.parse_config_file`.
[ "Parses", "global", "options", "from", "a", "config", "file", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L701-L706
26,853
tornadoweb/tornado
tornado/options.py
OptionParser.groups
def groups(self) -> Set[str]: """The set of option-groups created by ``define``. .. versionadded:: 3.1 """ return set(opt.group_name for opt in self._options.values())
python
def groups(self) -> Set[str]: """The set of option-groups created by ``define``. .. versionadded:: 3.1 """ return set(opt.group_name for opt in self._options.values())
[ "def", "groups", "(", "self", ")", "->", "Set", "[", "str", "]", ":", "return", "set", "(", "opt", ".", "group_name", "for", "opt", "in", "self", ".", "_options", ".", "values", "(", ")", ")" ]
The set of option-groups created by ``define``. .. versionadded:: 3.1
[ "The", "set", "of", "option", "-", "groups", "created", "by", "define", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L173-L178
26,854
tornadoweb/tornado
tornado/options.py
OptionParser.group_dict
def group_dict(self, group: str) -> Dict[str, Any]: """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application')) .. versionadded:: 3.1 """ return dict( (opt.name, opt.value()) for name, opt in self._options.items() if not group or group == opt.group_name )
python
def group_dict(self, group: str) -> Dict[str, Any]: """The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application')) .. versionadded:: 3.1 """ return dict( (opt.name, opt.value()) for name, opt in self._options.items() if not group or group == opt.group_name )
[ "def", "group_dict", "(", "self", ",", "group", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "dict", "(", "(", "opt", ".", "name", ",", "opt", ".", "value", "(", ")", ")", "for", "name", ",", "opt", "in", "self", ".", "_options", ".", "items", "(", ")", "if", "not", "group", "or", "group", "==", "opt", ".", "group_name", ")" ]
The names and values of options in a group. Useful for copying options into Application settings:: from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application')) .. versionadded:: 3.1
[ "The", "names", "and", "values", "of", "options", "in", "a", "group", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L180-L201
26,855
tornadoweb/tornado
tornado/options.py
OptionParser.as_dict
def as_dict(self) -> Dict[str, Any]: """The names and values of all options. .. versionadded:: 3.1 """ return dict((opt.name, opt.value()) for name, opt in self._options.items())
python
def as_dict(self) -> Dict[str, Any]: """The names and values of all options. .. versionadded:: 3.1 """ return dict((opt.name, opt.value()) for name, opt in self._options.items())
[ "def", "as_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "dict", "(", "(", "opt", ".", "name", ",", "opt", ".", "value", "(", ")", ")", "for", "name", ",", "opt", "in", "self", ".", "_options", ".", "items", "(", ")", ")" ]
The names and values of all options. .. versionadded:: 3.1
[ "The", "names", "and", "values", "of", "all", "options", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L203-L208
26,856
tornadoweb/tornado
tornado/options.py
OptionParser.define
def define( self, name: str, default: Any = None, type: type = None, help: str = None, metavar: str = None, multiple: bool = False, group: str = None, callback: Callable[[Any], None] = None, ) -> None: """Defines a new command line option. ``type`` can be any of `str`, `int`, `float`, `bool`, `~datetime.datetime`, or `~datetime.timedelta`. If no ``type`` is given but a ``default`` is, ``type`` is the type of ``default``. Otherwise, ``type`` defaults to `str`. If ``multiple`` is True, the option value is a list of ``type`` instead of an instance of ``type``. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags. """ normalized = self._normalize_name(name) if normalized in self._options: raise Error( "Option %r already defined in %s" % (normalized, self._options[normalized].file_name) ) frame = sys._getframe(0) options_file = frame.f_code.co_filename # Can be called directly, or through top level define() fn, in which # case, step up above that frame to look for real caller. if ( frame.f_back.f_code.co_filename == options_file and frame.f_back.f_code.co_name == "define" ): frame = frame.f_back file_name = frame.f_back.f_code.co_filename if file_name == options_file: file_name = "" if type is None: if not multiple and default is not None: type = default.__class__ else: type = str if group: group_name = group # type: Optional[str] else: group_name = file_name option = _Option( name, file_name=file_name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group_name=group_name, callback=callback, ) self._options[normalized] = option
python
def define( self, name: str, default: Any = None, type: type = None, help: str = None, metavar: str = None, multiple: bool = False, group: str = None, callback: Callable[[Any], None] = None, ) -> None: """Defines a new command line option. ``type`` can be any of `str`, `int`, `float`, `bool`, `~datetime.datetime`, or `~datetime.timedelta`. If no ``type`` is given but a ``default`` is, ``type`` is the type of ``default``. Otherwise, ``type`` defaults to `str`. If ``multiple`` is True, the option value is a list of ``type`` instead of an instance of ``type``. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags. """ normalized = self._normalize_name(name) if normalized in self._options: raise Error( "Option %r already defined in %s" % (normalized, self._options[normalized].file_name) ) frame = sys._getframe(0) options_file = frame.f_code.co_filename # Can be called directly, or through top level define() fn, in which # case, step up above that frame to look for real caller. if ( frame.f_back.f_code.co_filename == options_file and frame.f_back.f_code.co_name == "define" ): frame = frame.f_back file_name = frame.f_back.f_code.co_filename if file_name == options_file: file_name = "" if type is None: if not multiple and default is not None: type = default.__class__ else: type = str if group: group_name = group # type: Optional[str] else: group_name = file_name option = _Option( name, file_name=file_name, default=default, type=type, help=help, metavar=metavar, multiple=multiple, group_name=group_name, callback=callback, ) self._options[normalized] = option
[ "def", "define", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Any", "=", "None", ",", "type", ":", "type", "=", "None", ",", "help", ":", "str", "=", "None", ",", "metavar", ":", "str", "=", "None", ",", "multiple", ":", "bool", "=", "False", ",", "group", ":", "str", "=", "None", ",", "callback", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", "=", "None", ",", ")", "->", "None", ":", "normalized", "=", "self", ".", "_normalize_name", "(", "name", ")", "if", "normalized", "in", "self", ".", "_options", ":", "raise", "Error", "(", "\"Option %r already defined in %s\"", "%", "(", "normalized", ",", "self", ".", "_options", "[", "normalized", "]", ".", "file_name", ")", ")", "frame", "=", "sys", ".", "_getframe", "(", "0", ")", "options_file", "=", "frame", ".", "f_code", ".", "co_filename", "# Can be called directly, or through top level define() fn, in which", "# case, step up above that frame to look for real caller.", "if", "(", "frame", ".", "f_back", ".", "f_code", ".", "co_filename", "==", "options_file", "and", "frame", ".", "f_back", ".", "f_code", ".", "co_name", "==", "\"define\"", ")", ":", "frame", "=", "frame", ".", "f_back", "file_name", "=", "frame", ".", "f_back", ".", "f_code", ".", "co_filename", "if", "file_name", "==", "options_file", ":", "file_name", "=", "\"\"", "if", "type", "is", "None", ":", "if", "not", "multiple", "and", "default", "is", "not", "None", ":", "type", "=", "default", ".", "__class__", "else", ":", "type", "=", "str", "if", "group", ":", "group_name", "=", "group", "# type: Optional[str]", "else", ":", "group_name", "=", "file_name", "option", "=", "_Option", "(", "name", ",", "file_name", "=", "file_name", ",", "default", "=", "default", ",", "type", "=", "type", ",", "help", "=", "help", ",", "metavar", "=", "metavar", ",", "multiple", "=", "multiple", ",", "group_name", "=", "group_name", ",", "callback", "=", "callback", ",", ")", "self", ".", "_options", "[", "normalized", "]", "=", "option" ]
Defines a new command line option. ``type`` can be any of `str`, `int`, `float`, `bool`, `~datetime.datetime`, or `~datetime.timedelta`. If no ``type`` is given but a ``default`` is, ``type`` is the type of ``default``. Otherwise, ``type`` defaults to `str`. If ``multiple`` is True, the option value is a list of ``type`` instead of an instance of ``type``. ``help`` and ``metavar`` are used to construct the automatically generated command line help string. The help message is formatted like:: --name=METAVAR help string ``group`` is used to group the defined options in logical groups. By default, command line options are grouped by the file in which they are defined. Command line option names must be unique globally. If a ``callback`` is given, it will be run with the new value whenever the option is changed. This can be used to combine command-line and file-based options:: define("config", type=str, help="path to config file", callback=lambda path: parse_config_file(path, final=False)) With this definition, options in the file specified by ``--config`` will override options set earlier on the command line, but can be overridden by later flags.
[ "Defines", "a", "new", "command", "line", "option", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L210-L295
26,857
tornadoweb/tornado
tornado/options.py
OptionParser.parse_config_file
def parse_config_file(self, path: str, final: bool = True) -> None: """Parses and loads the config file at the given path. The config file contains Python code that will be executed (so it is **not safe** to use untrusted config files). Anything in the global namespace that matches a defined option will be used to set that option's value. Options may either be the specified type for the option or strings (in which case they will be parsed the same way as in `.parse_command_line`) Example (using the options defined in the top-level docs of this module):: port = 80 mysql_host = 'mydb.example.com:3306' # Both lists and comma-separated strings are allowed for # multiple=True. memcache_hosts = ['cache1.example.com:11011', 'cache2.example.com:11011'] memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011' If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. .. note:: `tornado.options` is primarily a command-line library. Config file support is provided for applications that wish to use it, but applications that prefer config files may wish to look at other libraries instead. .. versionchanged:: 4.1 Config files are now always interpreted as utf-8 instead of the system default encoding. .. versionchanged:: 4.4 The special variable ``__file__`` is available inside config files, specifying the absolute path to the config file itself. .. versionchanged:: 5.1 Added the ability to set options via strings in config files. """ config = {"__file__": os.path.abspath(path)} with open(path, "rb") as f: exec_in(native_str(f.read()), config, config) for name in config: normalized = self._normalize_name(name) if normalized in self._options: option = self._options[normalized] if option.multiple: if not isinstance(config[name], (list, str)): raise Error( "Option %r is required to be a list of %s " "or a comma-separated string" % (option.name, option.type.__name__) ) if type(config[name]) == str and option.type != str: option.parse(config[name]) else: option.set(config[name]) if final: self.run_parse_callbacks()
python
def parse_config_file(self, path: str, final: bool = True) -> None: """Parses and loads the config file at the given path. The config file contains Python code that will be executed (so it is **not safe** to use untrusted config files). Anything in the global namespace that matches a defined option will be used to set that option's value. Options may either be the specified type for the option or strings (in which case they will be parsed the same way as in `.parse_command_line`) Example (using the options defined in the top-level docs of this module):: port = 80 mysql_host = 'mydb.example.com:3306' # Both lists and comma-separated strings are allowed for # multiple=True. memcache_hosts = ['cache1.example.com:11011', 'cache2.example.com:11011'] memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011' If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. .. note:: `tornado.options` is primarily a command-line library. Config file support is provided for applications that wish to use it, but applications that prefer config files may wish to look at other libraries instead. .. versionchanged:: 4.1 Config files are now always interpreted as utf-8 instead of the system default encoding. .. versionchanged:: 4.4 The special variable ``__file__`` is available inside config files, specifying the absolute path to the config file itself. .. versionchanged:: 5.1 Added the ability to set options via strings in config files. """ config = {"__file__": os.path.abspath(path)} with open(path, "rb") as f: exec_in(native_str(f.read()), config, config) for name in config: normalized = self._normalize_name(name) if normalized in self._options: option = self._options[normalized] if option.multiple: if not isinstance(config[name], (list, str)): raise Error( "Option %r is required to be a list of %s " "or a comma-separated string" % (option.name, option.type.__name__) ) if type(config[name]) == str and option.type != str: option.parse(config[name]) else: option.set(config[name]) if final: self.run_parse_callbacks()
[ "def", "parse_config_file", "(", "self", ",", "path", ":", "str", ",", "final", ":", "bool", "=", "True", ")", "->", "None", ":", "config", "=", "{", "\"__file__\"", ":", "os", ".", "path", ".", "abspath", "(", "path", ")", "}", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "exec_in", "(", "native_str", "(", "f", ".", "read", "(", ")", ")", ",", "config", ",", "config", ")", "for", "name", "in", "config", ":", "normalized", "=", "self", ".", "_normalize_name", "(", "name", ")", "if", "normalized", "in", "self", ".", "_options", ":", "option", "=", "self", ".", "_options", "[", "normalized", "]", "if", "option", ".", "multiple", ":", "if", "not", "isinstance", "(", "config", "[", "name", "]", ",", "(", "list", ",", "str", ")", ")", ":", "raise", "Error", "(", "\"Option %r is required to be a list of %s \"", "\"or a comma-separated string\"", "%", "(", "option", ".", "name", ",", "option", ".", "type", ".", "__name__", ")", ")", "if", "type", "(", "config", "[", "name", "]", ")", "==", "str", "and", "option", ".", "type", "!=", "str", ":", "option", ".", "parse", "(", "config", "[", "name", "]", ")", "else", ":", "option", ".", "set", "(", "config", "[", "name", "]", ")", "if", "final", ":", "self", ".", "run_parse_callbacks", "(", ")" ]
Parses and loads the config file at the given path. The config file contains Python code that will be executed (so it is **not safe** to use untrusted config files). Anything in the global namespace that matches a defined option will be used to set that option's value. Options may either be the specified type for the option or strings (in which case they will be parsed the same way as in `.parse_command_line`) Example (using the options defined in the top-level docs of this module):: port = 80 mysql_host = 'mydb.example.com:3306' # Both lists and comma-separated strings are allowed for # multiple=True. memcache_hosts = ['cache1.example.com:11011', 'cache2.example.com:11011'] memcache_hosts = 'cache1.example.com:11011,cache2.example.com:11011' If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. .. note:: `tornado.options` is primarily a command-line library. Config file support is provided for applications that wish to use it, but applications that prefer config files may wish to look at other libraries instead. .. versionchanged:: 4.1 Config files are now always interpreted as utf-8 instead of the system default encoding. .. versionchanged:: 4.4 The special variable ``__file__`` is available inside config files, specifying the absolute path to the config file itself. .. versionchanged:: 5.1 Added the ability to set options via strings in config files.
[ "Parses", "and", "loads", "the", "config", "file", "at", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/options.py#L351-L418
26,858
tornadoweb/tornado
demos/blog/blog.py
BaseHandler.row_to_obj
def row_to_obj(self, row, cur): """Convert a SQL row to an object supporting dict and attribute access.""" obj = tornado.util.ObjectDict() for val, desc in zip(row, cur.description): obj[desc.name] = val return obj
python
def row_to_obj(self, row, cur): """Convert a SQL row to an object supporting dict and attribute access.""" obj = tornado.util.ObjectDict() for val, desc in zip(row, cur.description): obj[desc.name] = val return obj
[ "def", "row_to_obj", "(", "self", ",", "row", ",", "cur", ")", ":", "obj", "=", "tornado", ".", "util", ".", "ObjectDict", "(", ")", "for", "val", ",", "desc", "in", "zip", "(", "row", ",", "cur", ".", "description", ")", ":", "obj", "[", "desc", ".", "name", "]", "=", "val", "return", "obj" ]
Convert a SQL row to an object supporting dict and attribute access.
[ "Convert", "a", "SQL", "row", "to", "an", "object", "supporting", "dict", "and", "attribute", "access", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/blog/blog.py#L84-L89
26,859
tornadoweb/tornado
demos/blog/blog.py
BaseHandler.query
async def query(self, stmt, *args): """Query for a list of results. Typical usage:: results = await self.query(...) Or:: for row in await self.query(...) """ with (await self.application.db.cursor()) as cur: await cur.execute(stmt, args) return [self.row_to_obj(row, cur) for row in await cur.fetchall()]
python
async def query(self, stmt, *args): """Query for a list of results. Typical usage:: results = await self.query(...) Or:: for row in await self.query(...) """ with (await self.application.db.cursor()) as cur: await cur.execute(stmt, args) return [self.row_to_obj(row, cur) for row in await cur.fetchall()]
[ "async", "def", "query", "(", "self", ",", "stmt", ",", "*", "args", ")", ":", "with", "(", "await", "self", ".", "application", ".", "db", ".", "cursor", "(", ")", ")", "as", "cur", ":", "await", "cur", ".", "execute", "(", "stmt", ",", "args", ")", "return", "[", "self", ".", "row_to_obj", "(", "row", ",", "cur", ")", "for", "row", "in", "await", "cur", ".", "fetchall", "(", ")", "]" ]
Query for a list of results. Typical usage:: results = await self.query(...) Or:: for row in await self.query(...)
[ "Query", "for", "a", "list", "of", "results", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/blog/blog.py#L99-L112
26,860
tornadoweb/tornado
demos/blog/blog.py
BaseHandler.queryone
async def queryone(self, stmt, *args): """Query for exactly one result. Raises NoResultError if there are no results, or ValueError if there are more than one. """ results = await self.query(stmt, *args) if len(results) == 0: raise NoResultError() elif len(results) > 1: raise ValueError("Expected 1 result, got %d" % len(results)) return results[0]
python
async def queryone(self, stmt, *args): """Query for exactly one result. Raises NoResultError if there are no results, or ValueError if there are more than one. """ results = await self.query(stmt, *args) if len(results) == 0: raise NoResultError() elif len(results) > 1: raise ValueError("Expected 1 result, got %d" % len(results)) return results[0]
[ "async", "def", "queryone", "(", "self", ",", "stmt", ",", "*", "args", ")", ":", "results", "=", "await", "self", ".", "query", "(", "stmt", ",", "*", "args", ")", "if", "len", "(", "results", ")", "==", "0", ":", "raise", "NoResultError", "(", ")", "elif", "len", "(", "results", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Expected 1 result, got %d\"", "%", "len", "(", "results", ")", ")", "return", "results", "[", "0", "]" ]
Query for exactly one result. Raises NoResultError if there are no results, or ValueError if there are more than one.
[ "Query", "for", "exactly", "one", "result", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/blog/blog.py#L114-L125
26,861
tornadoweb/tornado
tornado/tcpserver.py
TCPServer.listen
def listen(self, port: int, address: str = "") -> None: """Starts accepting connections on the given port. This method may be called more than once to listen on multiple ports. `listen` takes effect immediately; it is not necessary to call `TCPServer.start` afterwards. It is, however, necessary to start the `.IOLoop`. """ sockets = bind_sockets(port, address=address) self.add_sockets(sockets)
python
def listen(self, port: int, address: str = "") -> None: """Starts accepting connections on the given port. This method may be called more than once to listen on multiple ports. `listen` takes effect immediately; it is not necessary to call `TCPServer.start` afterwards. It is, however, necessary to start the `.IOLoop`. """ sockets = bind_sockets(port, address=address) self.add_sockets(sockets)
[ "def", "listen", "(", "self", ",", "port", ":", "int", ",", "address", ":", "str", "=", "\"\"", ")", "->", "None", ":", "sockets", "=", "bind_sockets", "(", "port", ",", "address", "=", "address", ")", "self", ".", "add_sockets", "(", "sockets", ")" ]
Starts accepting connections on the given port. This method may be called more than once to listen on multiple ports. `listen` takes effect immediately; it is not necessary to call `TCPServer.start` afterwards. It is, however, necessary to start the `.IOLoop`.
[ "Starts", "accepting", "connections", "on", "the", "given", "port", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpserver.py#L143-L152
26,862
tornadoweb/tornado
tornado/tcpserver.py
TCPServer.add_sockets
def add_sockets(self, sockets: Iterable[socket.socket]) -> None: """Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server. """ for sock in sockets: self._sockets[sock.fileno()] = sock self._handlers[sock.fileno()] = add_accept_handler( sock, self._handle_connection )
python
def add_sockets(self, sockets: Iterable[socket.socket]) -> None: """Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server. """ for sock in sockets: self._sockets[sock.fileno()] = sock self._handlers[sock.fileno()] = add_accept_handler( sock, self._handle_connection )
[ "def", "add_sockets", "(", "self", ",", "sockets", ":", "Iterable", "[", "socket", ".", "socket", "]", ")", "->", "None", ":", "for", "sock", "in", "sockets", ":", "self", ".", "_sockets", "[", "sock", ".", "fileno", "(", ")", "]", "=", "sock", "self", ".", "_handlers", "[", "sock", ".", "fileno", "(", ")", "]", "=", "add_accept_handler", "(", "sock", ",", "self", ".", "_handle_connection", ")" ]
Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server.
[ "Makes", "this", "server", "start", "accepting", "connections", "on", "the", "given", "sockets", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpserver.py#L154-L167
26,863
tornadoweb/tornado
tornado/tcpserver.py
TCPServer.bind
def bind( self, port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = 128, reuse_port: bool = False, ) -> None: """Binds this server to the given port on the given address. To start the server, call `start`. If you want to run this server in a single process, you can call `listen` as a shortcut to the sequence of `bind` and `start` calls. Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument has the same meaning as for `.bind_sockets`. This method may be called multiple times prior to `start` to listen on multiple ports or interfaces. .. versionchanged:: 4.4 Added the ``reuse_port`` argument. """ sockets = bind_sockets( port, address=address, family=family, backlog=backlog, reuse_port=reuse_port ) if self._started: self.add_sockets(sockets) else: self._pending_sockets.extend(sockets)
python
def bind( self, port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = 128, reuse_port: bool = False, ) -> None: """Binds this server to the given port on the given address. To start the server, call `start`. If you want to run this server in a single process, you can call `listen` as a shortcut to the sequence of `bind` and `start` calls. Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument has the same meaning as for `.bind_sockets`. This method may be called multiple times prior to `start` to listen on multiple ports or interfaces. .. versionchanged:: 4.4 Added the ``reuse_port`` argument. """ sockets = bind_sockets( port, address=address, family=family, backlog=backlog, reuse_port=reuse_port ) if self._started: self.add_sockets(sockets) else: self._pending_sockets.extend(sockets)
[ "def", "bind", "(", "self", ",", "port", ":", "int", ",", "address", ":", "str", "=", "None", ",", "family", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "backlog", ":", "int", "=", "128", ",", "reuse_port", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "sockets", "=", "bind_sockets", "(", "port", ",", "address", "=", "address", ",", "family", "=", "family", ",", "backlog", "=", "backlog", ",", "reuse_port", "=", "reuse_port", ")", "if", "self", ".", "_started", ":", "self", ".", "add_sockets", "(", "sockets", ")", "else", ":", "self", ".", "_pending_sockets", ".", "extend", "(", "sockets", ")" ]
Binds this server to the given port on the given address. To start the server, call `start`. If you want to run this server in a single process, you can call `listen` as a shortcut to the sequence of `bind` and `start` calls. Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument has the same meaning as for `.bind_sockets`. This method may be called multiple times prior to `start` to listen on multiple ports or interfaces. .. versionchanged:: 4.4 Added the ``reuse_port`` argument.
[ "Binds", "this", "server", "to", "the", "given", "port", "on", "the", "given", "address", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpserver.py#L173-L210
26,864
tornadoweb/tornado
tornado/tcpserver.py
TCPServer.start
def start(self, num_processes: Optional[int] = 1, max_restarts: int = None) -> None: """Starts this server in the `.IOLoop`. By default, we run the server in this process and do not fork any additional child process. If num_processes is ``None`` or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If num_processes is given and > 1, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``TCPServer.start(n)``. Values of ``num_processes`` other than 1 are not supported on Windows. The ``max_restarts`` argument is passed to `.fork_processes`. .. versionchanged:: 6.0 Added ``max_restarts`` argument. """ assert not self._started self._started = True if num_processes != 1: process.fork_processes(num_processes, max_restarts) sockets = self._pending_sockets self._pending_sockets = [] self.add_sockets(sockets)
python
def start(self, num_processes: Optional[int] = 1, max_restarts: int = None) -> None: """Starts this server in the `.IOLoop`. By default, we run the server in this process and do not fork any additional child process. If num_processes is ``None`` or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If num_processes is given and > 1, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``TCPServer.start(n)``. Values of ``num_processes`` other than 1 are not supported on Windows. The ``max_restarts`` argument is passed to `.fork_processes`. .. versionchanged:: 6.0 Added ``max_restarts`` argument. """ assert not self._started self._started = True if num_processes != 1: process.fork_processes(num_processes, max_restarts) sockets = self._pending_sockets self._pending_sockets = [] self.add_sockets(sockets)
[ "def", "start", "(", "self", ",", "num_processes", ":", "Optional", "[", "int", "]", "=", "1", ",", "max_restarts", ":", "int", "=", "None", ")", "->", "None", ":", "assert", "not", "self", ".", "_started", "self", ".", "_started", "=", "True", "if", "num_processes", "!=", "1", ":", "process", ".", "fork_processes", "(", "num_processes", ",", "max_restarts", ")", "sockets", "=", "self", ".", "_pending_sockets", "self", ".", "_pending_sockets", "=", "[", "]", "self", ".", "add_sockets", "(", "sockets", ")" ]
Starts this server in the `.IOLoop`. By default, we run the server in this process and do not fork any additional child process. If num_processes is ``None`` or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If num_processes is given and > 1, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``TCPServer.start(n)``. Values of ``num_processes`` other than 1 are not supported on Windows. The ``max_restarts`` argument is passed to `.fork_processes`. .. versionchanged:: 6.0 Added ``max_restarts`` argument.
[ "Starts", "this", "server", "in", "the", ".", "IOLoop", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpserver.py#L212-L246
26,865
tornadoweb/tornado
tornado/tcpserver.py
TCPServer.stop
def stop(self) -> None: """Stops listening for new connections. Requests currently in progress may still continue after the server is stopped. """ if self._stopped: return self._stopped = True for fd, sock in self._sockets.items(): assert sock.fileno() == fd # Unregister socket from IOLoop self._handlers.pop(fd)() sock.close()
python
def stop(self) -> None: """Stops listening for new connections. Requests currently in progress may still continue after the server is stopped. """ if self._stopped: return self._stopped = True for fd, sock in self._sockets.items(): assert sock.fileno() == fd # Unregister socket from IOLoop self._handlers.pop(fd)() sock.close()
[ "def", "stop", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_stopped", ":", "return", "self", ".", "_stopped", "=", "True", "for", "fd", ",", "sock", "in", "self", ".", "_sockets", ".", "items", "(", ")", ":", "assert", "sock", ".", "fileno", "(", ")", "==", "fd", "# Unregister socket from IOLoop", "self", ".", "_handlers", ".", "pop", "(", "fd", ")", "(", ")", "sock", ".", "close", "(", ")" ]
Stops listening for new connections. Requests currently in progress may still continue after the server is stopped.
[ "Stops", "listening", "for", "new", "connections", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpserver.py#L248-L261
26,866
tornadoweb/tornado
tornado/queues.py
Queue.put
def put( self, item: _T, timeout: Union[float, datetime.timedelta] = None ) -> "Future[None]": """Put an item into the queue, perhaps waiting until there is room. Returns a Future, which raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denoting a time (on the same scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. """ future = Future() # type: Future[None] try: self.put_nowait(item) except QueueFull: self._putters.append((item, future)) _set_timeout(future, timeout) else: future.set_result(None) return future
python
def put( self, item: _T, timeout: Union[float, datetime.timedelta] = None ) -> "Future[None]": """Put an item into the queue, perhaps waiting until there is room. Returns a Future, which raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denoting a time (on the same scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. """ future = Future() # type: Future[None] try: self.put_nowait(item) except QueueFull: self._putters.append((item, future)) _set_timeout(future, timeout) else: future.set_result(None) return future
[ "def", "put", "(", "self", ",", "item", ":", "_T", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "\"Future[None]\"", ":", "future", "=", "Future", "(", ")", "# type: Future[None]", "try", ":", "self", ".", "put_nowait", "(", "item", ")", "except", "QueueFull", ":", "self", ".", "_putters", ".", "append", "(", "(", "item", ",", "future", ")", ")", "_set_timeout", "(", "future", ",", "timeout", ")", "else", ":", "future", ".", "set_result", "(", "None", ")", "return", "future" ]
Put an item into the queue, perhaps waiting until there is room. Returns a Future, which raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denoting a time (on the same scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time.
[ "Put", "an", "item", "into", "the", "queue", "perhaps", "waiting", "until", "there", "is", "room", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/queues.py#L186-L207
26,867
tornadoweb/tornado
tornado/queues.py
Queue.get_nowait
def get_nowait(self) -> _T: """Remove and return an item from the queue without blocking. Return an item if one is immediately available, else raise `QueueEmpty`. """ self._consume_expired() if self._putters: assert self.full(), "queue not full, why are putters waiting?" item, putter = self._putters.popleft() self.__put_internal(item) future_set_result_unless_cancelled(putter, None) return self._get() elif self.qsize(): return self._get() else: raise QueueEmpty
python
def get_nowait(self) -> _T: """Remove and return an item from the queue without blocking. Return an item if one is immediately available, else raise `QueueEmpty`. """ self._consume_expired() if self._putters: assert self.full(), "queue not full, why are putters waiting?" item, putter = self._putters.popleft() self.__put_internal(item) future_set_result_unless_cancelled(putter, None) return self._get() elif self.qsize(): return self._get() else: raise QueueEmpty
[ "def", "get_nowait", "(", "self", ")", "->", "_T", ":", "self", ".", "_consume_expired", "(", ")", "if", "self", ".", "_putters", ":", "assert", "self", ".", "full", "(", ")", ",", "\"queue not full, why are putters waiting?\"", "item", ",", "putter", "=", "self", ".", "_putters", ".", "popleft", "(", ")", "self", ".", "__put_internal", "(", "item", ")", "future_set_result_unless_cancelled", "(", "putter", ",", "None", ")", "return", "self", ".", "_get", "(", ")", "elif", "self", ".", "qsize", "(", ")", ":", "return", "self", ".", "_get", "(", ")", "else", ":", "raise", "QueueEmpty" ]
Remove and return an item from the queue without blocking. Return an item if one is immediately available, else raise `QueueEmpty`.
[ "Remove", "and", "return", "an", "item", "from", "the", "queue", "without", "blocking", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/queues.py#L254-L270
26,868
tornadoweb/tornado
tornado/queues.py
Queue.join
def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until all items in the queue are processed. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._finished.wait(timeout)
python
def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until all items in the queue are processed. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._finished.wait(timeout)
[ "def", "join", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "None", "]", ":", "return", "self", ".", "_finished", ".", "wait", "(", "timeout", ")" ]
Block until all items in the queue are processed. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout.
[ "Block", "until", "all", "items", "in", "the", "queue", "are", "processed", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/queues.py#L290-L296
26,869
tornadoweb/tornado
tornado/process.py
cpu_count
def cpu_count() -> int: """Returns the number of processors on this machine.""" if multiprocessing is None: return 1 try: return multiprocessing.cpu_count() except NotImplementedError: pass try: return os.sysconf("SC_NPROCESSORS_CONF") except (AttributeError, ValueError): pass gen_log.error("Could not detect number of processors; assuming 1") return 1
python
def cpu_count() -> int: """Returns the number of processors on this machine.""" if multiprocessing is None: return 1 try: return multiprocessing.cpu_count() except NotImplementedError: pass try: return os.sysconf("SC_NPROCESSORS_CONF") except (AttributeError, ValueError): pass gen_log.error("Could not detect number of processors; assuming 1") return 1
[ "def", "cpu_count", "(", ")", "->", "int", ":", "if", "multiprocessing", "is", "None", ":", "return", "1", "try", ":", "return", "multiprocessing", ".", "cpu_count", "(", ")", "except", "NotImplementedError", ":", "pass", "try", ":", "return", "os", ".", "sysconf", "(", "\"SC_NPROCESSORS_CONF\"", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "pass", "gen_log", ".", "error", "(", "\"Could not detect number of processors; assuming 1\"", ")", "return", "1" ]
Returns the number of processors on this machine.
[ "Returns", "the", "number", "of", "processors", "on", "this", "machine", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L51-L64
26,870
tornadoweb/tornado
tornado/process.py
fork_processes
def fork_processes(num_processes: Optional[int], max_restarts: int = None) -> int: """Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``fork_processes``. In each child process, ``fork_processes`` returns its *task id*, a number between 0 and ``num_processes``. Processes that exit abnormally (due to a signal or non-zero exit status) are restarted with the same id (up to ``max_restarts`` times). In the parent process, ``fork_processes`` returns None if all child processes have exited normally, but will otherwise only exit by throwing an exception. max_restarts defaults to 100. Availability: Unix """ if max_restarts is None: max_restarts = 100 global _task_id assert _task_id is None if num_processes is None or num_processes <= 0: num_processes = cpu_count() gen_log.info("Starting %d processes", num_processes) children = {} def start_child(i: int) -> Optional[int]: pid = os.fork() if pid == 0: # child process _reseed_random() global _task_id _task_id = i return i else: children[pid] = i return None for i in range(num_processes): id = start_child(i) if id is not None: return id num_restarts = 0 while children: try: pid, status = os.wait() except OSError as e: if errno_from_exception(e) == errno.EINTR: continue raise if pid not in children: continue id = children.pop(pid) if os.WIFSIGNALED(status): gen_log.warning( "child %d (pid %d) killed by signal %d, restarting", id, pid, os.WTERMSIG(status), ) elif os.WEXITSTATUS(status) != 0: gen_log.warning( "child %d (pid %d) exited with status %d, restarting", id, pid, os.WEXITSTATUS(status), ) else: gen_log.info("child %d (pid %d) exited normally", id, pid) continue num_restarts += 1 if num_restarts > max_restarts: raise RuntimeError("Too many child restarts, giving up") new_id = start_child(id) if new_id is not None: return new_id # All child processes exited cleanly, so exit the master process # instead of just returning to right after the call to # fork_processes (which will probably just start up another IOLoop # unless the caller checks the return value). sys.exit(0)
python
def fork_processes(num_processes: Optional[int], max_restarts: int = None) -> int: """Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``fork_processes``. In each child process, ``fork_processes`` returns its *task id*, a number between 0 and ``num_processes``. Processes that exit abnormally (due to a signal or non-zero exit status) are restarted with the same id (up to ``max_restarts`` times). In the parent process, ``fork_processes`` returns None if all child processes have exited normally, but will otherwise only exit by throwing an exception. max_restarts defaults to 100. Availability: Unix """ if max_restarts is None: max_restarts = 100 global _task_id assert _task_id is None if num_processes is None or num_processes <= 0: num_processes = cpu_count() gen_log.info("Starting %d processes", num_processes) children = {} def start_child(i: int) -> Optional[int]: pid = os.fork() if pid == 0: # child process _reseed_random() global _task_id _task_id = i return i else: children[pid] = i return None for i in range(num_processes): id = start_child(i) if id is not None: return id num_restarts = 0 while children: try: pid, status = os.wait() except OSError as e: if errno_from_exception(e) == errno.EINTR: continue raise if pid not in children: continue id = children.pop(pid) if os.WIFSIGNALED(status): gen_log.warning( "child %d (pid %d) killed by signal %d, restarting", id, pid, os.WTERMSIG(status), ) elif os.WEXITSTATUS(status) != 0: gen_log.warning( "child %d (pid %d) exited with status %d, restarting", id, pid, os.WEXITSTATUS(status), ) else: gen_log.info("child %d (pid %d) exited normally", id, pid) continue num_restarts += 1 if num_restarts > max_restarts: raise RuntimeError("Too many child restarts, giving up") new_id = start_child(id) if new_id is not None: return new_id # All child processes exited cleanly, so exit the master process # instead of just returning to right after the call to # fork_processes (which will probably just start up another IOLoop # unless the caller checks the return value). sys.exit(0)
[ "def", "fork_processes", "(", "num_processes", ":", "Optional", "[", "int", "]", ",", "max_restarts", ":", "int", "=", "None", ")", "->", "int", ":", "if", "max_restarts", "is", "None", ":", "max_restarts", "=", "100", "global", "_task_id", "assert", "_task_id", "is", "None", "if", "num_processes", "is", "None", "or", "num_processes", "<=", "0", ":", "num_processes", "=", "cpu_count", "(", ")", "gen_log", ".", "info", "(", "\"Starting %d processes\"", ",", "num_processes", ")", "children", "=", "{", "}", "def", "start_child", "(", "i", ":", "int", ")", "->", "Optional", "[", "int", "]", ":", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", "==", "0", ":", "# child process", "_reseed_random", "(", ")", "global", "_task_id", "_task_id", "=", "i", "return", "i", "else", ":", "children", "[", "pid", "]", "=", "i", "return", "None", "for", "i", "in", "range", "(", "num_processes", ")", ":", "id", "=", "start_child", "(", "i", ")", "if", "id", "is", "not", "None", ":", "return", "id", "num_restarts", "=", "0", "while", "children", ":", "try", ":", "pid", ",", "status", "=", "os", ".", "wait", "(", ")", "except", "OSError", "as", "e", ":", "if", "errno_from_exception", "(", "e", ")", "==", "errno", ".", "EINTR", ":", "continue", "raise", "if", "pid", "not", "in", "children", ":", "continue", "id", "=", "children", ".", "pop", "(", "pid", ")", "if", "os", ".", "WIFSIGNALED", "(", "status", ")", ":", "gen_log", ".", "warning", "(", "\"child %d (pid %d) killed by signal %d, restarting\"", ",", "id", ",", "pid", ",", "os", ".", "WTERMSIG", "(", "status", ")", ",", ")", "elif", "os", ".", "WEXITSTATUS", "(", "status", ")", "!=", "0", ":", "gen_log", ".", "warning", "(", "\"child %d (pid %d) exited with status %d, restarting\"", ",", "id", ",", "pid", ",", "os", ".", "WEXITSTATUS", "(", "status", ")", ",", ")", "else", ":", "gen_log", ".", "info", "(", "\"child %d (pid %d) exited normally\"", ",", "id", ",", "pid", ")", "continue", "num_restarts", "+=", "1", "if", "num_restarts", ">", "max_restarts", ":", "raise", "RuntimeError", "(", "\"Too many child restarts, giving up\"", ")", "new_id", "=", "start_child", "(", "id", ")", "if", "new_id", "is", "not", "None", ":", "return", "new_id", "# All child processes exited cleanly, so exit the master process", "# instead of just returning to right after the call to", "# fork_processes (which will probably just start up another IOLoop", "# unless the caller checks the return value).", "sys", ".", "exit", "(", "0", ")" ]
Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the ``autoreload=True`` option to `tornado.web.Application` which defaults to True when ``debug=True``). When using multiple processes, no IOLoops can be created or referenced until after the call to ``fork_processes``. In each child process, ``fork_processes`` returns its *task id*, a number between 0 and ``num_processes``. Processes that exit abnormally (due to a signal or non-zero exit status) are restarted with the same id (up to ``max_restarts`` times). In the parent process, ``fork_processes`` returns None if all child processes have exited normally, but will otherwise only exit by throwing an exception. max_restarts defaults to 100. Availability: Unix
[ "Starts", "multiple", "worker", "processes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L92-L185
26,871
tornadoweb/tornado
tornado/process.py
Subprocess.set_exit_callback
def set_exit_callback(self, callback: Callable[[int], None]) -> None: """Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than one ``IOLoop`` it may be necessary to call `Subprocess.initialize` first to designate one ``IOLoop`` to run the signal handlers. In many cases a close callback on the stdout or stderr streams can be used as an alternative to an exit callback if the signal handler is causing a problem. Availability: Unix """ self._exit_callback = callback Subprocess.initialize() Subprocess._waiting[self.pid] = self Subprocess._try_cleanup_process(self.pid)
python
def set_exit_callback(self, callback: Callable[[int], None]) -> None: """Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than one ``IOLoop`` it may be necessary to call `Subprocess.initialize` first to designate one ``IOLoop`` to run the signal handlers. In many cases a close callback on the stdout or stderr streams can be used as an alternative to an exit callback if the signal handler is causing a problem. Availability: Unix """ self._exit_callback = callback Subprocess.initialize() Subprocess._waiting[self.pid] = self Subprocess._try_cleanup_process(self.pid)
[ "def", "set_exit_callback", "(", "self", ",", "callback", ":", "Callable", "[", "[", "int", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_exit_callback", "=", "callback", "Subprocess", ".", "initialize", "(", ")", "Subprocess", ".", "_waiting", "[", "self", ".", "pid", "]", "=", "self", "Subprocess", ".", "_try_cleanup_process", "(", "self", ".", "pid", ")" ]
Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than one ``IOLoop`` it may be necessary to call `Subprocess.initialize` first to designate one ``IOLoop`` to run the signal handlers. In many cases a close callback on the stdout or stderr streams can be used as an alternative to an exit callback if the signal handler is causing a problem. Availability: Unix
[ "Runs", "callback", "when", "this", "process", "exits", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L264-L284
26,872
tornadoweb/tornado
tornado/process.py
Subprocess.wait_for_exit
def wait_for_exit(self, raise_error: bool = True) -> "Future[int]": """Returns a `.Future` which resolves when the process exits. Usage:: ret = yield proc.wait_for_exit() This is a coroutine-friendly alternative to `set_exit_callback` (and a replacement for the blocking `subprocess.Popen.wait`). By default, raises `subprocess.CalledProcessError` if the process has a non-zero exit status. Use ``wait_for_exit(raise_error=False)`` to suppress this behavior and return the exit status without raising. .. versionadded:: 4.2 Availability: Unix """ future = Future() # type: Future[int] def callback(ret: int) -> None: if ret != 0 and raise_error: # Unfortunately we don't have the original args any more. future_set_exception_unless_cancelled( future, CalledProcessError(ret, "unknown") ) else: future_set_result_unless_cancelled(future, ret) self.set_exit_callback(callback) return future
python
def wait_for_exit(self, raise_error: bool = True) -> "Future[int]": """Returns a `.Future` which resolves when the process exits. Usage:: ret = yield proc.wait_for_exit() This is a coroutine-friendly alternative to `set_exit_callback` (and a replacement for the blocking `subprocess.Popen.wait`). By default, raises `subprocess.CalledProcessError` if the process has a non-zero exit status. Use ``wait_for_exit(raise_error=False)`` to suppress this behavior and return the exit status without raising. .. versionadded:: 4.2 Availability: Unix """ future = Future() # type: Future[int] def callback(ret: int) -> None: if ret != 0 and raise_error: # Unfortunately we don't have the original args any more. future_set_exception_unless_cancelled( future, CalledProcessError(ret, "unknown") ) else: future_set_result_unless_cancelled(future, ret) self.set_exit_callback(callback) return future
[ "def", "wait_for_exit", "(", "self", ",", "raise_error", ":", "bool", "=", "True", ")", "->", "\"Future[int]\"", ":", "future", "=", "Future", "(", ")", "# type: Future[int]", "def", "callback", "(", "ret", ":", "int", ")", "->", "None", ":", "if", "ret", "!=", "0", "and", "raise_error", ":", "# Unfortunately we don't have the original args any more.", "future_set_exception_unless_cancelled", "(", "future", ",", "CalledProcessError", "(", "ret", ",", "\"unknown\"", ")", ")", "else", ":", "future_set_result_unless_cancelled", "(", "future", ",", "ret", ")", "self", ".", "set_exit_callback", "(", "callback", ")", "return", "future" ]
Returns a `.Future` which resolves when the process exits. Usage:: ret = yield proc.wait_for_exit() This is a coroutine-friendly alternative to `set_exit_callback` (and a replacement for the blocking `subprocess.Popen.wait`). By default, raises `subprocess.CalledProcessError` if the process has a non-zero exit status. Use ``wait_for_exit(raise_error=False)`` to suppress this behavior and return the exit status without raising. .. versionadded:: 4.2 Availability: Unix
[ "Returns", "a", ".", "Future", "which", "resolves", "when", "the", "process", "exits", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L286-L316
26,873
tornadoweb/tornado
tornado/process.py
Subprocess.initialize
def initialize(cls) -> None: """Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are each running in separate threads). .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. Availability: Unix """ if cls._initialized: return io_loop = ioloop.IOLoop.current() cls._old_sigchld = signal.signal( signal.SIGCHLD, lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup), ) cls._initialized = True
python
def initialize(cls) -> None: """Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are each running in separate threads). .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. Availability: Unix """ if cls._initialized: return io_loop = ioloop.IOLoop.current() cls._old_sigchld = signal.signal( signal.SIGCHLD, lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup), ) cls._initialized = True
[ "def", "initialize", "(", "cls", ")", "->", "None", ":", "if", "cls", ".", "_initialized", ":", "return", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "cls", ".", "_old_sigchld", "=", "signal", ".", "signal", "(", "signal", ".", "SIGCHLD", ",", "lambda", "sig", ",", "frame", ":", "io_loop", ".", "add_callback_from_signal", "(", "cls", ".", "_cleanup", ")", ",", ")", "cls", ".", "_initialized", "=", "True" ]
Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are each running in separate threads). .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. Availability: Unix
[ "Initializes", "the", "SIGCHLD", "handler", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L319-L340
26,874
tornadoweb/tornado
tornado/process.py
Subprocess.uninitialize
def uninitialize(cls) -> None: """Removes the ``SIGCHLD`` handler.""" if not cls._initialized: return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
python
def uninitialize(cls) -> None: """Removes the ``SIGCHLD`` handler.""" if not cls._initialized: return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
[ "def", "uninitialize", "(", "cls", ")", "->", "None", ":", "if", "not", "cls", ".", "_initialized", ":", "return", "signal", ".", "signal", "(", "signal", ".", "SIGCHLD", ",", "cls", ".", "_old_sigchld", ")", "cls", ".", "_initialized", "=", "False" ]
Removes the ``SIGCHLD`` handler.
[ "Removes", "the", "SIGCHLD", "handler", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L343-L348
26,875
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._handle_socket
def _handle_socket(self, event: int, fd: int, multi: Any, data: bytes) -> None: """Called by libcurl when it wants to change the file descriptors it cares about. """ event_map = { pycurl.POLL_NONE: ioloop.IOLoop.NONE, pycurl.POLL_IN: ioloop.IOLoop.READ, pycurl.POLL_OUT: ioloop.IOLoop.WRITE, pycurl.POLL_INOUT: ioloop.IOLoop.READ | ioloop.IOLoop.WRITE, } if event == pycurl.POLL_REMOVE: if fd in self._fds: self.io_loop.remove_handler(fd) del self._fds[fd] else: ioloop_event = event_map[event] # libcurl sometimes closes a socket and then opens a new # one using the same FD without giving us a POLL_NONE in # between. This is a problem with the epoll IOLoop, # because the kernel can tell when a socket is closed and # removes it from the epoll automatically, causing future # update_handler calls to fail. Since we can't tell when # this has happened, always use remove and re-add # instead of update. if fd in self._fds: self.io_loop.remove_handler(fd) self.io_loop.add_handler(fd, self._handle_events, ioloop_event) self._fds[fd] = ioloop_event
python
def _handle_socket(self, event: int, fd: int, multi: Any, data: bytes) -> None: """Called by libcurl when it wants to change the file descriptors it cares about. """ event_map = { pycurl.POLL_NONE: ioloop.IOLoop.NONE, pycurl.POLL_IN: ioloop.IOLoop.READ, pycurl.POLL_OUT: ioloop.IOLoop.WRITE, pycurl.POLL_INOUT: ioloop.IOLoop.READ | ioloop.IOLoop.WRITE, } if event == pycurl.POLL_REMOVE: if fd in self._fds: self.io_loop.remove_handler(fd) del self._fds[fd] else: ioloop_event = event_map[event] # libcurl sometimes closes a socket and then opens a new # one using the same FD without giving us a POLL_NONE in # between. This is a problem with the epoll IOLoop, # because the kernel can tell when a socket is closed and # removes it from the epoll automatically, causing future # update_handler calls to fail. Since we can't tell when # this has happened, always use remove and re-add # instead of update. if fd in self._fds: self.io_loop.remove_handler(fd) self.io_loop.add_handler(fd, self._handle_events, ioloop_event) self._fds[fd] = ioloop_event
[ "def", "_handle_socket", "(", "self", ",", "event", ":", "int", ",", "fd", ":", "int", ",", "multi", ":", "Any", ",", "data", ":", "bytes", ")", "->", "None", ":", "event_map", "=", "{", "pycurl", ".", "POLL_NONE", ":", "ioloop", ".", "IOLoop", ".", "NONE", ",", "pycurl", ".", "POLL_IN", ":", "ioloop", ".", "IOLoop", ".", "READ", ",", "pycurl", ".", "POLL_OUT", ":", "ioloop", ".", "IOLoop", ".", "WRITE", ",", "pycurl", ".", "POLL_INOUT", ":", "ioloop", ".", "IOLoop", ".", "READ", "|", "ioloop", ".", "IOLoop", ".", "WRITE", ",", "}", "if", "event", "==", "pycurl", ".", "POLL_REMOVE", ":", "if", "fd", "in", "self", ".", "_fds", ":", "self", ".", "io_loop", ".", "remove_handler", "(", "fd", ")", "del", "self", ".", "_fds", "[", "fd", "]", "else", ":", "ioloop_event", "=", "event_map", "[", "event", "]", "# libcurl sometimes closes a socket and then opens a new", "# one using the same FD without giving us a POLL_NONE in", "# between. This is a problem with the epoll IOLoop,", "# because the kernel can tell when a socket is closed and", "# removes it from the epoll automatically, causing future", "# update_handler calls to fail. Since we can't tell when", "# this has happened, always use remove and re-add", "# instead of update.", "if", "fd", "in", "self", ".", "_fds", ":", "self", ".", "io_loop", ".", "remove_handler", "(", "fd", ")", "self", ".", "io_loop", ".", "add_handler", "(", "fd", ",", "self", ".", "_handle_events", ",", "ioloop_event", ")", "self", ".", "_fds", "[", "fd", "]", "=", "ioloop_event" ]
Called by libcurl when it wants to change the file descriptors it cares about.
[ "Called", "by", "libcurl", "when", "it", "wants", "to", "change", "the", "file", "descriptors", "it", "cares", "about", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L104-L131
26,876
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._set_timeout
def _set_timeout(self, msecs: int) -> None: """Called by libcurl to schedule a timeout.""" if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = self.io_loop.add_timeout( self.io_loop.time() + msecs / 1000.0, self._handle_timeout )
python
def _set_timeout(self, msecs: int) -> None: """Called by libcurl to schedule a timeout.""" if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = self.io_loop.add_timeout( self.io_loop.time() + msecs / 1000.0, self._handle_timeout )
[ "def", "_set_timeout", "(", "self", ",", "msecs", ":", "int", ")", "->", "None", ":", "if", "self", ".", "_timeout", "is", "not", "None", ":", "self", ".", "io_loop", ".", "remove_timeout", "(", "self", ".", "_timeout", ")", "self", ".", "_timeout", "=", "self", ".", "io_loop", ".", "add_timeout", "(", "self", ".", "io_loop", ".", "time", "(", ")", "+", "msecs", "/", "1000.0", ",", "self", ".", "_handle_timeout", ")" ]
Called by libcurl to schedule a timeout.
[ "Called", "by", "libcurl", "to", "schedule", "a", "timeout", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L133-L139
26,877
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._handle_events
def _handle_events(self, fd: int, events: int) -> None: """Called by IOLoop when there is activity on one of our file descriptors. """ action = 0 if events & ioloop.IOLoop.READ: action |= pycurl.CSELECT_IN if events & ioloop.IOLoop.WRITE: action |= pycurl.CSELECT_OUT while True: try: ret, num_handles = self._multi.socket_action(fd, action) except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests()
python
def _handle_events(self, fd: int, events: int) -> None: """Called by IOLoop when there is activity on one of our file descriptors. """ action = 0 if events & ioloop.IOLoop.READ: action |= pycurl.CSELECT_IN if events & ioloop.IOLoop.WRITE: action |= pycurl.CSELECT_OUT while True: try: ret, num_handles = self._multi.socket_action(fd, action) except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests()
[ "def", "_handle_events", "(", "self", ",", "fd", ":", "int", ",", "events", ":", "int", ")", "->", "None", ":", "action", "=", "0", "if", "events", "&", "ioloop", ".", "IOLoop", ".", "READ", ":", "action", "|=", "pycurl", ".", "CSELECT_IN", "if", "events", "&", "ioloop", ".", "IOLoop", ".", "WRITE", ":", "action", "|=", "pycurl", ".", "CSELECT_OUT", "while", "True", ":", "try", ":", "ret", ",", "num_handles", "=", "self", ".", "_multi", ".", "socket_action", "(", "fd", ",", "action", ")", "except", "pycurl", ".", "error", "as", "e", ":", "ret", "=", "e", ".", "args", "[", "0", "]", "if", "ret", "!=", "pycurl", ".", "E_CALL_MULTI_PERFORM", ":", "break", "self", ".", "_finish_pending_requests", "(", ")" ]
Called by IOLoop when there is activity on one of our file descriptors.
[ "Called", "by", "IOLoop", "when", "there", "is", "activity", "on", "one", "of", "our", "file", "descriptors", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L141-L157
26,878
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._handle_timeout
def _handle_timeout(self) -> None: """Called by IOLoop when the requested timeout has passed.""" self._timeout = None while True: try: ret, num_handles = self._multi.socket_action(pycurl.SOCKET_TIMEOUT, 0) except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests() # In theory, we shouldn't have to do this because curl will # call _set_timeout whenever the timeout changes. However, # sometimes after _handle_timeout we will need to reschedule # immediately even though nothing has changed from curl's # perspective. This is because when socket_action is # called with SOCKET_TIMEOUT, libcurl decides internally which # timeouts need to be processed by using a monotonic clock # (where available) while tornado uses python's time.time() # to decide when timeouts have occurred. When those clocks # disagree on elapsed time (as they will whenever there is an # NTP adjustment), tornado might call _handle_timeout before # libcurl is ready. After each timeout, resync the scheduled # timeout with libcurl's current state. new_timeout = self._multi.timeout() if new_timeout >= 0: self._set_timeout(new_timeout)
python
def _handle_timeout(self) -> None: """Called by IOLoop when the requested timeout has passed.""" self._timeout = None while True: try: ret, num_handles = self._multi.socket_action(pycurl.SOCKET_TIMEOUT, 0) except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests() # In theory, we shouldn't have to do this because curl will # call _set_timeout whenever the timeout changes. However, # sometimes after _handle_timeout we will need to reschedule # immediately even though nothing has changed from curl's # perspective. This is because when socket_action is # called with SOCKET_TIMEOUT, libcurl decides internally which # timeouts need to be processed by using a monotonic clock # (where available) while tornado uses python's time.time() # to decide when timeouts have occurred. When those clocks # disagree on elapsed time (as they will whenever there is an # NTP adjustment), tornado might call _handle_timeout before # libcurl is ready. After each timeout, resync the scheduled # timeout with libcurl's current state. new_timeout = self._multi.timeout() if new_timeout >= 0: self._set_timeout(new_timeout)
[ "def", "_handle_timeout", "(", "self", ")", "->", "None", ":", "self", ".", "_timeout", "=", "None", "while", "True", ":", "try", ":", "ret", ",", "num_handles", "=", "self", ".", "_multi", ".", "socket_action", "(", "pycurl", ".", "SOCKET_TIMEOUT", ",", "0", ")", "except", "pycurl", ".", "error", "as", "e", ":", "ret", "=", "e", ".", "args", "[", "0", "]", "if", "ret", "!=", "pycurl", ".", "E_CALL_MULTI_PERFORM", ":", "break", "self", ".", "_finish_pending_requests", "(", ")", "# In theory, we shouldn't have to do this because curl will", "# call _set_timeout whenever the timeout changes. However,", "# sometimes after _handle_timeout we will need to reschedule", "# immediately even though nothing has changed from curl's", "# perspective. This is because when socket_action is", "# called with SOCKET_TIMEOUT, libcurl decides internally which", "# timeouts need to be processed by using a monotonic clock", "# (where available) while tornado uses python's time.time()", "# to decide when timeouts have occurred. When those clocks", "# disagree on elapsed time (as they will whenever there is an", "# NTP adjustment), tornado might call _handle_timeout before", "# libcurl is ready. After each timeout, resync the scheduled", "# timeout with libcurl's current state.", "new_timeout", "=", "self", ".", "_multi", ".", "timeout", "(", ")", "if", "new_timeout", ">=", "0", ":", "self", ".", "_set_timeout", "(", "new_timeout", ")" ]
Called by IOLoop when the requested timeout has passed.
[ "Called", "by", "IOLoop", "when", "the", "requested", "timeout", "has", "passed", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L159-L186
26,879
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._handle_force_timeout
def _handle_force_timeout(self) -> None: """Called by IOLoop periodically to ask libcurl to process any events it may have forgotten about. """ while True: try: ret, num_handles = self._multi.socket_all() except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests()
python
def _handle_force_timeout(self) -> None: """Called by IOLoop periodically to ask libcurl to process any events it may have forgotten about. """ while True: try: ret, num_handles = self._multi.socket_all() except pycurl.error as e: ret = e.args[0] if ret != pycurl.E_CALL_MULTI_PERFORM: break self._finish_pending_requests()
[ "def", "_handle_force_timeout", "(", "self", ")", "->", "None", ":", "while", "True", ":", "try", ":", "ret", ",", "num_handles", "=", "self", ".", "_multi", ".", "socket_all", "(", ")", "except", "pycurl", ".", "error", "as", "e", ":", "ret", "=", "e", ".", "args", "[", "0", "]", "if", "ret", "!=", "pycurl", ".", "E_CALL_MULTI_PERFORM", ":", "break", "self", ".", "_finish_pending_requests", "(", ")" ]
Called by IOLoop periodically to ask libcurl to process any events it may have forgotten about.
[ "Called", "by", "IOLoop", "periodically", "to", "ask", "libcurl", "to", "process", "any", "events", "it", "may", "have", "forgotten", "about", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L188-L199
26,880
tornadoweb/tornado
tornado/curl_httpclient.py
CurlAsyncHTTPClient._finish_pending_requests
def _finish_pending_requests(self) -> None: """Process any requests that were completed by the last call to multi.socket_action. """ while True: num_q, ok_list, err_list = self._multi.info_read() for curl in ok_list: self._finish(curl) for curl, errnum, errmsg in err_list: self._finish(curl, errnum, errmsg) if num_q == 0: break self._process_queue()
python
def _finish_pending_requests(self) -> None: """Process any requests that were completed by the last call to multi.socket_action. """ while True: num_q, ok_list, err_list = self._multi.info_read() for curl in ok_list: self._finish(curl) for curl, errnum, errmsg in err_list: self._finish(curl, errnum, errmsg) if num_q == 0: break self._process_queue()
[ "def", "_finish_pending_requests", "(", "self", ")", "->", "None", ":", "while", "True", ":", "num_q", ",", "ok_list", ",", "err_list", "=", "self", ".", "_multi", ".", "info_read", "(", ")", "for", "curl", "in", "ok_list", ":", "self", ".", "_finish", "(", "curl", ")", "for", "curl", ",", "errnum", ",", "errmsg", "in", "err_list", ":", "self", ".", "_finish", "(", "curl", ",", "errnum", ",", "errmsg", ")", "if", "num_q", "==", "0", ":", "break", "self", ".", "_process_queue", "(", ")" ]
Process any requests that were completed by the last call to multi.socket_action.
[ "Process", "any", "requests", "that", "were", "completed", "by", "the", "last", "call", "to", "multi", ".", "socket_action", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/curl_httpclient.py#L201-L213
26,881
tornadoweb/tornado
demos/s3server/s3server.py
start
def start(port, root_directory, bucket_depth): """Starts the mock S3 server on the given port at the given path.""" application = S3Application(root_directory, bucket_depth) http_server = httpserver.HTTPServer(application) http_server.listen(port) ioloop.IOLoop.current().start()
python
def start(port, root_directory, bucket_depth): """Starts the mock S3 server on the given port at the given path.""" application = S3Application(root_directory, bucket_depth) http_server = httpserver.HTTPServer(application) http_server.listen(port) ioloop.IOLoop.current().start()
[ "def", "start", "(", "port", ",", "root_directory", ",", "bucket_depth", ")", ":", "application", "=", "S3Application", "(", "root_directory", ",", "bucket_depth", ")", "http_server", "=", "httpserver", ".", "HTTPServer", "(", "application", ")", "http_server", ".", "listen", "(", "port", ")", "ioloop", ".", "IOLoop", ".", "current", "(", ")", ".", "start", "(", ")" ]
Starts the mock S3 server on the given port at the given path.
[ "Starts", "the", "mock", "S3", "server", "on", "the", "given", "port", "at", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/s3server/s3server.py#L57-L62
26,882
tornadoweb/tornado
tornado/httpclient.py
HTTPClient.close
def close(self) -> None: """Closes the HTTPClient, freeing any resources used.""" if not self._closed: self._async_client.close() self._io_loop.close() self._closed = True
python
def close(self) -> None: """Closes the HTTPClient, freeing any resources used.""" if not self._closed: self._async_client.close() self._io_loop.close() self._closed = True
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_closed", ":", "self", ".", "_async_client", ".", "close", "(", ")", "self", ".", "_io_loop", ".", "close", "(", ")", "self", ".", "_closed", "=", "True" ]
Closes the HTTPClient, freeing any resources used.
[ "Closes", "the", "HTTPClient", "freeing", "any", "resources", "used", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpclient.py#L113-L118
26,883
tornadoweb/tornado
tornado/httpclient.py
HTTPClient.fetch
def fetch( self, request: Union["HTTPRequest", str], **kwargs: Any ) -> "HTTPResponse": """Executes a request, returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` If an error occurs during the fetch, we raise an `HTTPError` unless the ``raise_error`` keyword argument is set to False. """ response = self._io_loop.run_sync( functools.partial(self._async_client.fetch, request, **kwargs) ) return response
python
def fetch( self, request: Union["HTTPRequest", str], **kwargs: Any ) -> "HTTPResponse": """Executes a request, returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` If an error occurs during the fetch, we raise an `HTTPError` unless the ``raise_error`` keyword argument is set to False. """ response = self._io_loop.run_sync( functools.partial(self._async_client.fetch, request, **kwargs) ) return response
[ "def", "fetch", "(", "self", ",", "request", ":", "Union", "[", "\"HTTPRequest\"", ",", "str", "]", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"HTTPResponse\"", ":", "response", "=", "self", ".", "_io_loop", ".", "run_sync", "(", "functools", ".", "partial", "(", "self", ".", "_async_client", ".", "fetch", ",", "request", ",", "*", "*", "kwargs", ")", ")", "return", "response" ]
Executes a request, returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` If an error occurs during the fetch, we raise an `HTTPError` unless the ``raise_error`` keyword argument is set to False.
[ "Executes", "a", "request", "returning", "an", "HTTPResponse", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpclient.py#L120-L135
26,884
tornadoweb/tornado
tornado/httpclient.py
AsyncHTTPClient.close
def close(self) -> None: """Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when creating the `AsyncHTTPClient`. No other methods may be called on the `AsyncHTTPClient` after ``close()``. """ if self._closed: return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gotten mixed up. A # value of None appears to be possible when this is called # from a destructor (HTTPClient.__del__) as the weakref # gets cleared before the destructor runs. if cached_val is not None and cached_val is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache")
python
def close(self) -> None: """Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when creating the `AsyncHTTPClient`. No other methods may be called on the `AsyncHTTPClient` after ``close()``. """ if self._closed: return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gotten mixed up. A # value of None appears to be possible when this is called # from a destructor (HTTPClient.__del__) as the weakref # gets cleared before the destructor runs. if cached_val is not None and cached_val is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache")
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "if", "self", ".", "_instance_cache", "is", "not", "None", ":", "cached_val", "=", "self", ".", "_instance_cache", ".", "pop", "(", "self", ".", "io_loop", ",", "None", ")", "# If there's an object other than self in the instance", "# cache for our IOLoop, something has gotten mixed up. A", "# value of None appears to be possible when this is called", "# from a destructor (HTTPClient.__del__) as the weakref", "# gets cleared before the destructor runs.", "if", "cached_val", "is", "not", "None", "and", "cached_val", "is", "not", "self", ":", "raise", "RuntimeError", "(", "\"inconsistent AsyncHTTPClient cache\"", ")" ]
Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when creating the `AsyncHTTPClient`. No other methods may be called on the `AsyncHTTPClient` after ``close()``.
[ "Destroys", "this", "HTTP", "client", "freeing", "any", "file", "descriptors", "used", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpclient.py#L221-L245
26,885
tornadoweb/tornado
tornado/httpclient.py
AsyncHTTPClient.fetch
def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> Awaitable["HTTPResponse"]: """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` if the request returned a non-200 response code (other errors may also be raised if the server could not be contacted). Instead, if ``raise_error`` is set to False, the response will always be returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. Instead, you must check the response's ``error`` attribute or call its `~HTTPResponse.rethrow` method. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. The ``raise_error=False`` argument only affects the `HTTPError` raised when a non-200 response code is used, instead of suppressing all errors. """ if self._closed: raise RuntimeError("fetch() called on closed AsyncHTTPClient") if not isinstance(request, HTTPRequest): request = HTTPRequest(url=request, **kwargs) else: if kwargs: raise ValueError( "kwargs can't be used if request is an HTTPRequest object" ) # We may modify this (to add Host, Accept-Encoding, etc), # so make sure we don't modify the caller's object. This is also # where normal dicts get converted to HTTPHeaders objects. request.headers = httputil.HTTPHeaders(request.headers) request_proxy = _RequestProxy(request, self.defaults) future = Future() # type: Future[HTTPResponse] def handle_response(response: "HTTPResponse") -> None: if response.error: if raise_error or not response._error_is_response_code: future_set_exception_unless_cancelled(future, response.error) return future_set_result_unless_cancelled(future, response) self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response) return future
python
def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> Awaitable["HTTPResponse"]: """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` if the request returned a non-200 response code (other errors may also be raised if the server could not be contacted). Instead, if ``raise_error`` is set to False, the response will always be returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. Instead, you must check the response's ``error`` attribute or call its `~HTTPResponse.rethrow` method. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. The ``raise_error=False`` argument only affects the `HTTPError` raised when a non-200 response code is used, instead of suppressing all errors. """ if self._closed: raise RuntimeError("fetch() called on closed AsyncHTTPClient") if not isinstance(request, HTTPRequest): request = HTTPRequest(url=request, **kwargs) else: if kwargs: raise ValueError( "kwargs can't be used if request is an HTTPRequest object" ) # We may modify this (to add Host, Accept-Encoding, etc), # so make sure we don't modify the caller's object. This is also # where normal dicts get converted to HTTPHeaders objects. request.headers = httputil.HTTPHeaders(request.headers) request_proxy = _RequestProxy(request, self.defaults) future = Future() # type: Future[HTTPResponse] def handle_response(response: "HTTPResponse") -> None: if response.error: if raise_error or not response._error_is_response_code: future_set_exception_unless_cancelled(future, response.error) return future_set_result_unless_cancelled(future, response) self.fetch_impl(cast(HTTPRequest, request_proxy), handle_response) return future
[ "def", "fetch", "(", "self", ",", "request", ":", "Union", "[", "str", ",", "\"HTTPRequest\"", "]", ",", "raise_error", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Awaitable", "[", "\"HTTPResponse\"", "]", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"fetch() called on closed AsyncHTTPClient\"", ")", "if", "not", "isinstance", "(", "request", ",", "HTTPRequest", ")", ":", "request", "=", "HTTPRequest", "(", "url", "=", "request", ",", "*", "*", "kwargs", ")", "else", ":", "if", "kwargs", ":", "raise", "ValueError", "(", "\"kwargs can't be used if request is an HTTPRequest object\"", ")", "# We may modify this (to add Host, Accept-Encoding, etc),", "# so make sure we don't modify the caller's object. This is also", "# where normal dicts get converted to HTTPHeaders objects.", "request", ".", "headers", "=", "httputil", ".", "HTTPHeaders", "(", "request", ".", "headers", ")", "request_proxy", "=", "_RequestProxy", "(", "request", ",", "self", ".", "defaults", ")", "future", "=", "Future", "(", ")", "# type: Future[HTTPResponse]", "def", "handle_response", "(", "response", ":", "\"HTTPResponse\"", ")", "->", "None", ":", "if", "response", ".", "error", ":", "if", "raise_error", "or", "not", "response", ".", "_error_is_response_code", ":", "future_set_exception_unless_cancelled", "(", "future", ",", "response", ".", "error", ")", "return", "future_set_result_unless_cancelled", "(", "future", ",", "response", ")", "self", ".", "fetch_impl", "(", "cast", "(", "HTTPRequest", ",", "request_proxy", ")", ",", "handle_response", ")", "return", "future" ]
Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` if the request returned a non-200 response code (other errors may also be raised if the server could not be contacted). Instead, if ``raise_error`` is set to False, the response will always be returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. Instead, you must check the response's ``error`` attribute or call its `~HTTPResponse.rethrow` method. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. The ``raise_error=False`` argument only affects the `HTTPError` raised when a non-200 response code is used, instead of suppressing all errors.
[ "Executes", "a", "request", "asynchronously", "returning", "an", "HTTPResponse", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpclient.py#L247-L305
26,886
tornadoweb/tornado
tornado/httpclient.py
AsyncHTTPClient.configure
def configure( cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any ) -> None: """Configures the `AsyncHTTPClient` subclass to use. ``AsyncHTTPClient()`` actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or ``None`` to use the default, ``SimpleAsyncHTTPClient``) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument ``max_clients`` determines the maximum number of simultaneous `~AsyncHTTPClient.fetch()` operations that can execute in parallel on each `.IOLoop`. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") """ super(AsyncHTTPClient, cls).configure(impl, **kwargs)
python
def configure( cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any ) -> None: """Configures the `AsyncHTTPClient` subclass to use. ``AsyncHTTPClient()`` actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or ``None`` to use the default, ``SimpleAsyncHTTPClient``) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument ``max_clients`` determines the maximum number of simultaneous `~AsyncHTTPClient.fetch()` operations that can execute in parallel on each `.IOLoop`. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") """ super(AsyncHTTPClient, cls).configure(impl, **kwargs)
[ "def", "configure", "(", "cls", ",", "impl", ":", "\"Union[None, str, Type[Configurable]]\"", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "super", "(", "AsyncHTTPClient", ",", "cls", ")", ".", "configure", "(", "impl", ",", "*", "*", "kwargs", ")" ]
Configures the `AsyncHTTPClient` subclass to use. ``AsyncHTTPClient()`` actually creates an instance of a subclass. This method may be called with either a class object or the fully-qualified name of such a class (or ``None`` to use the default, ``SimpleAsyncHTTPClient``) If additional keyword arguments are given, they will be passed to the constructor of each subclass instance created. The keyword argument ``max_clients`` determines the maximum number of simultaneous `~AsyncHTTPClient.fetch()` operations that can execute in parallel on each `.IOLoop`. Additional arguments may be supported depending on the implementation class in use. Example:: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
[ "Configures", "the", "AsyncHTTPClient", "subclass", "to", "use", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpclient.py#L313-L334
26,887
aio-libs/aiohttp
aiohttp/connector.py
BaseConnector._cleanup
def _cleanup(self) -> None: """Cleanup unused transports.""" if self._cleanup_handle: self._cleanup_handle.cancel() now = self._loop.time() timeout = self._keepalive_timeout if self._conns: connections = {} deadline = now - timeout for key, conns in self._conns.items(): alive = [] for proto, use_time in conns: if proto.is_connected(): if use_time - deadline < 0: transport = proto.transport proto.close() if (key.is_ssl and not self._cleanup_closed_disabled): self._cleanup_closed_transports.append( transport) else: alive.append((proto, use_time)) if alive: connections[key] = alive self._conns = connections if self._conns: self._cleanup_handle = helpers.weakref_handle( self, '_cleanup', timeout, self._loop)
python
def _cleanup(self) -> None: """Cleanup unused transports.""" if self._cleanup_handle: self._cleanup_handle.cancel() now = self._loop.time() timeout = self._keepalive_timeout if self._conns: connections = {} deadline = now - timeout for key, conns in self._conns.items(): alive = [] for proto, use_time in conns: if proto.is_connected(): if use_time - deadline < 0: transport = proto.transport proto.close() if (key.is_ssl and not self._cleanup_closed_disabled): self._cleanup_closed_transports.append( transport) else: alive.append((proto, use_time)) if alive: connections[key] = alive self._conns = connections if self._conns: self._cleanup_handle = helpers.weakref_handle( self, '_cleanup', timeout, self._loop)
[ "def", "_cleanup", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_cleanup_handle", ":", "self", ".", "_cleanup_handle", ".", "cancel", "(", ")", "now", "=", "self", ".", "_loop", ".", "time", "(", ")", "timeout", "=", "self", ".", "_keepalive_timeout", "if", "self", ".", "_conns", ":", "connections", "=", "{", "}", "deadline", "=", "now", "-", "timeout", "for", "key", ",", "conns", "in", "self", ".", "_conns", ".", "items", "(", ")", ":", "alive", "=", "[", "]", "for", "proto", ",", "use_time", "in", "conns", ":", "if", "proto", ".", "is_connected", "(", ")", ":", "if", "use_time", "-", "deadline", "<", "0", ":", "transport", "=", "proto", ".", "transport", "proto", ".", "close", "(", ")", "if", "(", "key", ".", "is_ssl", "and", "not", "self", ".", "_cleanup_closed_disabled", ")", ":", "self", ".", "_cleanup_closed_transports", ".", "append", "(", "transport", ")", "else", ":", "alive", ".", "append", "(", "(", "proto", ",", "use_time", ")", ")", "if", "alive", ":", "connections", "[", "key", "]", "=", "alive", "self", ".", "_conns", "=", "connections", "if", "self", ".", "_conns", ":", "self", ".", "_cleanup_handle", "=", "helpers", ".", "weakref_handle", "(", "self", ",", "'_cleanup'", ",", "timeout", ",", "self", ".", "_loop", ")" ]
Cleanup unused transports.
[ "Cleanup", "unused", "transports", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L327-L359
26,888
aio-libs/aiohttp
aiohttp/connector.py
BaseConnector._cleanup_closed
def _cleanup_closed(self) -> None: """Double confirmation for transport close. Some broken ssl servers may leave socket open without proper close. """ if self._cleanup_closed_handle: self._cleanup_closed_handle.cancel() for transport in self._cleanup_closed_transports: if transport is not None: transport.abort() self._cleanup_closed_transports = [] if not self._cleanup_closed_disabled: self._cleanup_closed_handle = helpers.weakref_handle( self, '_cleanup_closed', self._cleanup_closed_period, self._loop)
python
def _cleanup_closed(self) -> None: """Double confirmation for transport close. Some broken ssl servers may leave socket open without proper close. """ if self._cleanup_closed_handle: self._cleanup_closed_handle.cancel() for transport in self._cleanup_closed_transports: if transport is not None: transport.abort() self._cleanup_closed_transports = [] if not self._cleanup_closed_disabled: self._cleanup_closed_handle = helpers.weakref_handle( self, '_cleanup_closed', self._cleanup_closed_period, self._loop)
[ "def", "_cleanup_closed", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_cleanup_closed_handle", ":", "self", ".", "_cleanup_closed_handle", ".", "cancel", "(", ")", "for", "transport", "in", "self", ".", "_cleanup_closed_transports", ":", "if", "transport", "is", "not", "None", ":", "transport", ".", "abort", "(", ")", "self", ".", "_cleanup_closed_transports", "=", "[", "]", "if", "not", "self", ".", "_cleanup_closed_disabled", ":", "self", ".", "_cleanup_closed_handle", "=", "helpers", ".", "weakref_handle", "(", "self", ",", "'_cleanup_closed'", ",", "self", ".", "_cleanup_closed_period", ",", "self", ".", "_loop", ")" ]
Double confirmation for transport close. Some broken ssl servers may leave socket open without proper close.
[ "Double", "confirmation", "for", "transport", "close", ".", "Some", "broken", "ssl", "servers", "may", "leave", "socket", "open", "without", "proper", "close", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L371-L387
26,889
aio-libs/aiohttp
aiohttp/connector.py
BaseConnector._available_connections
def _available_connections(self, key: 'ConnectionKey') -> int: """ Return number of available connections taking into account the limit, limit_per_host and the connection key. If it returns less than 1 means that there is no connections availables. """ if self._limit: # total calc available connections available = self._limit - len(self._acquired) # check limit per host if (self._limit_per_host and available > 0 and key in self._acquired_per_host): acquired = self._acquired_per_host.get(key) assert acquired is not None available = self._limit_per_host - len(acquired) elif self._limit_per_host and key in self._acquired_per_host: # check limit per host acquired = self._acquired_per_host.get(key) assert acquired is not None available = self._limit_per_host - len(acquired) else: available = 1 return available
python
def _available_connections(self, key: 'ConnectionKey') -> int: """ Return number of available connections taking into account the limit, limit_per_host and the connection key. If it returns less than 1 means that there is no connections availables. """ if self._limit: # total calc available connections available = self._limit - len(self._acquired) # check limit per host if (self._limit_per_host and available > 0 and key in self._acquired_per_host): acquired = self._acquired_per_host.get(key) assert acquired is not None available = self._limit_per_host - len(acquired) elif self._limit_per_host and key in self._acquired_per_host: # check limit per host acquired = self._acquired_per_host.get(key) assert acquired is not None available = self._limit_per_host - len(acquired) else: available = 1 return available
[ "def", "_available_connections", "(", "self", ",", "key", ":", "'ConnectionKey'", ")", "->", "int", ":", "if", "self", ".", "_limit", ":", "# total calc available connections", "available", "=", "self", ".", "_limit", "-", "len", "(", "self", ".", "_acquired", ")", "# check limit per host", "if", "(", "self", ".", "_limit_per_host", "and", "available", ">", "0", "and", "key", "in", "self", ".", "_acquired_per_host", ")", ":", "acquired", "=", "self", ".", "_acquired_per_host", ".", "get", "(", "key", ")", "assert", "acquired", "is", "not", "None", "available", "=", "self", ".", "_limit_per_host", "-", "len", "(", "acquired", ")", "elif", "self", ".", "_limit_per_host", "and", "key", "in", "self", ".", "_acquired_per_host", ":", "# check limit per host", "acquired", "=", "self", ".", "_acquired_per_host", ".", "get", "(", "key", ")", "assert", "acquired", "is", "not", "None", "available", "=", "self", ".", "_limit_per_host", "-", "len", "(", "acquired", ")", "else", ":", "available", "=", "1", "return", "available" ]
Return number of available connections taking into account the limit, limit_per_host and the connection key. If it returns less than 1 means that there is no connections availables.
[ "Return", "number", "of", "available", "connections", "taking", "into", "account", "the", "limit", "limit_per_host", "and", "the", "connection", "key", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L439-L467
26,890
aio-libs/aiohttp
aiohttp/connector.py
BaseConnector.connect
async def connect(self, req: 'ClientRequest', traces: List['Trace'], timeout: 'ClientTimeout') -> Connection: """Get from pool or create new connection.""" key = req.connection_key available = self._available_connections(key) # Wait if there are no available connections. if available <= 0: fut = self._loop.create_future() # This connection will now count towards the limit. waiters = self._waiters[key] waiters.append(fut) if traces: for trace in traces: await trace.send_connection_queued_start() try: await fut except BaseException as e: # remove a waiter even if it was cancelled, normally it's # removed when it's notified try: waiters.remove(fut) except ValueError: # fut may no longer be in list pass raise e finally: if not waiters: try: del self._waiters[key] except KeyError: # the key was evicted before. pass if traces: for trace in traces: await trace.send_connection_queued_end() proto = self._get(key) if proto is None: placeholder = cast(ResponseHandler, _TransportPlaceholder()) self._acquired.add(placeholder) self._acquired_per_host[key].add(placeholder) if traces: for trace in traces: await trace.send_connection_create_start() try: proto = await self._create_connection(req, traces, timeout) if self._closed: proto.close() raise ClientConnectionError("Connector is closed.") except BaseException: if not self._closed: self._acquired.remove(placeholder) self._drop_acquired_per_host(key, placeholder) self._release_waiter() raise else: if not self._closed: self._acquired.remove(placeholder) self._drop_acquired_per_host(key, placeholder) if traces: for trace in traces: await trace.send_connection_create_end() else: if traces: for trace in traces: await trace.send_connection_reuseconn() self._acquired.add(proto) self._acquired_per_host[key].add(proto) return Connection(self, key, proto, self._loop)
python
async def connect(self, req: 'ClientRequest', traces: List['Trace'], timeout: 'ClientTimeout') -> Connection: """Get from pool or create new connection.""" key = req.connection_key available = self._available_connections(key) # Wait if there are no available connections. if available <= 0: fut = self._loop.create_future() # This connection will now count towards the limit. waiters = self._waiters[key] waiters.append(fut) if traces: for trace in traces: await trace.send_connection_queued_start() try: await fut except BaseException as e: # remove a waiter even if it was cancelled, normally it's # removed when it's notified try: waiters.remove(fut) except ValueError: # fut may no longer be in list pass raise e finally: if not waiters: try: del self._waiters[key] except KeyError: # the key was evicted before. pass if traces: for trace in traces: await trace.send_connection_queued_end() proto = self._get(key) if proto is None: placeholder = cast(ResponseHandler, _TransportPlaceholder()) self._acquired.add(placeholder) self._acquired_per_host[key].add(placeholder) if traces: for trace in traces: await trace.send_connection_create_start() try: proto = await self._create_connection(req, traces, timeout) if self._closed: proto.close() raise ClientConnectionError("Connector is closed.") except BaseException: if not self._closed: self._acquired.remove(placeholder) self._drop_acquired_per_host(key, placeholder) self._release_waiter() raise else: if not self._closed: self._acquired.remove(placeholder) self._drop_acquired_per_host(key, placeholder) if traces: for trace in traces: await trace.send_connection_create_end() else: if traces: for trace in traces: await trace.send_connection_reuseconn() self._acquired.add(proto) self._acquired_per_host[key].add(proto) return Connection(self, key, proto, self._loop)
[ "async", "def", "connect", "(", "self", ",", "req", ":", "'ClientRequest'", ",", "traces", ":", "List", "[", "'Trace'", "]", ",", "timeout", ":", "'ClientTimeout'", ")", "->", "Connection", ":", "key", "=", "req", ".", "connection_key", "available", "=", "self", ".", "_available_connections", "(", "key", ")", "# Wait if there are no available connections.", "if", "available", "<=", "0", ":", "fut", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "# This connection will now count towards the limit.", "waiters", "=", "self", ".", "_waiters", "[", "key", "]", "waiters", ".", "append", "(", "fut", ")", "if", "traces", ":", "for", "trace", "in", "traces", ":", "await", "trace", ".", "send_connection_queued_start", "(", ")", "try", ":", "await", "fut", "except", "BaseException", "as", "e", ":", "# remove a waiter even if it was cancelled, normally it's", "# removed when it's notified", "try", ":", "waiters", ".", "remove", "(", "fut", ")", "except", "ValueError", ":", "# fut may no longer be in list", "pass", "raise", "e", "finally", ":", "if", "not", "waiters", ":", "try", ":", "del", "self", ".", "_waiters", "[", "key", "]", "except", "KeyError", ":", "# the key was evicted before.", "pass", "if", "traces", ":", "for", "trace", "in", "traces", ":", "await", "trace", ".", "send_connection_queued_end", "(", ")", "proto", "=", "self", ".", "_get", "(", "key", ")", "if", "proto", "is", "None", ":", "placeholder", "=", "cast", "(", "ResponseHandler", ",", "_TransportPlaceholder", "(", ")", ")", "self", ".", "_acquired", ".", "add", "(", "placeholder", ")", "self", ".", "_acquired_per_host", "[", "key", "]", ".", "add", "(", "placeholder", ")", "if", "traces", ":", "for", "trace", "in", "traces", ":", "await", "trace", ".", "send_connection_create_start", "(", ")", "try", ":", "proto", "=", "await", "self", ".", "_create_connection", "(", "req", ",", "traces", ",", "timeout", ")", "if", "self", ".", "_closed", ":", "proto", ".", "close", "(", ")", "raise", "ClientConnectionError", "(", "\"Connector is closed.\"", ")", "except", "BaseException", ":", "if", "not", "self", ".", "_closed", ":", "self", ".", "_acquired", ".", "remove", "(", "placeholder", ")", "self", ".", "_drop_acquired_per_host", "(", "key", ",", "placeholder", ")", "self", ".", "_release_waiter", "(", ")", "raise", "else", ":", "if", "not", "self", ".", "_closed", ":", "self", ".", "_acquired", ".", "remove", "(", "placeholder", ")", "self", ".", "_drop_acquired_per_host", "(", "key", ",", "placeholder", ")", "if", "traces", ":", "for", "trace", "in", "traces", ":", "await", "trace", ".", "send_connection_create_end", "(", ")", "else", ":", "if", "traces", ":", "for", "trace", "in", "traces", ":", "await", "trace", ".", "send_connection_reuseconn", "(", ")", "self", ".", "_acquired", ".", "add", "(", "proto", ")", "self", ".", "_acquired_per_host", "[", "key", "]", ".", "add", "(", "proto", ")", "return", "Connection", "(", "self", ",", "key", ",", "proto", ",", "self", ".", "_loop", ")" ]
Get from pool or create new connection.
[ "Get", "from", "pool", "or", "create", "new", "connection", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L469-L547
26,891
aio-libs/aiohttp
aiohttp/connector.py
BaseConnector._release_waiter
def _release_waiter(self) -> None: """ Iterates over all waiters till found one that is not finsihed and belongs to a host that has available connections. """ if not self._waiters: return # Having the dict keys ordered this avoids to iterate # at the same order at each call. queues = list(self._waiters.keys()) random.shuffle(queues) for key in queues: if self._available_connections(key) < 1: continue waiters = self._waiters[key] while waiters: waiter = waiters.popleft() if not waiter.done(): waiter.set_result(None) return
python
def _release_waiter(self) -> None: """ Iterates over all waiters till found one that is not finsihed and belongs to a host that has available connections. """ if not self._waiters: return # Having the dict keys ordered this avoids to iterate # at the same order at each call. queues = list(self._waiters.keys()) random.shuffle(queues) for key in queues: if self._available_connections(key) < 1: continue waiters = self._waiters[key] while waiters: waiter = waiters.popleft() if not waiter.done(): waiter.set_result(None) return
[ "def", "_release_waiter", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_waiters", ":", "return", "# Having the dict keys ordered this avoids to iterate", "# at the same order at each call.", "queues", "=", "list", "(", "self", ".", "_waiters", ".", "keys", "(", ")", ")", "random", ".", "shuffle", "(", "queues", ")", "for", "key", "in", "queues", ":", "if", "self", ".", "_available_connections", "(", "key", ")", "<", "1", ":", "continue", "waiters", "=", "self", ".", "_waiters", "[", "key", "]", "while", "waiters", ":", "waiter", "=", "waiters", ".", "popleft", "(", ")", "if", "not", "waiter", ".", "done", "(", ")", ":", "waiter", ".", "set_result", "(", "None", ")", "return" ]
Iterates over all waiters till found one that is not finsihed and belongs to a host that has available connections.
[ "Iterates", "over", "all", "waiters", "till", "found", "one", "that", "is", "not", "finsihed", "and", "belongs", "to", "a", "host", "that", "has", "available", "connections", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L575-L597
26,892
aio-libs/aiohttp
aiohttp/connector.py
TCPConnector.close
def close(self) -> Awaitable[None]: """Close all ongoing DNS calls.""" for ev in self._throttle_dns_events.values(): ev.cancel() return super().close()
python
def close(self) -> Awaitable[None]: """Close all ongoing DNS calls.""" for ev in self._throttle_dns_events.values(): ev.cancel() return super().close()
[ "def", "close", "(", "self", ")", "->", "Awaitable", "[", "None", "]", ":", "for", "ev", "in", "self", ".", "_throttle_dns_events", ".", "values", "(", ")", ":", "ev", ".", "cancel", "(", ")", "return", "super", "(", ")", ".", "close", "(", ")" ]
Close all ongoing DNS calls.
[ "Close", "all", "ongoing", "DNS", "calls", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L744-L749
26,893
aio-libs/aiohttp
aiohttp/connector.py
TCPConnector._create_connection
async def _create_connection(self, req: 'ClientRequest', traces: List['Trace'], timeout: 'ClientTimeout') -> ResponseHandler: """Create connection. Has same keyword arguments as BaseEventLoop.create_connection. """ if req.proxy: _, proto = await self._create_proxy_connection( req, traces, timeout) else: _, proto = await self._create_direct_connection( req, traces, timeout) return proto
python
async def _create_connection(self, req: 'ClientRequest', traces: List['Trace'], timeout: 'ClientTimeout') -> ResponseHandler: """Create connection. Has same keyword arguments as BaseEventLoop.create_connection. """ if req.proxy: _, proto = await self._create_proxy_connection( req, traces, timeout) else: _, proto = await self._create_direct_connection( req, traces, timeout) return proto
[ "async", "def", "_create_connection", "(", "self", ",", "req", ":", "'ClientRequest'", ",", "traces", ":", "List", "[", "'Trace'", "]", ",", "timeout", ":", "'ClientTimeout'", ")", "->", "ResponseHandler", ":", "if", "req", ".", "proxy", ":", "_", ",", "proto", "=", "await", "self", ".", "_create_proxy_connection", "(", "req", ",", "traces", ",", "timeout", ")", "else", ":", "_", ",", "proto", "=", "await", "self", ".", "_create_direct_connection", "(", "req", ",", "traces", ",", "timeout", ")", "return", "proto" ]
Create connection. Has same keyword arguments as BaseEventLoop.create_connection.
[ "Create", "connection", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L842-L856
26,894
aio-libs/aiohttp
aiohttp/connector.py
TCPConnector._get_ssl_context
def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]: """Logic to get the correct SSL context 0. if req.ssl is false, return None 1. if ssl_context is specified in req, use it 2. if _ssl_context is specified in self, use it 3. otherwise: 1. if verify_ssl is not specified in req, use self.ssl_context (will generate a default context according to self.verify_ssl) 2. if verify_ssl is True in req, generate a default SSL context 3. if verify_ssl is False in req, generate a SSL context that won't verify """ if req.is_ssl(): if ssl is None: # pragma: no cover raise RuntimeError('SSL is not supported.') sslcontext = req.ssl if isinstance(sslcontext, ssl.SSLContext): return sslcontext if sslcontext is not None: # not verified or fingerprinted return self._make_ssl_context(False) sslcontext = self._ssl if isinstance(sslcontext, ssl.SSLContext): return sslcontext if sslcontext is not None: # not verified or fingerprinted return self._make_ssl_context(False) return self._make_ssl_context(True) else: return None
python
def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]: """Logic to get the correct SSL context 0. if req.ssl is false, return None 1. if ssl_context is specified in req, use it 2. if _ssl_context is specified in self, use it 3. otherwise: 1. if verify_ssl is not specified in req, use self.ssl_context (will generate a default context according to self.verify_ssl) 2. if verify_ssl is True in req, generate a default SSL context 3. if verify_ssl is False in req, generate a SSL context that won't verify """ if req.is_ssl(): if ssl is None: # pragma: no cover raise RuntimeError('SSL is not supported.') sslcontext = req.ssl if isinstance(sslcontext, ssl.SSLContext): return sslcontext if sslcontext is not None: # not verified or fingerprinted return self._make_ssl_context(False) sslcontext = self._ssl if isinstance(sslcontext, ssl.SSLContext): return sslcontext if sslcontext is not None: # not verified or fingerprinted return self._make_ssl_context(False) return self._make_ssl_context(True) else: return None
[ "def", "_get_ssl_context", "(", "self", ",", "req", ":", "'ClientRequest'", ")", "->", "Optional", "[", "SSLContext", "]", ":", "if", "req", ".", "is_ssl", "(", ")", ":", "if", "ssl", "is", "None", ":", "# pragma: no cover", "raise", "RuntimeError", "(", "'SSL is not supported.'", ")", "sslcontext", "=", "req", ".", "ssl", "if", "isinstance", "(", "sslcontext", ",", "ssl", ".", "SSLContext", ")", ":", "return", "sslcontext", "if", "sslcontext", "is", "not", "None", ":", "# not verified or fingerprinted", "return", "self", ".", "_make_ssl_context", "(", "False", ")", "sslcontext", "=", "self", ".", "_ssl", "if", "isinstance", "(", "sslcontext", ",", "ssl", ".", "SSLContext", ")", ":", "return", "sslcontext", "if", "sslcontext", "is", "not", "None", ":", "# not verified or fingerprinted", "return", "self", ".", "_make_ssl_context", "(", "False", ")", "return", "self", ".", "_make_ssl_context", "(", "True", ")", "else", ":", "return", "None" ]
Logic to get the correct SSL context 0. if req.ssl is false, return None 1. if ssl_context is specified in req, use it 2. if _ssl_context is specified in self, use it 3. otherwise: 1. if verify_ssl is not specified in req, use self.ssl_context (will generate a default context according to self.verify_ssl) 2. if verify_ssl is True in req, generate a default SSL context 3. if verify_ssl is False in req, generate a SSL context that won't verify
[ "Logic", "to", "get", "the", "correct", "SSL", "context" ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/connector.py#L871-L902
26,895
aio-libs/aiohttp
aiohttp/http_websocket.py
WSMessage.json
def json(self, *, # type: ignore loads: Callable[[Any], Any]=json.loads) -> None: """Return parsed JSON data. .. versionadded:: 0.22 """ return loads(self.data)
python
def json(self, *, # type: ignore loads: Callable[[Any], Any]=json.loads) -> None: """Return parsed JSON data. .. versionadded:: 0.22 """ return loads(self.data)
[ "def", "json", "(", "self", ",", "*", ",", "# type: ignore", "loads", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", "=", "json", ".", "loads", ")", "->", "None", ":", "return", "loads", "(", "self", ".", "data", ")" ]
Return parsed JSON data. .. versionadded:: 0.22
[ "Return", "parsed", "JSON", "data", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/http_websocket.py#L85-L91
26,896
aio-libs/aiohttp
aiohttp/http_websocket.py
WebSocketWriter.pong
async def pong(self, message: bytes=b'') -> None: """Send pong message.""" if isinstance(message, str): message = message.encode('utf-8') await self._send_frame(message, WSMsgType.PONG)
python
async def pong(self, message: bytes=b'') -> None: """Send pong message.""" if isinstance(message, str): message = message.encode('utf-8') await self._send_frame(message, WSMsgType.PONG)
[ "async", "def", "pong", "(", "self", ",", "message", ":", "bytes", "=", "b''", ")", "->", "None", ":", "if", "isinstance", "(", "message", ",", "str", ")", ":", "message", "=", "message", ".", "encode", "(", "'utf-8'", ")", "await", "self", ".", "_send_frame", "(", "message", ",", "WSMsgType", ".", "PONG", ")" ]
Send pong message.
[ "Send", "pong", "message", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/http_websocket.py#L622-L626
26,897
aio-libs/aiohttp
aiohttp/http_websocket.py
WebSocketWriter.ping
async def ping(self, message: bytes=b'') -> None: """Send ping message.""" if isinstance(message, str): message = message.encode('utf-8') await self._send_frame(message, WSMsgType.PING)
python
async def ping(self, message: bytes=b'') -> None: """Send ping message.""" if isinstance(message, str): message = message.encode('utf-8') await self._send_frame(message, WSMsgType.PING)
[ "async", "def", "ping", "(", "self", ",", "message", ":", "bytes", "=", "b''", ")", "->", "None", ":", "if", "isinstance", "(", "message", ",", "str", ")", ":", "message", "=", "message", ".", "encode", "(", "'utf-8'", ")", "await", "self", ".", "_send_frame", "(", "message", ",", "WSMsgType", ".", "PING", ")" ]
Send ping message.
[ "Send", "ping", "message", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/http_websocket.py#L628-L632
26,898
aio-libs/aiohttp
aiohttp/cookiejar.py
CookieJar.update_cookies
def update_cookies(self, cookies: LooseCookies, response_url: URL=URL()) -> None: """Update cookies.""" hostname = response_url.raw_host if not self._unsafe and is_ip_address(hostname): # Don't accept cookies from IPs return if isinstance(cookies, Mapping): cookies = cookies.items() # type: ignore for name, cookie in cookies: if not isinstance(cookie, Morsel): tmp = SimpleCookie() tmp[name] = cookie # type: ignore cookie = tmp[name] domain = cookie["domain"] # ignore domains with trailing dots if domain.endswith('.'): domain = "" del cookie["domain"] if not domain and hostname is not None: # Set the cookie's domain to the response hostname # and set its host-only-flag self._host_only_cookies.add((hostname, name)) domain = cookie["domain"] = hostname if domain.startswith("."): # Remove leading dot domain = domain[1:] cookie["domain"] = domain if hostname and not self._is_domain_match(domain, hostname): # Setting cookies for different domains is not allowed continue path = cookie["path"] if not path or not path.startswith("/"): # Set the cookie's path to the response path path = response_url.path if not path.startswith("/"): path = "/" else: # Cut everything from the last slash to the end path = "/" + path[1:path.rfind("/")] cookie["path"] = path max_age = cookie["max-age"] if max_age: try: delta_seconds = int(max_age) self._expire_cookie(self._loop.time() + delta_seconds, domain, name) except ValueError: cookie["max-age"] = "" else: expires = cookie["expires"] if expires: expire_time = self._parse_date(expires) if expire_time: self._expire_cookie(expire_time.timestamp(), domain, name) else: cookie["expires"] = "" self._cookies[domain][name] = cookie self._do_expiration()
python
def update_cookies(self, cookies: LooseCookies, response_url: URL=URL()) -> None: """Update cookies.""" hostname = response_url.raw_host if not self._unsafe and is_ip_address(hostname): # Don't accept cookies from IPs return if isinstance(cookies, Mapping): cookies = cookies.items() # type: ignore for name, cookie in cookies: if not isinstance(cookie, Morsel): tmp = SimpleCookie() tmp[name] = cookie # type: ignore cookie = tmp[name] domain = cookie["domain"] # ignore domains with trailing dots if domain.endswith('.'): domain = "" del cookie["domain"] if not domain and hostname is not None: # Set the cookie's domain to the response hostname # and set its host-only-flag self._host_only_cookies.add((hostname, name)) domain = cookie["domain"] = hostname if domain.startswith("."): # Remove leading dot domain = domain[1:] cookie["domain"] = domain if hostname and not self._is_domain_match(domain, hostname): # Setting cookies for different domains is not allowed continue path = cookie["path"] if not path or not path.startswith("/"): # Set the cookie's path to the response path path = response_url.path if not path.startswith("/"): path = "/" else: # Cut everything from the last slash to the end path = "/" + path[1:path.rfind("/")] cookie["path"] = path max_age = cookie["max-age"] if max_age: try: delta_seconds = int(max_age) self._expire_cookie(self._loop.time() + delta_seconds, domain, name) except ValueError: cookie["max-age"] = "" else: expires = cookie["expires"] if expires: expire_time = self._parse_date(expires) if expire_time: self._expire_cookie(expire_time.timestamp(), domain, name) else: cookie["expires"] = "" self._cookies[domain][name] = cookie self._do_expiration()
[ "def", "update_cookies", "(", "self", ",", "cookies", ":", "LooseCookies", ",", "response_url", ":", "URL", "=", "URL", "(", ")", ")", "->", "None", ":", "hostname", "=", "response_url", ".", "raw_host", "if", "not", "self", ".", "_unsafe", "and", "is_ip_address", "(", "hostname", ")", ":", "# Don't accept cookies from IPs", "return", "if", "isinstance", "(", "cookies", ",", "Mapping", ")", ":", "cookies", "=", "cookies", ".", "items", "(", ")", "# type: ignore", "for", "name", ",", "cookie", "in", "cookies", ":", "if", "not", "isinstance", "(", "cookie", ",", "Morsel", ")", ":", "tmp", "=", "SimpleCookie", "(", ")", "tmp", "[", "name", "]", "=", "cookie", "# type: ignore", "cookie", "=", "tmp", "[", "name", "]", "domain", "=", "cookie", "[", "\"domain\"", "]", "# ignore domains with trailing dots", "if", "domain", ".", "endswith", "(", "'.'", ")", ":", "domain", "=", "\"\"", "del", "cookie", "[", "\"domain\"", "]", "if", "not", "domain", "and", "hostname", "is", "not", "None", ":", "# Set the cookie's domain to the response hostname", "# and set its host-only-flag", "self", ".", "_host_only_cookies", ".", "add", "(", "(", "hostname", ",", "name", ")", ")", "domain", "=", "cookie", "[", "\"domain\"", "]", "=", "hostname", "if", "domain", ".", "startswith", "(", "\".\"", ")", ":", "# Remove leading dot", "domain", "=", "domain", "[", "1", ":", "]", "cookie", "[", "\"domain\"", "]", "=", "domain", "if", "hostname", "and", "not", "self", ".", "_is_domain_match", "(", "domain", ",", "hostname", ")", ":", "# Setting cookies for different domains is not allowed", "continue", "path", "=", "cookie", "[", "\"path\"", "]", "if", "not", "path", "or", "not", "path", ".", "startswith", "(", "\"/\"", ")", ":", "# Set the cookie's path to the response path", "path", "=", "response_url", ".", "path", "if", "not", "path", ".", "startswith", "(", "\"/\"", ")", ":", "path", "=", "\"/\"", "else", ":", "# Cut everything from the last slash to the end", "path", "=", "\"/\"", "+", "path", "[", "1", ":", "path", ".", "rfind", "(", "\"/\"", ")", "]", "cookie", "[", "\"path\"", "]", "=", "path", "max_age", "=", "cookie", "[", "\"max-age\"", "]", "if", "max_age", ":", "try", ":", "delta_seconds", "=", "int", "(", "max_age", ")", "self", ".", "_expire_cookie", "(", "self", ".", "_loop", ".", "time", "(", ")", "+", "delta_seconds", ",", "domain", ",", "name", ")", "except", "ValueError", ":", "cookie", "[", "\"max-age\"", "]", "=", "\"\"", "else", ":", "expires", "=", "cookie", "[", "\"expires\"", "]", "if", "expires", ":", "expire_time", "=", "self", ".", "_parse_date", "(", "expires", ")", "if", "expire_time", ":", "self", ".", "_expire_cookie", "(", "expire_time", ".", "timestamp", "(", ")", ",", "domain", ",", "name", ")", "else", ":", "cookie", "[", "\"expires\"", "]", "=", "\"\"", "self", ".", "_cookies", "[", "domain", "]", "[", "name", "]", "=", "cookie", "self", ".", "_do_expiration", "(", ")" ]
Update cookies.
[ "Update", "cookies", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/cookiejar.py#L113-L186
26,899
aio-libs/aiohttp
aiohttp/cookiejar.py
CookieJar.filter_cookies
def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]': """Returns this jar's cookies filtered by their attributes.""" self._do_expiration() request_url = URL(request_url) filtered = SimpleCookie() hostname = request_url.raw_host or "" is_not_secure = request_url.scheme not in ("https", "wss") for cookie in self: name = cookie.key domain = cookie["domain"] # Send shared cookies if not domain: filtered[name] = cookie.value continue if not self._unsafe and is_ip_address(hostname): continue if (domain, name) in self._host_only_cookies: if domain != hostname: continue elif not self._is_domain_match(domain, hostname): continue if not self._is_path_match(request_url.path, cookie["path"]): continue if is_not_secure and cookie["secure"]: continue # It's critical we use the Morsel so the coded_value # (based on cookie version) is preserved mrsl_val = cast('Morsel[str]', cookie.get(cookie.key, Morsel())) mrsl_val.set(cookie.key, cookie.value, cookie.coded_value) filtered[name] = mrsl_val return filtered
python
def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]': """Returns this jar's cookies filtered by their attributes.""" self._do_expiration() request_url = URL(request_url) filtered = SimpleCookie() hostname = request_url.raw_host or "" is_not_secure = request_url.scheme not in ("https", "wss") for cookie in self: name = cookie.key domain = cookie["domain"] # Send shared cookies if not domain: filtered[name] = cookie.value continue if not self._unsafe and is_ip_address(hostname): continue if (domain, name) in self._host_only_cookies: if domain != hostname: continue elif not self._is_domain_match(domain, hostname): continue if not self._is_path_match(request_url.path, cookie["path"]): continue if is_not_secure and cookie["secure"]: continue # It's critical we use the Morsel so the coded_value # (based on cookie version) is preserved mrsl_val = cast('Morsel[str]', cookie.get(cookie.key, Morsel())) mrsl_val.set(cookie.key, cookie.value, cookie.coded_value) filtered[name] = mrsl_val return filtered
[ "def", "filter_cookies", "(", "self", ",", "request_url", ":", "URL", "=", "URL", "(", ")", ")", "->", "'BaseCookie[str]'", ":", "self", ".", "_do_expiration", "(", ")", "request_url", "=", "URL", "(", "request_url", ")", "filtered", "=", "SimpleCookie", "(", ")", "hostname", "=", "request_url", ".", "raw_host", "or", "\"\"", "is_not_secure", "=", "request_url", ".", "scheme", "not", "in", "(", "\"https\"", ",", "\"wss\"", ")", "for", "cookie", "in", "self", ":", "name", "=", "cookie", ".", "key", "domain", "=", "cookie", "[", "\"domain\"", "]", "# Send shared cookies", "if", "not", "domain", ":", "filtered", "[", "name", "]", "=", "cookie", ".", "value", "continue", "if", "not", "self", ".", "_unsafe", "and", "is_ip_address", "(", "hostname", ")", ":", "continue", "if", "(", "domain", ",", "name", ")", "in", "self", ".", "_host_only_cookies", ":", "if", "domain", "!=", "hostname", ":", "continue", "elif", "not", "self", ".", "_is_domain_match", "(", "domain", ",", "hostname", ")", ":", "continue", "if", "not", "self", ".", "_is_path_match", "(", "request_url", ".", "path", ",", "cookie", "[", "\"path\"", "]", ")", ":", "continue", "if", "is_not_secure", "and", "cookie", "[", "\"secure\"", "]", ":", "continue", "# It's critical we use the Morsel so the coded_value", "# (based on cookie version) is preserved", "mrsl_val", "=", "cast", "(", "'Morsel[str]'", ",", "cookie", ".", "get", "(", "cookie", ".", "key", ",", "Morsel", "(", ")", ")", ")", "mrsl_val", ".", "set", "(", "cookie", ".", "key", ",", "cookie", ".", "value", ",", "cookie", ".", "coded_value", ")", "filtered", "[", "name", "]", "=", "mrsl_val", "return", "filtered" ]
Returns this jar's cookies filtered by their attributes.
[ "Returns", "this", "jar", "s", "cookies", "filtered", "by", "their", "attributes", "." ]
9504fe2affaaff673fa4f3754c1c44221f8ba47d
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/cookiejar.py#L188-L226