Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def current(instance: bool = True) -> Optional["IOLoop"]: try: loop = asyncio.get_event_loop() except (RuntimeError, AssertionError): if not instance: return None raise try: retu...
[ "Returns the current thread's `IOLoop`.\n\n If an `IOLoop` is currently running or has been marked as\n current by `make_current`, returns that instance. If there is\n no current `IOLoop` and ``instance`` is true, creates one.\n\n .. versionchanged:: 4.1\n Added ``instance`` a...
Please provide a description of the function:def clear_current() -> None: old = IOLoop.current(instance=False) if old is not None: old._clear_current_hook() if asyncio is None: IOLoop._current.instance = None
[ "Clears the `IOLoop` for the current thread.\n\n Intended primarily for use by test frameworks in between tests.\n\n .. versionchanged:: 5.0\n This method also clears the current `asyncio` event loop.\n " ]
Please provide a description of the function:def add_handler( # noqa: F811 self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int ) -> None: raise NotImplementedError()
[ "Registers the given handler to receive the given events for ``fd``.\n\n The ``fd`` argument may either be an integer file descriptor or\n a file-like object with a ``fileno()`` and ``close()`` method.\n\n The ``events`` argument is a bitwise or of the constants\n ``IOLoop.READ``, ``IOLo...
Please provide a description of the function:def _setup_logging(self) -> None: if not any( [ logging.getLogger().handlers, logging.getLogger("tornado").handlers, logging.getLogger("tornado.application").handlers, ] ): ...
[ "The IOLoop catches and logs exceptions, so it's\n important that log output be visible. However, python's\n default behavior for non-root loggers (prior to python\n 3.2) is to print an unhelpful \"no handlers could be\n found\" message rather than the actual log entry, so we\n m...
Please provide a description of the function:def run_sync(self, func: Callable, timeout: float = None) -> Any: future_cell = [None] # type: List[Optional[Future]] def run() -> None: try: result = func() if result is not None: fro...
[ "Starts the `IOLoop`, runs the given function, and stops the loop.\n\n The function must return either an awaitable object or\n ``None``. If the function returns an awaitable object, the\n `IOLoop` will run until the awaitable is resolved (and\n `run_sync()` will return the awaitable's r...
Please provide a description of the function:def add_timeout( self, deadline: Union[float, datetime.timedelta], callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: if isinstance(deadline, numbers.Real): return self.call_at(deadli...
[ "Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n Returns an opaque handle that may be passed to\n `remove_timeout` to cancel.\n\n ``deadline`` may be a number denoting a time (on the same\n scale as `IOLoop.time`, normally `time.time`), or a\n `datetime.timed...
Please provide a description of the function:def call_later( self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: return self.call_at(self.time() + delay, callback, *args, **kwargs)
[ "Runs the ``callback`` after ``delay`` seconds have passed.\n\n Returns an opaque handle that may be passed to `remove_timeout`\n to cancel. Note that unlike the `asyncio` method of the same\n name, the returned object does not have a ``cancel()`` method.\n\n See `add_timeout` for comme...
Please provide a description of the function:def call_at( self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: return self.add_timeout(when, callback, *args, **kwargs)
[ "Runs the ``callback`` at the absolute time designated by ``when``.\n\n ``when`` must be a number using the same reference point as\n `IOLoop.time`.\n\n Returns an opaque handle that may be passed to `remove_timeout`\n to cancel. Note that unlike the `asyncio` method of the same\n ...
Please provide a description of the function:def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None: self.add_callback(callback, *args, **kwargs)
[ "Calls the given callback on the next IOLoop iteration.\n\n As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n .. versionadded:: 4.0\n " ]
Please provide a description of the function:def add_future( self, future: "Union[Future[_T], concurrent.futures.Future[_T]]", callback: Callable[["Future[_T]"], None], ) -> None: if isinstance(future, Future): # Note that we specifically do not want the inline b...
[ "Schedules a callback on the ``IOLoop`` when the given\n `.Future` is finished.\n\n The callback is invoked with one argument, the\n `.Future`.\n\n This method only accepts `.Future` objects and not other\n awaitables (unlike most of Tornado where the two are\n interchangea...
Please provide a description of the function:def run_in_executor( self, executor: Optional[concurrent.futures.Executor], func: Callable[..., _T], *args: Any ) -> Awaitable[_T]: if executor is None: if not hasattr(self, "_executor"): from t...
[ "Runs a function in a ``concurrent.futures.Executor``. If\n ``executor`` is ``None``, the IO loop's default executor will be used.\n\n Use `functools.partial` to pass keyword arguments to ``func``.\n\n .. versionadded:: 5.0\n " ]
Please provide a description of the function:def _run_callback(self, callback: Callable[[], Any]) -> None: try: ret = callback() if ret is not None: from tornado import gen # Functions that return Futures typically swallow all # e...
[ "Runs a callback with error handling.\n\n .. versionchanged:: 6.0\n\n CancelledErrors are no longer logged.\n " ]
Please provide a description of the function:def start(self) -> None: # Looking up the IOLoop here allows to first instantiate the # PeriodicCallback in another thread, then start it using # IOLoop.add_callback(). self.io_loop = IOLoop.current() self._running = True ...
[ "Starts the timer." ]
Please provide a description of the function:def stop(self) -> None: self._running = False if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = None
[ "Stops the timer." ]
Please provide a description of the function:def url_concat( url: str, args: Union[ None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...] ], ) -> str: if args is None: return url parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = ...
[ "Concatenate url and arguments regardless of whether\n url has existing query parameters.\n\n ``args`` may be either a dictionary or a list of key-value pairs\n (the latter allows for multiple values with the same key.\n\n >>> url_concat(\"http://example.com/foo\", dict(c=\"d\"))\n 'http://example.co...
Please provide a description of the function:def _parse_request_range( range_header: str ) -> Optional[Tuple[Optional[int], Optional[int]]]: unit, _, value = range_header.partition("=") unit, value = unit.strip(), value.strip() if unit != "bytes": return None start_b, _, end_b = value.p...
[ "Parses a Range header.\n\n Returns either ``None`` or tuple ``(start, end)``.\n Note that while the HTTP headers use inclusive byte positions,\n this method returns indexes suitable for use in slices.\n\n >>> start, end = _parse_request_range(\"bytes=1-2\")\n >>> start, end\n (1, 3)\n >>> [0, ...
Please provide a description of the function:def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: start = start or 0 end = (end or total) - 1 return "bytes %s-%s/%s" % (start, end, total)
[ "Returns a suitable Content-Range header:\n\n >>> print(_get_content_range(None, 1, 4))\n bytes 0-0/4\n >>> print(_get_content_range(1, 3, 4))\n bytes 1-2/4\n >>> print(_get_content_range(None, None, 4))\n bytes 0-3/4\n " ]
Please provide a description of the function:def parse_body_arguments( content_type: str, body: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], headers: HTTPHeaders = None, ) -> None: if content_type.startswith("application/x-www-form-urlencoded"): if hea...
[ "Parses a form request body.\n\n Supports ``application/x-www-form-urlencoded`` and\n ``multipart/form-data``. The ``content_type`` parameter should be\n a string and ``body`` should be a byte string. The ``arguments``\n and ``files`` parameters are dictionaries that will be updated\n with the pars...
Please provide a description of the function:def parse_multipart_form_data( boundary: bytes, data: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], ) -> None: # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at le...
[ "Parses a ``multipart/form-data`` body.\n\n The ``boundary`` and ``data`` parameters are both byte strings.\n The dictionaries given in the arguments and files parameters\n will be updated with the contents of the body.\n\n .. versionchanged:: 5.1\n\n Now recognizes non-ASCII filenames in RFC 2231...
Please provide a description of the function:def format_timestamp( ts: Union[int, float, tuple, time.struct_time, datetime.datetime] ) -> str: if isinstance(ts, (int, float)): time_num = ts elif isinstance(ts, (tuple, time.struct_time)): time_num = calendar.timegm(ts) elif isinstanc...
[ "Formats a timestamp in the format used by HTTP.\n\n The argument may be a numeric timestamp as returned by `time.time`,\n a time tuple as returned by `time.gmtime`, or a `datetime.datetime`\n object.\n\n >>> format_timestamp(1359312200)\n 'Sun, 27 Jan 2013 18:43:20 GMT'\n " ]
Please provide a description of the function:def parse_request_start_line(line: str) -> RequestStartLine: try: method, path, version = line.split(" ") except ValueError: # https://tools.ietf.org/html/rfc7230#section-3.1.1 # invalid request-line SHOULD respond with a 400 (Bad Request...
[ "Returns a (method, path, version) tuple for an HTTP 1.x request line.\n\n The response is a `collections.namedtuple`.\n\n >>> parse_request_start_line(\"GET /foo HTTP/1.1\")\n RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')\n " ]
Please provide a description of the function:def parse_response_start_line(line: str) -> ResponseStartLine: line = native_str(line) match = re.match("(HTTP/1.[0-9]) ([0-9]+) ([^\r]*)", line) if not match: raise HTTPInputError("Error parsing response start line") return ResponseStartLine(mat...
[ "Returns a (version, code, reason) tuple for an HTTP 1.x response line.\n\n The response is a `collections.namedtuple`.\n\n >>> parse_response_start_line(\"HTTP/1.1 200 OK\")\n ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')\n " ]
Please provide a description of the function:def _parse_header(line: str) -> Tuple[str, Dict[str, str]]: r parts = _parseparam(";" + line) key = next(parts) # decode_params treats first argument special, but we already stripped key params = [("Dummy", "value")] for p in parts: i = p.find...
[ "Parse a Content-type like header.\n\n Return the main content-type and a dictionary of options.\n\n >>> d = \"form-data; foo=\\\"b\\\\\\\\a\\\\\\\"r\\\"; file*=utf-8''T%C3%A4st\"\n >>> ct, d = _parse_header(d)\n >>> ct\n 'form-data'\n >>> d['file'] == r'T\\u00e4st'.encode('ascii').decode('unicode...
Please provide a description of the function:def _encode_header(key: str, pdict: Dict[str, str]) -> str: if not pdict: return key out = [key] # Sort the parameters just to make it easy to test. for k, v in sorted(pdict.items()): if v is None: out.append(k) else: ...
[ "Inverse of _parse_header.\n\n >>> _encode_header('permessage-deflate',\n ... {'client_max_window_bits': 15, 'client_no_context_takeover': None})\n 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'\n " ]
Please provide a description of the function:def encode_username_password( username: Union[str, bytes], password: Union[str, bytes] ) -> bytes: if isinstance(username, unicode_type): username = unicodedata.normalize("NFC", username) if isinstance(password, unicode_type): password = unic...
[ "Encodes a username/password pair in the format used by HTTP auth.\n\n The return value is a byte string in the form ``username:password``.\n\n .. versionadded:: 5.1\n " ]
Please provide a description of the function:def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]: match = re.match(r"^(.+):(\d+)$", netloc) if match: host = match.group(1) port = int(match.group(2)) # type: Optional[int] else: host = netloc port = None ...
[ "Returns ``(host, port)`` tuple from ``netloc``.\n\n Returned ``port`` will be ``None`` if not present.\n\n .. versionadded:: 4.1\n " ]
Please provide a description of the function:def qs_to_qsl(qs: Dict[str, List[AnyStr]]) -> Iterable[Tuple[str, AnyStr]]: for k, vs in qs.items(): for v in vs: yield (k, v)
[ "Generator converting a result of ``parse_qs`` back to name-value pairs.\n\n .. versionadded:: 5.0\n " ]
Please provide a description of the function:def _unquote_cookie(s: str) -> str: # If there aren't any doublequotes, # then there can't be any special characters. See RFC 2109. if s is None or len(s) < 2: return s if s[0] != '"' or s[-1] != '"': return s # We have to assume th...
[ "Handle double quotes and escaping in cookie values.\n\n This method is copied verbatim from the Python 3.5 standard\n library (http.cookies._unquote) so we don't have to depend on\n non-public interfaces.\n " ]
Please provide a description of the function:def parse_cookie(cookie: str) -> Dict[str, str]: cookiedict = {} for chunk in cookie.split(str(";")): if str("=") in chunk: key, val = chunk.split(str("="), 1) else: # Assume an empty name per # https://bugzill...
[ "Parse a ``Cookie`` HTTP header into a dict of name/value pairs.\n\n This function attempts to mimic browser cookie parsing behavior;\n it specifically does not follow any of the cookie-related RFCs\n (because browsers don't either).\n\n The algorithm used is identical to that used by Django version 1.9...
Please provide a description of the function:def add(self, name: str, value: str) -> None: norm_name = _normalized_headers[name] self._last_key = norm_name if norm_name in self: self._dict[norm_name] = ( native_str(self[norm_name]) + "," + native_str(value) ...
[ "Adds a new value for the given key." ]
Please provide a description of the function:def get_list(self, name: str) -> List[str]: norm_name = _normalized_headers[name] return self._as_list.get(norm_name, [])
[ "Returns all values for the given header as a list." ]
Please provide a description of the function:def get_all(self) -> Iterable[Tuple[str, str]]: for name, values in self._as_list.items(): for value in values: yield (name, value)
[ "Returns an iterable of all (name, value) pairs.\n\n If a header has multiple values, multiple pairs will be\n returned with the same name.\n " ]
Please provide a description of the function:def parse_line(self, line: str) -> None: if line[0].isspace(): # continuation of a multi-line header if self._last_key is None: raise HTTPInputError("first header line cannot start with whitespace") new_par...
[ "Updates the dictionary with a single header line.\n\n >>> h = HTTPHeaders()\n >>> h.parse_line(\"Content-Type: text/html\")\n >>> h.get('content-type')\n 'text/html'\n " ]
Please provide a description of the function:def parse(cls, headers: str) -> "HTTPHeaders": h = cls() for line in _CRLF_RE.split(headers): if line: h.parse_line(line) return h
[ "Returns a dictionary from HTTP header text.\n\n >>> h = HTTPHeaders.parse(\"Content-Type: text/html\\\\r\\\\nContent-Length: 42\\\\r\\\\n\")\n >>> sorted(h.items())\n [('Content-Length', '42'), ('Content-Type', 'text/html')]\n\n .. versionchanged:: 5.1\n\n Raises `HTTPInputErr...
Please provide a description of the function:def cookies(self) -> Dict[str, http.cookies.Morsel]: if not hasattr(self, "_cookies"): self._cookies = http.cookies.SimpleCookie() if "Cookie" in self.headers: try: parsed = parse_cookie(self.header...
[ "A dictionary of ``http.cookies.Morsel`` objects." ]
Please provide a description of the function:def request_time(self) -> float: if self._finish_time is None: return time.time() - self._start_time else: return self._finish_time - self._start_time
[ "Returns the amount of time it took for this request to execute." ]
Please provide a description of the function:def get_ssl_certificate( self, binary_form: bool = False ) -> Union[None, Dict, bytes]: try: if self.connection is None: return None # TODO: add a method to HTTPConnection for this so it can work with HTTP/...
[ "Returns the client's SSL certificate, if any.\n\n To use client certificates, the HTTPServer's\n `ssl.SSLContext.verify_mode` field must be set, e.g.::\n\n ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n ssl_ctx.load_cert_chain(\"foo.crt\", \"foo.key\")\n ...
Please provide a description of the function:def bind_sockets( port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = _DEFAULT_BACKLOG, flags: int = None, reuse_port: bool = False, ) -> List[socket.socket]: if reuse_port and not hasattr(socket, "...
[ "Creates listening sockets bound to the given port and address.\n\n Returns a list of socket objects (multiple sockets are returned if\n the given address maps to multiple IP addresses, which is most common\n for mixed IPv4 and IPv6 use).\n\n Address may be either an IP address or hostname. If it's a h...
Please provide a description of the function:def add_accept_handler( sock: socket.socket, callback: Callable[[socket.socket, Any], None] ) -> Callable[[], None]: io_loop = IOLoop.current() removed = [False] def accept_handler(fd: socket.socket, events: int) -> None: # More connections may ...
[ "Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n When a connection is accepted, ``callback(connection, address)`` will\n be run (``connection`` is a socket object, and ``address`` is the\n address of the other end of the connection). Note that this signature\n is different fr...
Please provide a description of the function:def is_valid_ip(ip: str) -> bool: if not ip or "\x00" in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo( ip, 0, socket.AF_UNSPEC, socket...
[ "Returns ``True`` if the given string is a well-formed IP address.\n\n Supports IPv4 and IPv6.\n " ]
Please provide a description of the function:def ssl_options_to_context( ssl_options: Union[Dict[str, Any], ssl.SSLContext] ) -> ssl.SSLContext: if isinstance(ssl_options, ssl.SSLContext): return ssl_options assert isinstance(ssl_options, dict) assert all(k in _SSL_CONTEXT_KEYWORDS for k in...
[ "Try to convert an ``ssl_options`` dictionary to an\n `~ssl.SSLContext` object.\n\n The ``ssl_options`` dictionary contains keywords to be passed to\n `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can\n be used instead. This function converts the dict form to its\n `~ssl.SSLContext`...
Please provide a description of the function:def ssl_wrap_socket( socket: socket.socket, ssl_options: Union[Dict[str, Any], ssl.SSLContext], server_hostname: str = None, **kwargs: Any ) -> ssl.SSLSocket: context = ssl_options_to_context(ssl_options) if ssl.HAS_SNI: # In python 3.4, ...
[ "Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n ``ssl_options`` may be either an `ssl.SSLContext` object or a\n dictionary (as accepted by `ssl_options_to_context`). Additional\n keyword arguments are passed to ``wrap_socket`` (either the\n `~ssl.SSLContext` method or the `ssl` module func...
Please provide a description of the function:def run_on_executor(*args: Any, **kwargs: Any) -> Callable: # Fully type-checking decorators is tricky, and this one is # discouraged anyway so it doesn't have all the generic magic. def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]: ...
[ "Decorator to run a synchronous method asynchronously on an executor.\n\n The decorated method may be called with a ``callback`` keyword\n argument and returns a future.\n\n The executor to be used is determined by the ``executor``\n attributes of ``self``. To use a different attribute name, pass a\n ...
Please provide a description of the function:def chain_future(a: "Future[_T]", b: "Future[_T]") -> None: def copy(future: "Future[_T]") -> None: assert future is a if b.done(): return if hasattr(a, "exc_info") and a.exc_info() is not None: # type: ignore future...
[ "Chain two futures together so that when one completes, so does the other.\n\n The result (success or failure) of ``a`` will be copied to ``b``, unless\n ``b`` has already been completed or cancelled by the time ``a`` finishes.\n\n .. versionchanged:: 5.0\n\n Now accepts both Tornado/asyncio `Future`...
Please provide a description of the function:def future_set_exception_unless_cancelled( future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException ) -> None: if not future.cancelled(): future.set_exception(exc) else: app_log.error("Exception after Future was cancelled", exc_inf...
[ "Set the given ``exc`` as the `Future`'s exception.\n\n If the Future is already canceled, logs the exception instead. If\n this logging is not desired, the caller should explicitly check\n the state of the Future and call ``Future.set_exception`` instead of\n this wrapper.\n\n Avoids ``asyncio.Inval...
Please provide a description of the function:def future_set_exc_info( future: "Union[futures.Future[_T], Future[_T]]", exc_info: Tuple[ Optional[type], Optional[BaseException], Optional[types.TracebackType] ], ) -> None: if exc_info[1] is None: raise Exception("future_set_exc_info c...
[ "Set the given ``exc_info`` as the `Future`'s exception.\n\n Understands both `asyncio.Future` and the extensions in older\n versions of Tornado to enable better tracebacks on Python 2.\n\n .. versionadded:: 5.0\n\n .. versionchanged:: 6.0\n\n If the future is already cancelled, this function is a...
Please provide a description of the function:def future_add_done_callback( # noqa: F811 future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None] ) -> None: if future.done(): callback(future) else: future.add_done_callback(callback)
[ "Arrange to call ``callback`` when ``future`` is complete.\n\n ``callback`` is invoked with one argument, the ``future``.\n\n If ``future`` is already done, ``callback`` is invoked immediately.\n This may differ from the behavior of ``Future.add_done_callback``,\n which makes no such guarantee.\n\n ....
Please provide a description of the function:def filter_whitespace(mode: str, text: str) -> str: if mode == "all": return text elif mode == "single": text = re.sub(r"([\t ]+)", " ", text) text = re.sub(r"(\s*\n\s*)", "\n", text) return text elif mode == "oneline": ...
[ "Transform whitespace in ``text`` according to ``mode``.\n\n Available modes are:\n\n * ``all``: Return all whitespace unmodified.\n * ``single``: Collapse consecutive whitespace with a single whitespace\n character, preserving newlines.\n * ``oneline``: Collapse all runs of whitespace into a singl...
Please provide a description of the function:def generate(self, **kwargs: Any) -> bytes: namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squ...
[ "Generate this template with the given arguments." ]
Please provide a description of the function:def load(self, name: str, parent_path: str = None) -> Template: name = self.resolve_path(name, parent_path=parent_path) with self.lock: if name not in self.templates: self.templates[name] = self._create_template(name) ...
[ "Loads a template." ]
Please provide a description of the function:def coroutine( func: Callable[..., "Generator[Any, Any, _T]"] ) -> Callable[..., "Future[_T]"]: @functools.wraps(func) def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Future[_T] # This function is type-annotated with a comment to work...
[ "Decorator for asynchronous generators.\n\n For compatibility with older versions of Python, coroutines may\n also \"return\" by raising the special exception `Return(value)\n <Return>`.\n\n Functions with this decorator return a `.Future`.\n\n .. warning::\n\n When exceptions occur inside a co...
Please provide a description of the function:def multi( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": return multi_future(children, quiet_exceptions=quiet_exceptions)
[ "Runs multiple asynchronous operations in parallel.\n\n ``children`` may either be a list or a dict whose values are\n yieldable objects. ``multi()`` returns a new yieldable\n object that resolves to a parallel structure containing their\n results. If ``children`` is a list, the result is a list of\n ...
Please provide a description of the function:def multi_future( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": if isinstance(children, dict): keys = list(children.ke...
[ "Wait for multiple asynchronous futures in parallel.\n\n Since Tornado 6.0, this function is exactly the same as `multi`.\n\n .. versionadded:: 4.0\n\n .. versionchanged:: 4.2\n If multiple ``Futures`` fail, any exceptions after the first (which is\n raised) will be logged. Added the ``quiet_ex...
Please provide a description of the function:def maybe_future(x: Any) -> Future: if is_future(x): return x else: fut = _create_future() fut.set_result(x) return fut
[ "Converts ``x`` into a `.Future`.\n\n If ``x`` is already a `.Future`, it is simply returned; otherwise\n it is wrapped in a new `.Future`. This is suitable for use as\n ``result = yield gen.maybe_future(f())`` when you don't know whether\n ``f()`` returns a `.Future` or not.\n\n .. deprecated:: 4.3...
Please provide a description of the function:def with_timeout( timeout: Union[float, datetime.timedelta], future: _Yieldable, quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> Future: # It's tempting to optimize this by cancelling the input future on timeout # i...
[ "Wraps a `.Future` (or other yieldable object) in a timeout.\n\n Raises `tornado.util.TimeoutError` if the input future does not\n complete before ``timeout``, which may be specified in any form\n allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or\n an absolute time relative to `.IOLoop.ti...
Please provide a description of the function:def sleep(duration: float) -> "Future[None]": f = _create_future() IOLoop.current().call_later( duration, lambda: future_set_result_unless_cancelled(f, None) ) return f
[ "Return a `.Future` that resolves after the given number of seconds.\n\n When used with ``yield`` in a coroutine, this is a non-blocking\n analogue to `time.sleep` (which should not be used in coroutines\n because it is blocking)::\n\n yield gen.sleep(0.5)\n\n Note that calling this function on i...
Please provide a description of the function:def convert_yielded(yielded: _Yieldable) -> Future: if yielded is None or yielded is moment: return moment elif yielded is _null_future: return _null_future elif isinstance(yielded, (list, dict)): return multi(yielded) # type: ignore...
[ "Convert a yielded object into a `.Future`.\n\n The default implementation accepts lists, dictionaries, and\n Futures. This has the side effect of starting any coroutines that\n did not start themselves, similar to `asyncio.ensure_future`.\n\n If the `~functools.singledispatch` library is available, thi...
Please provide a description of the function:def next(self) -> Future: self._running_future = Future() if self._finished: self._return_result(self._finished.popleft()) return self._running_future
[ "Returns a `.Future` that will yield the next available result.\n\n Note that this `.Future` will not be the same object as any of\n the inputs.\n " ]
Please provide a description of the function:def run(self) -> None: if self.running or self.finished: return try: self.running = True while True: future = self.future if future is None: raise Exception("No p...
[ "Starts or resumes the generator, running until it reaches a\n yield point that is not ready.\n " ]
Please provide a description of the function:def append(self, data: Union[bytes, bytearray, memoryview]) -> None: size = len(data) if size > self._large_buf_threshold: if not isinstance(data, memoryview): data = memoryview(data) self._buffers.append((True...
[ "\n Append the given piece of data (should be a buffer-compatible object).\n " ]
Please provide a description of the function:def peek(self, size: int) -> memoryview: assert size > 0 try: is_memview, b = self._buffers[0] except IndexError: return memoryview(b"") pos = self._first_pos if is_memview: return typing.c...
[ "\n Get a view over at most ``size`` bytes (possibly fewer) at the\n current buffer position.\n " ]
Please provide a description of the function:def advance(self, size: int) -> None: assert 0 < size <= self._size self._size -= size pos = self._first_pos buffers = self._buffers while buffers and size > 0: is_large, b = buffers[0] b_remain = len(...
[ "\n Advance the current buffer position by ``size`` bytes.\n " ]
Please provide a description of the function:def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]: future = self._start_read() self._read_regex = re.compile(regex) self._read_max_bytes = max_bytes try: self._try_inline_read() ex...
[ "Asynchronously read until we have matched the given regex.\n\n The result includes the data that matches the regex and anything\n that came before it.\n\n If ``max_bytes`` is not None, the connection will be closed\n if more than ``max_bytes`` bytes have been read and the regex is\n ...
Please provide a description of the function:def read_until(self, delimiter: bytes, max_bytes: int = None) -> Awaitable[bytes]: future = self._start_read() self._read_delimiter = delimiter self._read_max_bytes = max_bytes try: self._try_inline_read() except U...
[ "Asynchronously read until we have found the given delimiter.\n\n The result includes all the data read including the delimiter.\n\n If ``max_bytes`` is not None, the connection will be closed\n if more than ``max_bytes`` bytes have been read and the delimiter\n is not found.\n\n ...
Please provide a description of the function:def read_bytes(self, num_bytes: int, partial: bool = False) -> Awaitable[bytes]: future = self._start_read() assert isinstance(num_bytes, numbers.Integral) self._read_bytes = num_bytes self._read_partial = partial try: ...
[ "Asynchronously read a number of bytes.\n\n If ``partial`` is true, data is returned as soon as we have\n any bytes to return (but never more than ``num_bytes``)\n\n .. versionchanged:: 4.0\n Added the ``partial`` argument. The callback argument is now\n optional and a `....
Please provide a description of the function:def read_into(self, buf: bytearray, partial: bool = False) -> Awaitable[int]: future = self._start_read() # First copy data already in read buffer available_bytes = self._read_buffer_size n = len(buf) if available_bytes >= n:...
[ "Asynchronously read a number of bytes.\n\n ``buf`` must be a writable buffer into which data will be read.\n\n If ``partial`` is true, the callback is run as soon as any bytes\n have been read. Otherwise, it is run when the ``buf`` has been\n entirely filled with read data.\n\n ...
Please provide a description of the function:def read_until_close(self) -> Awaitable[bytes]: future = self._start_read() if self.closed(): self._finish_read(self._read_buffer_size, False) return future self._read_until_close = True try: self._...
[ "Asynchronously reads all data from the socket until it is closed.\n\n This will buffer all available data until ``max_buffer_size``\n is reached. If flow control or cancellation are desired, use a\n loop with `read_bytes(partial=True) <.read_bytes>` instead.\n\n .. versionchanged:: 4.0\...
Please provide a description of the function:def write(self, data: Union[bytes, memoryview]) -> "Future[None]": self._check_closed() if data: if ( self.max_write_buffer_size is not None and len(self._write_buffer) + len(data) > self.max_write_buffer_s...
[ "Asynchronously write the given data to this stream.\n\n This method returns a `.Future` that resolves (with a result\n of ``None``) when the write has been completed.\n\n The ``data`` argument may be of type `bytes` or `memoryview`.\n\n .. versionchanged:: 4.0\n Now returns a...
Please provide a description of the function:def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None: self._close_callback = callback self._maybe_add_error_listener()
[ "Call the given callback when the stream is closed.\n\n This mostly is not necessary for applications that use the\n `.Future` interface; all outstanding ``Futures`` will resolve\n with a `StreamClosedError` when the stream is closed. However,\n it is still useful as a way to signal that...
Please provide a description of the function:def close( self, exc_info: Union[ None, bool, BaseException, Tuple[ "Optional[Type[BaseException]]", Optional[BaseException], Optional[TracebackType], ...
[ "Close this stream.\n\n If ``exc_info`` is true, set the ``error`` attribute to the current\n exception from `sys.exc_info` (or if ``exc_info`` is a tuple,\n use that instead of `sys.exc_info`).\n " ]
Please provide a description of the function:def _try_inline_read(self) -> None: # See if we've already got the data from a previous read pos = self._find_read_pos() if pos is not None: self._read_from_buffer(pos) return self._check_closed() pos =...
[ "Attempt to complete the current read operation from buffered data.\n\n If the read can be completed without blocking, schedules the\n read callback on the next IOLoop iteration; otherwise starts\n listening for reads on the socket.\n " ]
Please provide a description of the function:def _read_to_buffer(self) -> Optional[int]: try: while True: try: if self._user_read_buffer: buf = memoryview(self._read_buffer)[ self._read_buffer_size : ...
[ "Reads from the socket and appends the result to the read buffer.\n\n Returns the number of bytes read. Returns 0 if there is nothing\n to read (i.e. the read returns EWOULDBLOCK or equivalent). On\n error closes the socket and raises an exception.\n " ]
Please provide a description of the function: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.\n\n The argument is either a position in the read buffer or None,\n as returned by _find_read_pos.\n " ]
Please provide a description of the function: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...
[ "Attempts to find a position in the read buffer that satisfies\n the currently-pending read.\n\n Returns a position in the buffer if the current read can be satisfied,\n or None if it cannot.\n " ]
Please provide a description of the function:def _add_io_state(self, state: int) -> None: if self.closed(): # connection has been closed, so there can be no future events return if self._state is None: self._state = ioloop.IOLoop.ERROR | state sel...
[ "Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler.\n\n Implementation notes: Reads and writes have a fast path and a\n slow path. The fast path reads synchronously from socket\n buffers, while the slow path uses `_add_io_state` to schedule\n an IOLoop callback.\n\n T...
Please provide a description of the function: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.\n\n May be overridden in subclasses.\n " ]
Please provide a description of the function: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[IOStre...
[ "Connects the socket to a remote address without blocking.\n\n May only be called if the socket passed to the constructor was\n not previously connected. The address parameter is in the\n same format as for `socket.connect <socket.socket.connect>` for\n the type of socket passed to the ...
Please provide a description of the function: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_f...
[ "Convert this `IOStream` to an `SSLIOStream`.\n\n This enables protocols that begin in clear-text mode and\n switch to SSL after some initial negotiation (such as the\n ``STARTTLS`` extension to SMTP and IMAP).\n\n This method cannot be used if there are outstanding reads\n or wri...
Please provide a description of the function: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...
[ "Returns ``True`` if peercert is valid according to the configured\n validation mode and hostname.\n\n The ssl handshake already tested the certificate for a valid\n CA signature; the only thing that remains is to check\n the hostname.\n " ]
Please provide a description of the function: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._finis...
[ "Wait for the initial SSL handshake to complete.\n\n If a ``callback`` is given, it will be called with no\n arguments once the handshake is complete; otherwise this\n method returns a `.Future` which will resolve to the\n stream itself after the handshake is complete.\n\n Once th...
Please provide a description of the function: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 ...
[ "Turns on formatted logging output as configured.\n\n This is called automatically by `tornado.options.parse_command_line`\n and `tornado.options.parse_config_file`.\n " ]
Please provide a description of the function: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=...
[ "Add logging-related flags to ``options``.\n\n These options are present automatically on the default options instance;\n this method is only necessary if you have created your own `.OptionParser`.\n\n .. versionadded:: 4.2\n This function existed in prior versions but was broken and undocumented un...
Please provide a description of the function: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 = ...
[ "Creates a AsyncHTTPClient.\n\n Only a single AsyncHTTPClient instance exists per IOLoop\n in order to provide limitations on the number of pending connections.\n ``force_instance=True`` may be used to suppress this behavior.\n\n Note that because of this implicit reuse, unless ``force_i...
Please provide a description of the function: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...
[ "Timeout callback of request.\n\n Construct a timeout HTTPResponse when a timeout occurs.\n\n :arg object key: A simple object to mark the request.\n :info string key: More detailed timeout information.\n " ]
Please provide a description of the function: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, ...
[ "Timeout callback of _HTTPConnection instance.\n\n Raise a `HTTPTimeoutError` when a timeout occurs.\n\n :info string key: More detailed timeout information.\n " ]
Please provide a description of the function: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 ...
[ "Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.\n\n See http://oauth.net/core/1.0a/#signing_process\n " ]
Please provide a description of the function: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...
[ "Redirects to the authentication URL for this service.\n\n After authentication, the service will redirect back to the given\n callback URI with additional parameters including ``openid.mode``.\n\n We request the given attributes for the authenticated user by\n default (name, email, lang...
Please provide a description of the function:async def get_authenticated_user( self, http_client: httpclient.AsyncHTTPClient = None ) -> Dict[str, Any]: handler = cast(RequestHandler, self) # Verify the OpenID response via direct request to the OP args = dict( (k...
[ "Fetches the authenticated user data upon redirect.\n\n This method should be called by the handler that receives the\n redirect from the `authenticate_redirect()` method (which is\n often the same as the one that calls it; in that case you would\n call `get_authenticated_user` if the ``...
Please provide a description of the function:async def authorize_redirect( self, callback_uri: str = None, extra_params: Dict[str, Any] = None, http_client: httpclient.AsyncHTTPClient = None, ) -> None: if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False):...
[ "Redirects the user to obtain OAuth authorization for this service.\n\n The ``callback_uri`` may be omitted if you have previously\n registered a callback URI with the third-party service. For\n some services, you must use a previously-registered callback\n URI and cannot specify a callb...
Please provide a description of the function: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 = handl...
[ "Gets the OAuth authorized user and access token.\n\n This method should be called from the handler for your\n OAuth callback URL to complete the registration process. We run the\n callback with the authenticated user dictionary. This dictionary\n will contain an ``access_key`` which ca...
Please provide a description of the function: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\n user.\n\n Should be a coroutine whose result is a dictionary\n containing information about the user, which may have been\n retrieved by using ``access_token`` to make a request to the\n service.\n\n The ac...
Please provide a description of the function:def authorize_redirect( self, redirect_uri: str = None, client_id: str = None, client_secret: str = None, extra_params: Dict[str, Any] = None, scope: str = None, response_type: str = "code", ) -> None: ...
[ "Redirects the user to obtain OAuth authorization for this service.\n\n Some providers require that you register a redirect URL with\n your application instead of passing one via this method. You\n should call this method to log the user in, and then call\n ``get_authenticated_user`` in ...
Please provide a description of the function: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...
[ "Fetches the given URL auth an OAuth2 access token.\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n Example usage:\n\n ..testcode::\n\n class MainHandler(tornado.web.RequestHandler,\n ...
Please provide a description of the function: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(sel...
[ "Just like `~OAuthMixin.authorize_redirect`, but\n auto-redirects if authorized.\n\n This is generally the right interface to use if you are using\n Twitter for single-sign on.\n\n .. versionchanged:: 3.1\n Now returns a `.Future` and takes an optional callback, for\n ...
Please provide a description of the function:async def twitter_request( self, path: str, access_token: Dict[str, Any], post_args: Dict[str, Any] = None, **args: Any ) -> Any: if path.startswith("http:") or path.startswith("https:"): # Raw urls are...
[ "Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n The path should not include the format or API version number.\n (we automatically use JSON format and API version 1).\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should ...
Please provide a description of the function: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( { ...
[ "Handles the login for the Google user, returning an access token.\n\n The result is a dictionary containing an ``access_token`` field\n ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n Unlike other ``get_authenticated_user`` methods in t...
Please provide a description of the function: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...
[ "Handles the login for the Facebook user, returning a user object.\n\n Example usage:\n\n .. testcode::\n\n class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n tornado.auth.FacebookGraphMixin):\n async def get(self):\n ...
Please provide a description of the function:async def facebook_request( self, path: str, access_token: str = None, post_args: Dict[str, Any] = None, **args: Any ) -> Any: url = self._FACEBOOK_BASE_URL + path return await self.oauth2_request( ...
[ "Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n If the request is a POST, ``post_args`` should be provided. Query\n string arguments should be given as keyword arguments.\n\n An introduction to the Facebook Graph API can be found at\n http://developers.facebook.com/d...
Please provide a description of the function: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():...
[ "Wait for `.notify`.\n\n Returns a `.Future` that resolves ``True`` if the condition is notified,\n or ``False`` after a timeout.\n " ]
Please provide a description of the function: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 ...
[ "Wake ``n`` waiters." ]