text
stringlengths
81
112k
Get a view over at most ``size`` bytes (possibly fewer) at the current buffer position. def peek(self, size: int) -> memoryview: """ Get a view over at most ``size`` bytes (possibly fewer) at the current buffer position. """ assert size > 0 try: is_me...
Advance the current buffer position by ``size`` bytes. def advance(self, size: int) -> None: """ Advance the current buffer position by ``size`` bytes. """ assert 0 < size <= self._size self._size -= size pos = self._first_pos buffers = self._buffers whi...
Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not sati...
Asynchronously read until we have found the given delimiter. The result includes all the data read including the delimiter. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the delimiter is not found. .. versioncha...
Asynchronously read a number of bytes. If ``partial`` is true, data is returned as soon as we have any bytes to return (but never more than ``num_bytes``) .. versionchanged:: 4.0 Added the ``partial`` argument. The callback argument is now optional and a `.Future` will...
Asynchronously read a number of bytes. ``buf`` must be a writable buffer into which data will be read. If ``partial`` is true, the callback is run as soon as any bytes have been read. Otherwise, it is run when the ``buf`` has been entirely filled with read data. .. versionadd...
Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 ...
Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. .. versionchanged:: 4.0 Now returns a `.Future` if...
Call the given callback when the stream is closed. This mostly is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed. However, it is still useful as a way to signal that the strea...
Close this stream. If ``exc_info`` is true, set the ``error`` attribute to the current exception from `sys.exc_info` (or if ``exc_info`` is a tuple, use that instead of `sys.exc_info`). def close( self, exc_info: Union[ None, bool, BaseExcept...
Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket. def _try_inline_read(self) -> None: """Attempt to complete the...
Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception. def _read_to_buffer(self) -> Optional[int]: ...
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. def _read_from_buffer(self, pos: int) -> None: """Attempts to complete the currently-pending read from the buffer. The argument...
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. def _find_read_pos(self) -> Optional[int]: """Attempts to find a position in the read buffer that satis...
Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler. Implementation notes: Reads and writes have a fast path and a slow path. The fast path reads synchronously from socket buffers, while the slow path uses `_add_io_state` to schedule an IOLoop callback. To detect clo...
Return ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses. def _is_connreset(self, exc: BaseException) -> bool: """Return ``True`` if exc is ECONNRESET or equivalent. May be overridden in subclasses. """ return ( isinstance(exc, (socket.er...
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 c...
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 s...
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. def _verify_cert(self, peercert: Any) -> bool: """Ret...
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 ...
Turns on formatted logging output as configured. This is called automatically by `tornado.options.parse_command_line` and `tornado.options.parse_config_file`. def enable_pretty_logging(options: Any = None, logger: logging.Logger = None) -> None: """Turns on formatted logging output as configured. Thi...
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. d...
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`` ...
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. def _on_timeout(self, key: object, info: str = None) -> None: """Timeout callback of request....
Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information. def _on_timeout(self, info: str = None) -> None: """Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a tim...
Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process def _oauth10a_signature( consumer_token: Dict[str, Any], method: str, url: str, parameters: Dict[str, Any] = {}, token: Dict[str, Any] = None, ) -> bytes: """Calculates the ...
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 u...
Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the `authenticate_redirect()` method (which is often the same as the one that calls it; in that case you would call `get_authenticated_user` if the ``openid.mod...
Redirects the user to obtain OAuth authorization for this service. The ``callback_uri`` may be omitted if you have previously registered a callback URI with the third-party service. For some services, you must use a previously-registered callback URI and cannot specify a callback via th...
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 ...
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 wi...
Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call ``get_authenticated_user`` in the handle...
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, ...
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 compatibilit...
Fetches the given API path, e.g., ``statuses/user_timeline/btaylor`` The path should not include the format or API version number. (we automatically use JSON format and API version 1). If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as...
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 packa...
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 ...
Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. An introduction to the Facebook Graph API can be found at http://developers.facebook.com/docs/api ...
Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]: """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the cond...
Wake ``n`` waiters. 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 ...
Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block. 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:...
Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until the internal flag is true. Returns an awaitable, which raises `tor...
Increment the counter and wake one waiter. def release(self) -> None: """Increment the counter and wake one waiter.""" self._value += 1 while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): self._value -= 1 # If the ...
Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline. def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Decrement t...
Increment the counter and wake one waiter. def release(self) -> None: """Increment the counter and wake one waiter.""" if self._value >= self._initial_value: raise ValueError("Semaphore released too many times") super(BoundedSemaphore, self).release()
Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Re...
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...
Clears the callback attributes. This allows the request handler to be garbage collected more quickly in CPython by breaking up reference cycles. def _clear_callbacks(self) -> None: """Clears the callback attributes. This allows the request handler to be garbage collected more ...
Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. May only be called during `.HTTPMessageDelegate.headers_received`. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. def detac...
Implements `.HTTPConnection.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`.""" l...
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. def write(self, chunk: bytes) -> "Future[None]": """Implements `.HTTPConnection.write`. For backward...
Implements `.HTTPConnection.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...
Closes the connection. Returns a `.Future` that resolves after the serving loop has exited. async def close(self) -> None: """Closes the connection. Returns a `.Future` that resolves after the serving loop has exited. """ self.stream.close() # Block until the serving l...
Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate` def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None: """Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate` """ as...
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 corouti...
Sends the given message to the client of this Web Socket. The message may be either a string or a dict (which will be encoded as json). If the ``binary`` argument is false, the message will be sent as utf8; in binary mode any byte string is allowed. If the connection is alread...
Send ping frame to the remote end. The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications. Consider using the ``websocket_ping_interval`` applicatio...
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 a...
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 ...
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 expens...
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. def _run_callback( self, callback: Callable, *args: Any, **kwargs: Any ) -> "Optional[Future[Any]]": """Runs the given ca...
Instantly aborts the WebSocket connection by closing the socket 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() # forc...
Verifies all invariant- and required headers If a header is missing or have an incorrect value ValueError will be raised def _handle_websocket_headers(self, handler: WebSocketHandler) -> None: """Verifies all invariant- and required headers If a header is missing or have an incorrect ...
Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key. 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() ...
Process the headers sent by the server to this client connection. 'key' is the websocket handshake challenge/response key. def _process_server_headers( self, key: Union[str, bytes], headers: httputil.HTTPHeaders ) -> None: """Process the headers sent by the server to this client connection...
Converts a websocket agreed_parameters set to keyword arguments for our compressor objects. def _get_compressor_options( self, side: str, agreed_parameters: Dict[str, Any], compression_options: Dict[str, Any] = None, ) -> Dict[str, Any]: """Converts a websocket agree...
Sends the given message to the client of this Web Socket. def write_message( self, message: Union[str, bytes], binary: bool = False ) -> "Future[None]": """Sends the given message to the client of this Web Socket.""" if binary: opcode = 0x2 else: opcode = 0x1...
Send ping frame. def write_ping(self, data: bytes) -> None: """Send ping frame.""" assert isinstance(data, bytes) self._write_frame(True, 0x9, data)
Execute on_message, returning its Future if it is a coroutine. 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: ...
Closes the WebSocket connection. 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 # "norm...
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. def is_closing(self) -> bool: """Return ``True`` if this connection is closing. The connection ...
Start sending periodic pings to keep the connection alive 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() ...
Send a ping to keep the websocket alive Called periodically if the websocket_ping_interval is set and non-zero. 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_cl...
Closes the websocket connection. ``code`` and ``reason`` are documented under `WebSocketHandler.close`. .. versionadded:: 3.2 .. versionchanged:: 4.0 Added the ``code`` and ``reason`` arguments. def close(self, code: int = None, reason: str = None) -> None: """Clo...
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`...
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 c...
Send ping frame to the remote end. The data argument allows a small amount of data (up to 125 bytes) to be sent as a part of the ping message. Note that not all websocket implementations expose this data to applications. Consider using the ``ping_interval`` argument to ...
Defines an option in the global namespace. See `OptionParser.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 a...
Parses global options from the command line. See `OptionParser.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, f...
Parses global options from a config file. See `OptionParser.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)
An iterable of (name, value) pairs. .. versionadded:: 3.1 def items(self) -> Iterable[Tuple[str, Any]]: """An iterable of (name, value) pairs. .. versionadded:: 3.1 """ return [(opt.name, opt.value()) for name, opt in self._options.items()]
The set of option-groups created by ``define``. .. versionadded:: 3.1 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())
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_com...
The names and values of all options. .. versionadded:: 3.1 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())
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 ...
Parses all options given on the command line (defaults to `sys.argv`). Options look like ``--option=value`` and are parsed according to their ``type``. For boolean options, ``--option`` is equivalent to ``--option=true`` If the option has ``multiple=True``, comma-separated valu...
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 ...
Prints all the command line options to stderr (or another file). def print_help(self, file: TextIO = None) -> None: """Prints all the command line options to stderr (or another file).""" if file is None: file = sys.stderr print("Usage: %s [OPTIONS]" % sys.argv[0], file=file) ...
Convert a SQL row to an object supporting dict and attribute access. 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 re...
Execute a SQL statement. Must be called with ``await self.execute(...)`` async def execute(self, stmt, *args): """Execute a SQL statement. Must be called with ``await self.execute(...)`` """ with (await self.application.db.cursor()) as cur: await cur.execute(stmt, ...
Query for a list of results. Typical usage:: results = await self.query(...) Or:: for row in await self.query(...) async def query(self, stmt, *args): """Query for a list of results. Typical usage:: results = await self.query(...) Or:: ...
Query for exactly one result. Raises NoResultError if there are no results, or ValueError if there are more than one. 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....
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`. def listen(self, port: i...
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 pr...
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 ...
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_process...
Stops listening for new connections. Requests currently in progress may still continue after the server is stopped. def stop(self) -> None: """Stops listening for new connections. Requests currently in progress may still continue after the server is stopped. """ ...
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.tim...
Put an item into the queue without blocking. If no free slot is immediately available, raise `QueueFull`. def put_nowait(self, item: _T) -> None: """Put an item into the queue without blocking. If no free slot is immediately available, raise `QueueFull`. """ self._consume_expi...
Remove and return an item from the queue. Returns an awaitable which resolves once an item is available, or 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 ...