repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tornadoweb/tornado | tornado/web.py | RequestHandler.xsrf_token | def xsrf_token(self) -> bytes:
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
... | python | def xsrf_token(self) -> bytes:
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
... | [
"def",
"xsrf_token",
"(",
"self",
")",
"->",
"bytes",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_xsrf_token\"",
")",
":",
"version",
",",
"token",
",",
"timestamp",
"=",
"self",
".",
"_get_raw_xsrf_token",
"(",
")",
"output_version",
"=",
"self",
... | The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See h... | [
"The",
"XSRF",
"-",
"prevention",
"token",
"for",
"the",
"current",
"user",
"/",
"session",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1368-L1422 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler._get_raw_xsrf_token | def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
"""Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.... | python | def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
"""Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.... | [
"def",
"_get_raw_xsrf_token",
"(",
"self",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"int",
"]",
",",
"bytes",
",",
"float",
"]",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_raw_xsrf_token\"",
")",
":",
"cookie",
"=",
"self",
".",
"get_cookie",
... | Read or generate the xsrf token in its raw form.
The raw_xsrf_token is a tuple containing:
* version: the version of the cookie from which this token was read,
or None if we generated a new token in this request.
* token: the raw token data; random (non-ascii) bytes.
* timest... | [
"Read",
"or",
"generate",
"the",
"xsrf",
"token",
"in",
"its",
"raw",
"form",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1424-L1448 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler._decode_xsrf_token | def _decode_xsrf_token(
self, cookie: str
) -> Tuple[Optional[int], Optional[bytes], Optional[float]]:
"""Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token.
"""
try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
... | python | def _decode_xsrf_token(
self, cookie: str
) -> Tuple[Optional[int], Optional[bytes], Optional[float]]:
"""Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token.
"""
try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
... | [
"def",
"_decode_xsrf_token",
"(",
"self",
",",
"cookie",
":",
"str",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"int",
"]",
",",
"Optional",
"[",
"bytes",
"]",
",",
"Optional",
"[",
"float",
"]",
"]",
":",
"try",
":",
"m",
"=",
"_signed_value_version_re... | Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token. | [
"Convert",
"a",
"cookie",
"string",
"into",
"a",
"the",
"tuple",
"form",
"returned",
"by",
"_get_raw_xsrf_token",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1450-L1484 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.check_xsrf_cookie | def check_xsrf_cookie(self) -> None:
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
r... | python | def check_xsrf_cookie(self) -> None:
"""Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
r... | [
"def",
"check_xsrf_cookie",
"(",
"self",
")",
"->",
"None",
":",
"# Prior to release 1.1.1, this check was ignored if the HTTP header",
"# ``X-Requested-With: XMLHTTPRequest`` was present. This exception",
"# has been shown to be insecure and has been removed. For more",
"# information pleas... | Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.
To prevent cross-site request forgery, we set an ``_xsrf``
cookie and include the same value as a non-cookie
field with all ``POST`` requests. If the two do not match, we
reject the form submission as a potential forgery... | [
"Verifies",
"that",
"the",
"_xsrf",
"cookie",
"matches",
"the",
"_xsrf",
"argument",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1486-L1522 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.static_url | def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str:
"""Returns a static URL for the given relative static file path.
This method requires you set the ``static_path`` setting in your
application (which specifies the root directory of your static
files).
... | python | def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str:
"""Returns a static URL for the given relative static file path.
This method requires you set the ``static_path`` setting in your
application (which specifies the root directory of your static
files).
... | [
"def",
"static_url",
"(",
"self",
",",
"path",
":",
"str",
",",
"include_host",
":",
"bool",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"str",
":",
"self",
".",
"require_setting",
"(",
"\"static_path\"",
",",
"\"static_url\"",
")",
"g... | Returns a static URL for the given relative static file path.
This method requires you set the ``static_path`` setting in your
application (which specifies the root directory of your static
files).
This method returns a versioned url (by default appending
``?v=<signature>``), w... | [
"Returns",
"a",
"static",
"URL",
"for",
"the",
"given",
"relative",
"static",
"file",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1543-L1577 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.require_setting | def require_setting(self, name: str, feature: str = "this feature") -> None:
"""Raises an exception if the given app setting is not defined."""
if not self.application.settings.get(name):
raise Exception(
"You must define the '%s' setting in your "
"applicatio... | python | def require_setting(self, name: str, feature: str = "this feature") -> None:
"""Raises an exception if the given app setting is not defined."""
if not self.application.settings.get(name):
raise Exception(
"You must define the '%s' setting in your "
"applicatio... | [
"def",
"require_setting",
"(",
"self",
",",
"name",
":",
"str",
",",
"feature",
":",
"str",
"=",
"\"this feature\"",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"application",
".",
"settings",
".",
"get",
"(",
"name",
")",
":",
"raise",
"Exceptio... | Raises an exception if the given app setting is not defined. | [
"Raises",
"an",
"exception",
"if",
"the",
"given",
"app",
"setting",
"is",
"not",
"defined",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1579-L1585 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.reverse_url | def reverse_url(self, name: str, *args: Any) -> str:
"""Alias for `Application.reverse_url`."""
return self.application.reverse_url(name, *args) | python | def reverse_url(self, name: str, *args: Any) -> str:
"""Alias for `Application.reverse_url`."""
return self.application.reverse_url(name, *args) | [
"def",
"reverse_url",
"(",
"self",
",",
"name",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"str",
":",
"return",
"self",
".",
"application",
".",
"reverse_url",
"(",
"name",
",",
"*",
"args",
")"
] | Alias for `Application.reverse_url`. | [
"Alias",
"for",
"Application",
".",
"reverse_url",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1587-L1589 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.compute_etag | def compute_etag(self) -> Optional[str]:
"""Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado's default etag support.
"""
... | python | def compute_etag(self) -> Optional[str]:
"""Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado's default etag support.
"""
... | [
"def",
"compute_etag",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"part",
"in",
"self",
".",
"_write_buffer",
":",
"hasher",
".",
"update",
"(",
"part",
")",
"return",
"'\"%s\"'",
... | Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado's default etag support. | [
"Computes",
"the",
"etag",
"header",
"to",
"be",
"used",
"for",
"this",
"request",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1591-L1602 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.check_etag_header | def check_etag_header(self) -> bool:
"""Checks the ``Etag`` header against requests's ``If-None-Match``.
Returns ``True`` if the request's Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.s... | python | def check_etag_header(self) -> bool:
"""Checks the ``Etag`` header against requests's ``If-None-Match``.
Returns ``True`` if the request's Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.s... | [
"def",
"check_etag_header",
"(",
"self",
")",
"->",
"bool",
":",
"computed_etag",
"=",
"utf8",
"(",
"self",
".",
"_headers",
".",
"get",
"(",
"\"Etag\"",
",",
"\"\"",
")",
")",
"# Find all weak and strong etag values from If-None-Match header",
"# because RFC 7232 all... | Checks the ``Etag`` header against requests's ``If-None-Match``.
Returns ``True`` if the request's Etag matches and a 304 should be
returned. For example::
self.set_etag_header()
if self.check_etag_header():
self.set_status(304)
return
T... | [
"Checks",
"the",
"Etag",
"header",
"against",
"requests",
"s",
"If",
"-",
"None",
"-",
"Match",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1615-L1653 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler._execute | async def _execute(
self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes
) -> None:
"""Executes this request with the given output transforms."""
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
r... | python | async def _execute(
self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes
) -> None:
"""Executes this request with the given output transforms."""
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
r... | [
"async",
"def",
"_execute",
"(",
"self",
",",
"transforms",
":",
"List",
"[",
"\"OutputTransform\"",
"]",
",",
"*",
"args",
":",
"bytes",
",",
"*",
"*",
"kwargs",
":",
"bytes",
")",
"->",
"None",
":",
"self",
".",
"_transforms",
"=",
"transforms",
"try... | Executes this request with the given output transforms. | [
"Executes",
"this",
"request",
"with",
"the",
"given",
"output",
"transforms",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1655-L1714 | train |
tornadoweb/tornado | tornado/web.py | RequestHandler.log_exception | def log_exception(
self,
typ: "Optional[Type[BaseException]]",
value: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack ... | python | def log_exception(
self,
typ: "Optional[Type[BaseException]]",
value: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
"""Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack ... | [
"def",
"log_exception",
"(",
"self",
",",
"typ",
":",
"\"Optional[Type[BaseException]]\"",
",",
"value",
":",
"Optional",
"[",
"BaseException",
"]",
",",
"tb",
":",
"Optional",
"[",
"TracebackType",
"]",
",",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
... | Override to customize logging of uncaught exceptions.
By default logs instances of `HTTPError` as warnings without
stack traces (on the ``tornado.general`` logger), and all
other exceptions as errors with stack traces (on the
``tornado.application`` logger).
.. versionadded:: 3... | [
"Override",
"to",
"customize",
"logging",
"of",
"uncaught",
"exceptions",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1763-L1789 | train |
tornadoweb/tornado | tornado/web.py | Application.listen | def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer:
"""Starts an HTTP server for this application on the given port.
This is a convenience alias for creating an `.HTTPServer`
object and calling its listen method. Keyword arguments not
supported by `HTTPServer.l... | python | def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer:
"""Starts an HTTP server for this application on the given port.
This is a convenience alias for creating an `.HTTPServer`
object and calling its listen method. Keyword arguments not
supported by `HTTPServer.l... | [
"def",
"listen",
"(",
"self",
",",
"port",
":",
"int",
",",
"address",
":",
"str",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"HTTPServer",
":",
"server",
"=",
"HTTPServer",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"server",
"... | Starts an HTTP server for this application on the given port.
This is a convenience alias for creating an `.HTTPServer`
object and calling its listen method. Keyword arguments not
supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the
`.HTTPServer` constructor. For adv... | [
"Starts",
"an",
"HTTP",
"server",
"for",
"this",
"application",
"on",
"the",
"given",
"port",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2092-L2113 | train |
tornadoweb/tornado | tornado/web.py | Application.add_handlers | def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None:
"""Appends the given handlers to our handler list.
Host patterns are processed sequentially in the order they were
added. All matching patterns will be considered.
"""
host_matcher = HostMatches(host_pa... | python | def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None:
"""Appends the given handlers to our handler list.
Host patterns are processed sequentially in the order they were
added. All matching patterns will be considered.
"""
host_matcher = HostMatches(host_pa... | [
"def",
"add_handlers",
"(",
"self",
",",
"host_pattern",
":",
"str",
",",
"host_handlers",
":",
"_RuleList",
")",
"->",
"None",
":",
"host_matcher",
"=",
"HostMatches",
"(",
"host_pattern",
")",
"rule",
"=",
"Rule",
"(",
"host_matcher",
",",
"_ApplicationRoute... | Appends the given handlers to our handler list.
Host patterns are processed sequentially in the order they were
added. All matching patterns will be considered. | [
"Appends",
"the",
"given",
"handlers",
"to",
"our",
"handler",
"list",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2115-L2129 | train |
tornadoweb/tornado | tornado/web.py | Application.get_handler_delegate | def get_handler_delegate(
self,
request: httputil.HTTPServerRequest,
target_class: Type[RequestHandler],
target_kwargs: Dict[str, Any] = None,
path_args: List[bytes] = None,
path_kwargs: Dict[str, bytes] = None,
) -> "_HandlerDelegate":
"""Returns `~.httputil.... | python | def get_handler_delegate(
self,
request: httputil.HTTPServerRequest,
target_class: Type[RequestHandler],
target_kwargs: Dict[str, Any] = None,
path_args: List[bytes] = None,
path_kwargs: Dict[str, bytes] = None,
) -> "_HandlerDelegate":
"""Returns `~.httputil.... | [
"def",
"get_handler_delegate",
"(",
"self",
",",
"request",
":",
"httputil",
".",
"HTTPServerRequest",
",",
"target_class",
":",
"Type",
"[",
"RequestHandler",
"]",
",",
"target_kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"path_args"... | Returns `~.httputil.HTTPMessageDelegate` that can serve a request
for application and `RequestHandler` subclass.
:arg httputil.HTTPServerRequest request: current HTTP request.
:arg RequestHandler target_class: a `RequestHandler` class.
:arg dict target_kwargs: keyword arguments for ``ta... | [
"Returns",
"~",
".",
"httputil",
".",
"HTTPMessageDelegate",
"that",
"can",
"serve",
"a",
"request",
"for",
"application",
"and",
"RequestHandler",
"subclass",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2187-L2207 | train |
tornadoweb/tornado | tornado/web.py | Application.reverse_url | def reverse_url(self, name: str, *args: Any) -> str:
"""Returns a URL path for handler named ``name``
The handler must be added to the application as a named `URLSpec`.
Args will be substituted for capturing groups in the `URLSpec` regex.
They will be converted to strings if necessary,... | python | def reverse_url(self, name: str, *args: Any) -> str:
"""Returns a URL path for handler named ``name``
The handler must be added to the application as a named `URLSpec`.
Args will be substituted for capturing groups in the `URLSpec` regex.
They will be converted to strings if necessary,... | [
"def",
"reverse_url",
"(",
"self",
",",
"name",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"str",
":",
"reversed_url",
"=",
"self",
".",
"default_router",
".",
"reverse_url",
"(",
"name",
",",
"*",
"args",
")",
"if",
"reversed_url",
"is",
"... | Returns a URL path for handler named ``name``
The handler must be added to the application as a named `URLSpec`.
Args will be substituted for capturing groups in the `URLSpec` regex.
They will be converted to strings if necessary, encoded as utf8,
and url-escaped. | [
"Returns",
"a",
"URL",
"path",
"for",
"handler",
"named",
"name"
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2209-L2222 | train |
tornadoweb/tornado | tornado/web.py | Application.log_request | def log_request(self, handler: RequestHandler) -> None:
"""Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary a... | python | def log_request(self, handler: RequestHandler) -> None:
"""Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary a... | [
"def",
"log_request",
"(",
"self",
",",
"handler",
":",
"RequestHandler",
")",
"->",
"None",
":",
"if",
"\"log_function\"",
"in",
"self",
".",
"settings",
":",
"self",
".",
"settings",
"[",
"\"log_function\"",
"]",
"(",
"handler",
")",
"return",
"if",
"han... | Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
``log_function``. | [
"Writes",
"a",
"completed",
"HTTP",
"request",
"to",
"the",
"logs",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2224-L2247 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.compute_etag | def compute_etag(self) -> Optional[str]:
"""Sets the ``Etag`` header based on static url version.
This allows efficient ``If-None-Match`` checks against cached
versions, and sends the correct ``Etag`` for a partial response
(i.e. the same ``Etag`` as the full file).
.. versiona... | python | def compute_etag(self) -> Optional[str]:
"""Sets the ``Etag`` header based on static url version.
This allows efficient ``If-None-Match`` checks against cached
versions, and sends the correct ``Etag`` for a partial response
(i.e. the same ``Etag`` as the full file).
.. versiona... | [
"def",
"compute_etag",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"assert",
"self",
".",
"absolute_path",
"is",
"not",
"None",
"version_hash",
"=",
"self",
".",
"_get_cached_version",
"(",
"self",
".",
"absolute_path",
")",
"if",
"not",
"ver... | Sets the ``Etag`` header based on static url version.
This allows efficient ``If-None-Match`` checks against cached
versions, and sends the correct ``Etag`` for a partial response
(i.e. the same ``Etag`` as the full file).
.. versionadded:: 3.1 | [
"Sets",
"the",
"Etag",
"header",
"based",
"on",
"static",
"url",
"version",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2655-L2668 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.set_headers | def set_headers(self) -> None:
"""Sets the content and caching headers on the response.
.. versionadded:: 3.1
"""
self.set_header("Accept-Ranges", "bytes")
self.set_etag_header()
if self.modified is not None:
self.set_header("Last-Modified", self.modified)
... | python | def set_headers(self) -> None:
"""Sets the content and caching headers on the response.
.. versionadded:: 3.1
"""
self.set_header("Accept-Ranges", "bytes")
self.set_etag_header()
if self.modified is not None:
self.set_header("Last-Modified", self.modified)
... | [
"def",
"set_headers",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"set_header",
"(",
"\"Accept-Ranges\"",
",",
"\"bytes\"",
")",
"self",
".",
"set_etag_header",
"(",
")",
"if",
"self",
".",
"modified",
"is",
"not",
"None",
":",
"self",
".",
"set_he... | Sets the content and caching headers on the response.
.. versionadded:: 3.1 | [
"Sets",
"the",
"content",
"and",
"caching",
"headers",
"on",
"the",
"response",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2670-L2693 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.should_return_304 | def should_return_304(self) -> bool:
"""Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1
"""
# If client sent If-None-Match, use it, ignore If-Modified-Since
if self.request.headers.get("If-None-Match"):
return self.check_etag_hea... | python | def should_return_304(self) -> bool:
"""Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1
"""
# If client sent If-None-Match, use it, ignore If-Modified-Since
if self.request.headers.get("If-None-Match"):
return self.check_etag_hea... | [
"def",
"should_return_304",
"(",
"self",
")",
"->",
"bool",
":",
"# If client sent If-None-Match, use it, ignore If-Modified-Since",
"if",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-None-Match\"",
")",
":",
"return",
"self",
".",
"check_etag_header... | Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1 | [
"Returns",
"True",
"if",
"the",
"headers",
"indicate",
"that",
"we",
"should",
"return",
"304",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2695-L2715 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_absolute_path | def get_absolute_path(cls, root: str, path: str) -> str:
"""Returns the absolute location of ``path`` relative to ``root``.
``root`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
This class method may be overridden in sub... | python | def get_absolute_path(cls, root: str, path: str) -> str:
"""Returns the absolute location of ``path`` relative to ``root``.
``root`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
This class method may be overridden in sub... | [
"def",
"get_absolute_path",
"(",
"cls",
",",
"root",
":",
"str",
",",
"path",
":",
"str",
")",
"->",
"str",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"path",
")",
")",
"return",... | Returns the absolute location of ``path`` relative to ``root``.
``root`` is the path configured for this `StaticFileHandler`
(in most cases the ``static_path`` `Application` setting).
This class method may be overridden in subclasses. By default
it returns a filesystem path, but other... | [
"Returns",
"the",
"absolute",
"location",
"of",
"path",
"relative",
"to",
"root",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2718-L2732 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.validate_absolute_path | def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]:
"""Validate and return the absolute path.
``root`` is the configured path for the `StaticFileHandler`,
and ``path`` is the result of `get_absolute_path`
This is an instance method called during request pr... | python | def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]:
"""Validate and return the absolute path.
``root`` is the configured path for the `StaticFileHandler`,
and ``path`` is the result of `get_absolute_path`
This is an instance method called during request pr... | [
"def",
"validate_absolute_path",
"(",
"self",
",",
"root",
":",
"str",
",",
"absolute_path",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"# os.path.abspath strips a trailing /.",
"# We must add it back to `root` so that we only match files",
"# in a directory n... | Validate and return the absolute path.
``root`` is the configured path for the `StaticFileHandler`,
and ``path`` is the result of `get_absolute_path`
This is an instance method called during request processing,
so it may raise `HTTPError` or use methods like
`RequestHandler.red... | [
"Validate",
"and",
"return",
"the",
"absolute",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2734-L2782 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_content | def get_content(
cls, abspath: str, start: int = None, end: int = None
) -> Generator[bytes, None, None]:
"""Retrieve the content of the requested resource which is located
at the given absolute path.
This class method may be overridden by subclasses. Note that its
signatur... | python | def get_content(
cls, abspath: str, start: int = None, end: int = None
) -> Generator[bytes, None, None]:
"""Retrieve the content of the requested resource which is located
at the given absolute path.
This class method may be overridden by subclasses. Note that its
signatur... | [
"def",
"get_content",
"(",
"cls",
",",
"abspath",
":",
"str",
",",
"start",
":",
"int",
"=",
"None",
",",
"end",
":",
"int",
"=",
"None",
")",
"->",
"Generator",
"[",
"bytes",
",",
"None",
",",
"None",
"]",
":",
"with",
"open",
"(",
"abspath",
",... | Retrieve the content of the requested resource which is located
at the given absolute path.
This class method may be overridden by subclasses. Note that its
signature is different from other overridable class methods
(no ``settings`` argument); this is deliberate to ensure that
... | [
"Retrieve",
"the",
"content",
"of",
"the",
"requested",
"resource",
"which",
"is",
"located",
"at",
"the",
"given",
"absolute",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2785-L2821 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_content_version | def get_content_version(cls, abspath: str) -> str:
"""Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1
"""
data = cls.get_c... | python | def get_content_version(cls, abspath: str) -> str:
"""Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1
"""
data = cls.get_c... | [
"def",
"get_content_version",
"(",
"cls",
",",
"abspath",
":",
"str",
")",
"->",
"str",
":",
"data",
"=",
"cls",
".",
"get_content",
"(",
"abspath",
")",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
"... | Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1 | [
"Returns",
"a",
"version",
"string",
"for",
"the",
"resource",
"at",
"the",
"given",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2824-L2839 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_modified_time | def get_modified_time(self) -> Optional[datetime.datetime]:
"""Returns the time that ``self.absolute_path`` was last modified.
May be overridden in subclasses. Should return a `~datetime.datetime`
object or None.
.. versionadded:: 3.1
"""
stat_result = self._stat()
... | python | def get_modified_time(self) -> Optional[datetime.datetime]:
"""Returns the time that ``self.absolute_path`` was last modified.
May be overridden in subclasses. Should return a `~datetime.datetime`
object or None.
.. versionadded:: 3.1
"""
stat_result = self._stat()
... | [
"def",
"get_modified_time",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
":",
"stat_result",
"=",
"self",
".",
"_stat",
"(",
")",
"# NOTE: Historically, this used stat_result[stat.ST_MTIME],",
"# which truncates the fractional portion of the ti... | Returns the time that ``self.absolute_path`` was last modified.
May be overridden in subclasses. Should return a `~datetime.datetime`
object or None.
.. versionadded:: 3.1 | [
"Returns",
"the",
"time",
"that",
"self",
".",
"absolute_path",
"was",
"last",
"modified",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2861-L2879 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_content_type | def get_content_type(self) -> str:
"""Returns the ``Content-Type`` header to be used for this request.
.. versionadded:: 3.1
"""
assert self.absolute_path is not None
mime_type, encoding = mimetypes.guess_type(self.absolute_path)
# per RFC 6713, use the appropriate type ... | python | def get_content_type(self) -> str:
"""Returns the ``Content-Type`` header to be used for this request.
.. versionadded:: 3.1
"""
assert self.absolute_path is not None
mime_type, encoding = mimetypes.guess_type(self.absolute_path)
# per RFC 6713, use the appropriate type ... | [
"def",
"get_content_type",
"(",
"self",
")",
"->",
"str",
":",
"assert",
"self",
".",
"absolute_path",
"is",
"not",
"None",
"mime_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"self",
".",
"absolute_path",
")",
"# per RFC 6713, use the approp... | Returns the ``Content-Type`` header to be used for this request.
.. versionadded:: 3.1 | [
"Returns",
"the",
"Content",
"-",
"Type",
"header",
"to",
"be",
"used",
"for",
"this",
"request",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2881-L2900 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_cache_time | def get_cache_time(
self, path: str, modified: Optional[datetime.datetime], mime_type: str
) -> int:
"""Override to customize cache control behavior.
Return a positive number of seconds to make the result
cacheable for that amount of time or 0 to mark resource as
cacheable f... | python | def get_cache_time(
self, path: str, modified: Optional[datetime.datetime], mime_type: str
) -> int:
"""Override to customize cache control behavior.
Return a positive number of seconds to make the result
cacheable for that amount of time or 0 to mark resource as
cacheable f... | [
"def",
"get_cache_time",
"(",
"self",
",",
"path",
":",
"str",
",",
"modified",
":",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
",",
"mime_type",
":",
"str",
")",
"->",
"int",
":",
"return",
"self",
".",
"CACHE_MAX_AGE",
"if",
"\"v\"",
"in",
"s... | Override to customize cache control behavior.
Return a positive number of seconds to make the result
cacheable for that amount of time or 0 to mark resource as
cacheable for an unspecified amount of time (subject to
browser heuristics).
By default returns cache expiry of 10 yea... | [
"Override",
"to",
"customize",
"cache",
"control",
"behavior",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2906-L2919 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.make_static_url | def make_static_url(
cls, settings: Dict[str, Any], path: str, include_version: bool = True
) -> str:
"""Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that it
is a class method rather than an instance method). Subclasses
... | python | def make_static_url(
cls, settings: Dict[str, Any], path: str, include_version: bool = True
) -> str:
"""Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that it
is a class method rather than an instance method). Subclasses
... | [
"def",
"make_static_url",
"(",
"cls",
",",
"settings",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"path",
":",
"str",
",",
"include_version",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"url",
"=",
"settings",
".",
"get",
"(",
"\"static_url_... | Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that it
is a class method rather than an instance method). Subclasses
are only required to implement the signature
``make_static_url(cls, settings, path)``; other keyword
argume... | [
"Constructs",
"a",
"versioned",
"url",
"for",
"the",
"given",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2922-L2951 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.parse_url_path | def parse_url_path(self, url_path: str) -> str:
"""Converts a static URL path into a filesystem path.
``url_path`` is the path component of the URL with
``static_url_prefix`` removed. The return value should be
filesystem path relative to ``static_path``.
This is the inverse o... | python | def parse_url_path(self, url_path: str) -> str:
"""Converts a static URL path into a filesystem path.
``url_path`` is the path component of the URL with
``static_url_prefix`` removed. The return value should be
filesystem path relative to ``static_path``.
This is the inverse o... | [
"def",
"parse_url_path",
"(",
"self",
",",
"url_path",
":",
"str",
")",
"->",
"str",
":",
"if",
"os",
".",
"path",
".",
"sep",
"!=",
"\"/\"",
":",
"url_path",
"=",
"url_path",
".",
"replace",
"(",
"\"/\"",
",",
"os",
".",
"path",
".",
"sep",
")",
... | Converts a static URL path into a filesystem path.
``url_path`` is the path component of the URL with
``static_url_prefix`` removed. The return value should be
filesystem path relative to ``static_path``.
This is the inverse of `make_static_url`. | [
"Converts",
"a",
"static",
"URL",
"path",
"into",
"a",
"filesystem",
"path",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2953-L2964 | train |
tornadoweb/tornado | tornado/web.py | StaticFileHandler.get_version | def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
"""Generate the version string to be used in static URLs.
``settings`` is the `Application.settings` dictionary and ``path``
is the relative location of the requested asset on the filesystem.
The returned value ... | python | def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
"""Generate the version string to be used in static URLs.
``settings`` is the `Application.settings` dictionary and ``path``
is the relative location of the requested asset on the filesystem.
The returned value ... | [
"def",
"get_version",
"(",
"cls",
",",
"settings",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"path",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"abs_path",
"=",
"cls",
".",
"get_absolute_path",
"(",
"settings",
"[",
"\"static_path\""... | Generate the version string to be used in static URLs.
``settings`` is the `Application.settings` dictionary and ``path``
is the relative location of the requested asset on the filesystem.
The returned value should be a string, or ``None`` if no version
could be determined.
.. ... | [
"Generate",
"the",
"version",
"string",
"to",
"be",
"used",
"in",
"static",
"URLs",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2967-L2981 | train |
tornadoweb/tornado | tornado/web.py | UIModule.render_string | def render_string(self, path: str, **kwargs: Any) -> bytes:
"""Renders a template and returns it as a string."""
return self.handler.render_string(path, **kwargs) | python | def render_string(self, path: str, **kwargs: Any) -> bytes:
"""Renders a template and returns it as a string."""
return self.handler.render_string(path, **kwargs) | [
"def",
"render_string",
"(",
"self",
",",
"path",
":",
"str",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"handler",
".",
"render_string",
"(",
"path",
",",
"*",
"*",
"kwargs",
")"
] | Renders a template and returns it as a string. | [
"Renders",
"a",
"template",
"and",
"returns",
"it",
"as",
"a",
"string",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L3241-L3243 | train |
tornadoweb/tornado | tornado/escape.py | xhtml_escape | def xhtml_escape(value: Union[str, bytes]) -> str:
"""Escapes a string so it is valid within HTML or XML.
Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
When used in attribute values the escaped strings must be enclosed
in quotes.
.. versionchanged:: 3.2
Added the single quo... | python | def xhtml_escape(value: Union[str, bytes]) -> str:
"""Escapes a string so it is valid within HTML or XML.
Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
When used in attribute values the escaped strings must be enclosed
in quotes.
.. versionchanged:: 3.2
Added the single quo... | [
"def",
"xhtml_escape",
"(",
"value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"return",
"_XHTML_ESCAPE_RE",
".",
"sub",
"(",
"lambda",
"match",
":",
"_XHTML_ESCAPE_DICT",
"[",
"match",
".",
"group",
"(",
"0",
")",
"]",
",",
... | Escapes a string so it is valid within HTML or XML.
Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
When used in attribute values the escaped strings must be enclosed
in quotes.
.. versionchanged:: 3.2
Added the single quote to the list of escaped characters. | [
"Escapes",
"a",
"string",
"so",
"it",
"is",
"valid",
"within",
"HTML",
"or",
"XML",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L43-L56 | train |
tornadoweb/tornado | tornado/escape.py | xhtml_unescape | def xhtml_unescape(value: Union[str, bytes]) -> str:
"""Un-escapes an XML-escaped string."""
return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value)) | python | def xhtml_unescape(value: Union[str, bytes]) -> str:
"""Un-escapes an XML-escaped string."""
return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value)) | [
"def",
"xhtml_unescape",
"(",
"value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"return",
"re",
".",
"sub",
"(",
"r\"&(#?)(\\w+?);\"",
",",
"_convert_entity",
",",
"_unicode",
"(",
"value",
")",
")"
] | Un-escapes an XML-escaped string. | [
"Un",
"-",
"escapes",
"an",
"XML",
"-",
"escaped",
"string",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L59-L61 | train |
tornadoweb/tornado | tornado/escape.py | json_decode | def json_decode(value: Union[str, bytes]) -> Any:
"""Returns Python objects for the given JSON string.
Supports both `str` and `bytes` inputs.
"""
return json.loads(to_basestring(value)) | python | def json_decode(value: Union[str, bytes]) -> Any:
"""Returns Python objects for the given JSON string.
Supports both `str` and `bytes` inputs.
"""
return json.loads(to_basestring(value)) | [
"def",
"json_decode",
"(",
"value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"Any",
":",
"return",
"json",
".",
"loads",
"(",
"to_basestring",
"(",
"value",
")",
")"
] | Returns Python objects for the given JSON string.
Supports both `str` and `bytes` inputs. | [
"Returns",
"Python",
"objects",
"for",
"the",
"given",
"JSON",
"string",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L78-L83 | train |
tornadoweb/tornado | tornado/escape.py | url_escape | def url_escape(value: Union[str, bytes], plus: bool = True) -> str:
"""Returns a URL-encoded version of the given value.
If ``plus`` is true (the default), spaces will be represented
as "+" instead of "%20". This is appropriate for query strings
but not for the path component of a URL. Note that this... | python | def url_escape(value: Union[str, bytes], plus: bool = True) -> str:
"""Returns a URL-encoded version of the given value.
If ``plus`` is true (the default), spaces will be represented
as "+" instead of "%20". This is appropriate for query strings
but not for the path component of a URL. Note that this... | [
"def",
"url_escape",
"(",
"value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"plus",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"quote",
"=",
"urllib",
".",
"parse",
".",
"quote_plus",
"if",
"plus",
"else",
"urllib",
".",
"parse",
"."... | Returns a URL-encoded version of the given value.
If ``plus`` is true (the default), spaces will be represented
as "+" instead of "%20". This is appropriate for query strings
but not for the path component of a URL. Note that this default
is the reverse of Python's urllib module.
.. versionadded... | [
"Returns",
"a",
"URL",
"-",
"encoded",
"version",
"of",
"the",
"given",
"value",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L91-L103 | train |
tornadoweb/tornado | tornado/escape.py | url_unescape | def url_unescape( # noqa: F811
value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True
) -> Union[str, bytes]:
"""Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the ... | python | def url_unescape( # noqa: F811
value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True
) -> Union[str, bytes]:
"""Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the ... | [
"def",
"url_unescape",
"(",
"# noqa: F811",
"value",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"encoding",
":",
"Optional",
"[",
"str",
"]",
"=",
"\"utf-8\"",
",",
"plus",
":",
"bool",
"=",
"True",
")",
"->",
"Union",
"[",
"str",
",",
"bytes"... | Decodes the given value from a URL.
The argument may be either a byte or unicode string.
If encoding is None, the result will be a byte string. Otherwise,
the result is a unicode string in the specified encoding.
If ``plus`` is true (the default), plus signs will be interpreted
as spaces (litera... | [
"Decodes",
"the",
"given",
"value",
"from",
"a",
"URL",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L118-L144 | train |
tornadoweb/tornado | tornado/escape.py | parse_qs_bytes | def parse_qs_bytes(
qs: str, keep_blank_values: bool = False, strict_parsing: bool = False
) -> Dict[str, List[bytes]]:
"""Parses a query string like urlparse.parse_qs, but returns the
values as byte strings.
Keys still become type str (interpreted as latin1 in python3!)
because it's too painful to... | python | def parse_qs_bytes(
qs: str, keep_blank_values: bool = False, strict_parsing: bool = False
) -> Dict[str, List[bytes]]:
"""Parses a query string like urlparse.parse_qs, but returns the
values as byte strings.
Keys still become type str (interpreted as latin1 in python3!)
because it's too painful to... | [
"def",
"parse_qs_bytes",
"(",
"qs",
":",
"str",
",",
"keep_blank_values",
":",
"bool",
"=",
"False",
",",
"strict_parsing",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"bytes",
"]",
"]",
":",
"# This is gross, but python3 do... | Parses a query string like urlparse.parse_qs, but returns the
values as byte strings.
Keys still become type str (interpreted as latin1 in python3!)
because it's too painful to keep them as byte strings in
python3 and in practice they're nearly always ascii anyway. | [
"Parses",
"a",
"query",
"string",
"like",
"urlparse",
".",
"parse_qs",
"but",
"returns",
"the",
"values",
"as",
"byte",
"strings",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L147-L165 | train |
tornadoweb/tornado | tornado/escape.py | utf8 | def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):... | python | def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811
"""Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8.
"""
if isinstance(value, _UTF8_TYPES):... | [
"def",
"utf8",
"(",
"value",
":",
"Union",
"[",
"None",
",",
"str",
",",
"bytes",
"]",
")",
"->",
"Optional",
"[",
"bytes",
"]",
":",
"# noqa: F811",
"if",
"isinstance",
"(",
"value",
",",
"_UTF8_TYPES",
")",
":",
"return",
"value",
"if",
"not",
"isi... | Converts a string argument to a byte string.
If the argument is already a byte string or None, it is returned unchanged.
Otherwise it must be a unicode string and is encoded as utf8. | [
"Converts",
"a",
"string",
"argument",
"to",
"a",
"byte",
"string",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L186-L196 | train |
tornadoweb/tornado | tornado/escape.py | to_unicode | def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_U... | python | def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_U... | [
"def",
"to_unicode",
"(",
"value",
":",
"Union",
"[",
"None",
",",
"str",
",",
"bytes",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"# noqa: F811",
"if",
"isinstance",
"(",
"value",
",",
"_TO_UNICODE_TYPES",
")",
":",
"return",
"value",
"if",
"no... | Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded as utf8. | [
"Converts",
"a",
"string",
"argument",
"to",
"a",
"unicode",
"string",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L217-L227 | train |
tornadoweb/tornado | tornado/escape.py | recursive_unicode | def recursive_unicode(obj: Any) -> Any:
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict(
(recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
)
eli... | python | def recursive_unicode(obj: Any) -> Any:
"""Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict(
(recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
)
eli... | [
"def",
"recursive_unicode",
"(",
"obj",
":",
"Any",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"recursive_unicode",
"(",
"k",
")",
",",
"recursive_unicode",
"(",
"v",
")",
")",
"for",
"("... | Walks a simple data structure, converting byte strings to unicode.
Supports lists, tuples, and dictionaries. | [
"Walks",
"a",
"simple",
"data",
"structure",
"converting",
"byte",
"strings",
"to",
"unicode",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L240-L256 | train |
tornadoweb/tornado | tornado/escape.py | linkify | def linkify(
text: Union[str, bytes],
shorten: bool = False,
extra_params: Union[str, Callable[[str], str]] = "",
require_protocol: bool = False,
permitted_protocols: List[str] = ["http", "https"],
) -> str:
"""Converts plain text into HTML with links.
For example: ``linkify("Hello http://t... | python | def linkify(
text: Union[str, bytes],
shorten: bool = False,
extra_params: Union[str, Callable[[str], str]] = "",
require_protocol: bool = False,
permitted_protocols: List[str] = ["http", "https"],
) -> str:
"""Converts plain text into HTML with links.
For example: ``linkify("Hello http://t... | [
"def",
"linkify",
"(",
"text",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"shorten",
":",
"bool",
"=",
"False",
",",
"extra_params",
":",
"Union",
"[",
"str",
",",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"]",
"=",
"\"\"",
",",
... | Converts plain text into HTML with links.
For example: ``linkify("Hello http://tornadoweb.org!")`` would return
``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!``
Parameters:
* ``shorten``: Long urls will be shortened for display.
* ``extra_params``: Extra text to include in th... | [
"Converts",
"plain",
"text",
"into",
"HTML",
"with",
"links",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L273-L375 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.current | def current(instance: bool = True) -> Optional["IOLoop"]:
"""Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
... | python | def current(instance: bool = True) -> Optional["IOLoop"]:
"""Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
... | [
"def",
"current",
"(",
"instance",
":",
"bool",
"=",
"True",
")",
"->",
"Optional",
"[",
"\"IOLoop\"",
"]",
":",
"try",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"except",
"(",
"RuntimeError",
",",
"AssertionError",
")",
":",
"if",
... | Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
.. versionchanged:: 4.1
Added ``instance`` argument to c... | [
"Returns",
"the",
"current",
"thread",
"s",
"IOLoop",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L244-L279 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.clear_current | def clear_current() -> None:
"""Clears the `IOLoop` for the current thread.
Intended primarily for use by test frameworks in between tests.
.. versionchanged:: 5.0
This method also clears the current `asyncio` event loop.
"""
old = IOLoop.current(instance=False)
... | python | def clear_current() -> None:
"""Clears the `IOLoop` for the current thread.
Intended primarily for use by test frameworks in between tests.
.. versionchanged:: 5.0
This method also clears the current `asyncio` event loop.
"""
old = IOLoop.current(instance=False)
... | [
"def",
"clear_current",
"(",
")",
"->",
"None",
":",
"old",
"=",
"IOLoop",
".",
"current",
"(",
"instance",
"=",
"False",
")",
"if",
"old",
"is",
"not",
"None",
":",
"old",
".",
"_clear_current_hook",
"(",
")",
"if",
"asyncio",
"is",
"None",
":",
"IO... | Clears the `IOLoop` for the current thread.
Intended primarily for use by test frameworks in between tests.
.. versionchanged:: 5.0
This method also clears the current `asyncio` event loop. | [
"Clears",
"the",
"IOLoop",
"for",
"the",
"current",
"thread",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L301-L313 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.add_handler | def add_handler( # noqa: F811
self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
) -> None:
"""Registers the given handler to receive the given events for ``fd``.
The ``fd`` argument may either be an integer file descriptor or
a file-like object with a ``f... | python | def add_handler( # noqa: F811
self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
) -> None:
"""Registers the given handler to receive the given events for ``fd``.
The ``fd`` argument may either be an integer file descriptor or
a file-like object with a ``f... | [
"def",
"add_handler",
"(",
"# noqa: F811",
"self",
",",
"fd",
":",
"Union",
"[",
"int",
",",
"_Selectable",
"]",
",",
"handler",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
",",
"events",
":",
"int",
")",
"->",
"None",
":",
"raise",
"NotImplementedE... | Registers the given handler to receive the given events for ``fd``.
The ``fd`` argument may either be an integer file descriptor or
a file-like object with a ``fileno()`` and ``close()`` method.
The ``events`` argument is a bitwise or of the constants
``IOLoop.READ``, ``IOLoop.WRITE``,... | [
"Registers",
"the",
"given",
"handler",
"to",
"receive",
"the",
"given",
"events",
"for",
"fd",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L382-L399 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop._setup_logging | def _setup_logging(self) -> None:
"""The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the ... | python | def _setup_logging(self) -> None:
"""The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the ... | [
"def",
"_setup_logging",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"any",
"(",
"[",
"logging",
".",
"getLogger",
"(",
")",
".",
"handlers",
",",
"logging",
".",
"getLogger",
"(",
"\"tornado\"",
")",
".",
"handlers",
",",
"logging",
".",
"getLog... | The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the actual log entry, so we
must explicit... | [
"The",
"IOLoop",
"catches",
"and",
"logs",
"exceptions",
"so",
"it",
"s",
"important",
"that",
"log",
"output",
"be",
"visible",
".",
"However",
"python",
"s",
"default",
"behavior",
"for",
"non",
"-",
"root",
"loggers",
"(",
"prior",
"to",
"python",
"3",
... | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L427-L445 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.run_sync | def run_sync(self, func: Callable, timeout: float = None) -> Any:
"""Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either an awaitable object or
``None``. If the function returns an awaitable object, the
`IOLoop` will run until the awaitable ... | python | def run_sync(self, func: Callable, timeout: float = None) -> Any:
"""Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either an awaitable object or
``None``. If the function returns an awaitable object, the
`IOLoop` will run until the awaitable ... | [
"def",
"run_sync",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"timeout",
":",
"float",
"=",
"None",
")",
"->",
"Any",
":",
"future_cell",
"=",
"[",
"None",
"]",
"# type: List[Optional[Future]]",
"def",
"run",
"(",
")",
"->",
"None",
":",
"try",
":... | Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either an awaitable object or
``None``. If the function returns an awaitable object, the
`IOLoop` will run until the awaitable is resolved (and
`run_sync()` will return the awaitable's result). If... | [
"Starts",
"the",
"IOLoop",
"runs",
"the",
"given",
"function",
"and",
"stops",
"the",
"loop",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L460-L532 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.add_timeout | def add_timeout(
self,
deadline: Union[float, datetime.timedelta],
callback: Callable[..., None],
*args: Any,
**kwargs: Any
) -> object:
"""Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
... | python | def add_timeout(
self,
deadline: Union[float, datetime.timedelta],
callback: Callable[..., None],
*args: Any,
**kwargs: Any
) -> object:
"""Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
... | [
"def",
"add_timeout",
"(",
"self",
",",
"deadline",
":",
"Union",
"[",
"float",
",",
"datetime",
".",
"timedelta",
"]",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any... | Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object... | [
"Runs",
"the",
"callback",
"at",
"the",
"time",
"deadline",
"from",
"the",
"I",
"/",
"O",
"loop",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L548-L587 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.call_later | def call_later(
self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> object:
"""Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method o... | python | def call_later(
self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> object:
"""Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method o... | [
"def",
"call_later",
"(",
"self",
",",
"delay",
":",
"float",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"object",
":",
"return",
"self",
".",
"cal... | Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thre... | [
"Runs",
"the",
"callback",
"after",
"delay",
"seconds",
"have",
"passed",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L589-L602 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.call_at | def call_at(
self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> object:
"""Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle th... | python | def call_at(
self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any
) -> object:
"""Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle th... | [
"def",
"call_at",
"(",
"self",
",",
"when",
":",
"float",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"object",
":",
"return",
"self",
".",
"add_tim... | Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the ... | [
"Runs",
"the",
"callback",
"at",
"the",
"absolute",
"time",
"designated",
"by",
"when",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L604-L620 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.spawn_callback | def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
"""Calls the given callback on the next IOLoop iteration.
As of Tornado 6.0, this method is equivalent to `add_callback`.
.. versionadded:: 4.0
"""
self.add_callback(callback, *args, **kwargs) | python | def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
"""Calls the given callback on the next IOLoop iteration.
As of Tornado 6.0, this method is equivalent to `add_callback`.
.. versionadded:: 4.0
"""
self.add_callback(callback, *args, **kwargs) | [
"def",
"spawn_callback",
"(",
"self",
",",
"callback",
":",
"Callable",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"add_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwarg... | Calls the given callback on the next IOLoop iteration.
As of Tornado 6.0, this method is equivalent to `add_callback`.
.. versionadded:: 4.0 | [
"Calls",
"the",
"given",
"callback",
"on",
"the",
"next",
"IOLoop",
"iteration",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L656-L663 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.add_future | def add_future(
self,
future: "Union[Future[_T], concurrent.futures.Future[_T]]",
callback: Callable[["Future[_T]"], None],
) -> None:
"""Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
... | python | def add_future(
self,
future: "Union[Future[_T], concurrent.futures.Future[_T]]",
callback: Callable[["Future[_T]"], None],
) -> None:
"""Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
... | [
"def",
"add_future",
"(",
"self",
",",
"future",
":",
"\"Union[Future[_T], concurrent.futures.Future[_T]]\"",
",",
"callback",
":",
"Callable",
"[",
"[",
"\"Future[_T]\"",
"]",
",",
"None",
"]",
",",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"future",
"... | Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`.
This method only accepts `.Future` objects and not other
awaitables (unlike most of Tornado where the two are
interchangeable). | [
"Schedules",
"a",
"callback",
"on",
"the",
"IOLoop",
"when",
"the",
"given",
".",
"Future",
"is",
"finished",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L665-L698 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop.run_in_executor | def run_in_executor(
self,
executor: Optional[concurrent.futures.Executor],
func: Callable[..., _T],
*args: Any
) -> Awaitable[_T]:
"""Runs a function in a ``concurrent.futures.Executor``. If
``executor`` is ``None``, the IO loop's default executor will be used.
... | python | def run_in_executor(
self,
executor: Optional[concurrent.futures.Executor],
func: Callable[..., _T],
*args: Any
) -> Awaitable[_T]:
"""Runs a function in a ``concurrent.futures.Executor``. If
``executor`` is ``None``, the IO loop's default executor will be used.
... | [
"def",
"run_in_executor",
"(",
"self",
",",
"executor",
":",
"Optional",
"[",
"concurrent",
".",
"futures",
".",
"Executor",
"]",
",",
"func",
":",
"Callable",
"[",
"...",
",",
"_T",
"]",
",",
"*",
"args",
":",
"Any",
")",
"->",
"Awaitable",
"[",
"_T... | Runs a function in a ``concurrent.futures.Executor``. If
``executor`` is ``None``, the IO loop's default executor will be used.
Use `functools.partial` to pass keyword arguments to ``func``.
.. versionadded:: 5.0 | [
"Runs",
"a",
"function",
"in",
"a",
"concurrent",
".",
"futures",
".",
"Executor",
".",
"If",
"executor",
"is",
"None",
"the",
"IO",
"loop",
"s",
"default",
"executor",
"will",
"be",
"used",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L700-L726 | train |
tornadoweb/tornado | tornado/ioloop.py | IOLoop._run_callback | def _run_callback(self, callback: Callable[[], Any]) -> None:
"""Runs a callback with error handling.
.. versionchanged:: 6.0
CancelledErrors are no longer logged.
"""
try:
ret = callback()
if ret is not None:
from tornado import gen
... | python | def _run_callback(self, callback: Callable[[], Any]) -> None:
"""Runs a callback with error handling.
.. versionchanged:: 6.0
CancelledErrors are no longer logged.
"""
try:
ret = callback()
if ret is not None:
from tornado import gen
... | [
"def",
"_run_callback",
"(",
"self",
",",
"callback",
":",
"Callable",
"[",
"[",
"]",
",",
"Any",
"]",
")",
"->",
"None",
":",
"try",
":",
"ret",
"=",
"callback",
"(",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"from",
"tornado",
"import",
"gen",
... | Runs a callback with error handling.
.. versionchanged:: 6.0
CancelledErrors are no longer logged. | [
"Runs",
"a",
"callback",
"with",
"error",
"handling",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L735-L763 | train |
tornadoweb/tornado | tornado/ioloop.py | PeriodicCallback.start | def start(self) -> None:
"""Starts the timer."""
# 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
self._next_timeout... | python | def start(self) -> None:
"""Starts the timer."""
# 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
self._next_timeout... | [
"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... | Starts the timer. | [
"Starts",
"the",
"timer",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L879-L887 | train |
tornadoweb/tornado | tornado/ioloop.py | PeriodicCallback.stop | def stop(self) -> None:
"""Stops the timer."""
self._running = False
if self._timeout is not None:
self.io_loop.remove_timeout(self._timeout)
self._timeout = None | python | def stop(self) -> None:
"""Stops the timer."""
self._running = False
if self._timeout is not None:
self.io_loop.remove_timeout(self._timeout)
self._timeout = None | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_running",
"=",
"False",
"if",
"self",
".",
"_timeout",
"is",
"not",
"None",
":",
"self",
".",
"io_loop",
".",
"remove_timeout",
"(",
"self",
".",
"_timeout",
")",
"self",
".",
"_timeo... | Stops the timer. | [
"Stops",
"the",
"timer",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L889-L894 | train |
tornadoweb/tornado | tornado/httputil.py | url_concat | def url_concat(
url: str,
args: Union[
None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...]
],
) -> str:
"""Concatenate url and arguments regardless of whether
url has existing query parameters.
``args`` may be either a dictionary or a list of key-value pairs
(th... | python | def url_concat(
url: str,
args: Union[
None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...]
],
) -> str:
"""Concatenate url and arguments regardless of whether
url has existing query parameters.
``args`` may be either a dictionary or a list of key-value pairs
(th... | [
"def",
"url_concat",
"(",
"url",
":",
"str",
",",
"args",
":",
"Union",
"[",
"None",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"Tuple",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]... | Concatenate url and arguments regardless of whether
url has existing query parameters.
``args`` may be either a dictionary or a list of key-value pairs
(the latter allows for multiple values with the same key.
>>> url_concat("http://example.com/foo", dict(c="d"))
'http://example.com/foo?c=d'
>... | [
"Concatenate",
"url",
"and",
"arguments",
"regardless",
"of",
"whether",
"url",
"has",
"existing",
"query",
"parameters",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L631-L675 | train |
tornadoweb/tornado | tornado/httputil.py | _parse_request_range | def _parse_request_range(
range_header: str
) -> Optional[Tuple[Optional[int], Optional[int]]]:
"""Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>... | python | def _parse_request_range(
range_header: str
) -> Optional[Tuple[Optional[int], Optional[int]]]:
"""Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>... | [
"def",
"_parse_request_range",
"(",
"range_header",
":",
"str",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"Optional",
"[",
"int",
"]",
",",
"Optional",
"[",
"int",
"]",
"]",
"]",
":",
"unit",
",",
"_",
",",
"value",
"=",
"range_header",
".",
"partition... | Parses a Range header.
Returns either ``None`` or tuple ``(start, end)``.
Note that while the HTTP headers use inclusive byte positions,
this method returns indexes suitable for use in slices.
>>> start, end = _parse_request_range("bytes=1-2")
>>> start, end
(1, 3)
>>> [0, 1, 2, 3, 4][star... | [
"Parses",
"a",
"Range",
"header",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L692-L740 | train |
tornadoweb/tornado | tornado/httputil.py | _get_content_range | def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str:
"""Returns a suitable Content-Range header:
>>> print(_get_content_range(None, 1, 4))
bytes 0-0/4
>>> print(_get_content_range(1, 3, 4))
bytes 1-2/4
>>> print(_get_content_range(None, None, 4))
bytes 0-3/4
... | python | def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str:
"""Returns a suitable Content-Range header:
>>> print(_get_content_range(None, 1, 4))
bytes 0-0/4
>>> print(_get_content_range(1, 3, 4))
bytes 1-2/4
>>> print(_get_content_range(None, None, 4))
bytes 0-3/4
... | [
"def",
"_get_content_range",
"(",
"start",
":",
"Optional",
"[",
"int",
"]",
",",
"end",
":",
"Optional",
"[",
"int",
"]",
",",
"total",
":",
"int",
")",
"->",
"str",
":",
"start",
"=",
"start",
"or",
"0",
"end",
"=",
"(",
"end",
"or",
"total",
"... | Returns a suitable Content-Range header:
>>> print(_get_content_range(None, 1, 4))
bytes 0-0/4
>>> print(_get_content_range(1, 3, 4))
bytes 1-2/4
>>> print(_get_content_range(None, None, 4))
bytes 0-3/4 | [
"Returns",
"a",
"suitable",
"Content",
"-",
"Range",
"header",
":"
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L743-L755 | train |
tornadoweb/tornado | tornado/httputil.py | parse_body_arguments | def parse_body_arguments(
content_type: str,
body: bytes,
arguments: Dict[str, List[bytes]],
files: Dict[str, List[HTTPFile]],
headers: HTTPHeaders = None,
) -> None:
"""Parses a form request body.
Supports ``application/x-www-form-urlencoded`` and
``multipart/form-data``. The ``conten... | python | def parse_body_arguments(
content_type: str,
body: bytes,
arguments: Dict[str, List[bytes]],
files: Dict[str, List[HTTPFile]],
headers: HTTPHeaders = None,
) -> None:
"""Parses a form request body.
Supports ``application/x-www-form-urlencoded`` and
``multipart/form-data``. The ``conten... | [
"def",
"parse_body_arguments",
"(",
"content_type",
":",
"str",
",",
"body",
":",
"bytes",
",",
"arguments",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"bytes",
"]",
"]",
",",
"files",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"HTTPFile",
"]",
"]",
... | Parses a form request body.
Supports ``application/x-www-form-urlencoded`` and
``multipart/form-data``. The ``content_type`` parameter should be
a string and ``body`` should be a byte string. The ``arguments``
and ``files`` parameters are dictionaries that will be updated
with the parsed contents... | [
"Parses",
"a",
"form",
"request",
"body",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L765-L810 | train |
tornadoweb/tornado | tornado/httputil.py | parse_multipart_form_data | def parse_multipart_form_data(
boundary: bytes,
data: bytes,
arguments: Dict[str, List[bytes]],
files: Dict[str, List[HTTPFile]],
) -> None:
"""Parses a ``multipart/form-data`` body.
The ``boundary`` and ``data`` parameters are both byte strings.
The dictionaries given in the arguments and ... | python | def parse_multipart_form_data(
boundary: bytes,
data: bytes,
arguments: Dict[str, List[bytes]],
files: Dict[str, List[HTTPFile]],
) -> None:
"""Parses a ``multipart/form-data`` body.
The ``boundary`` and ``data`` parameters are both byte strings.
The dictionaries given in the arguments and ... | [
"def",
"parse_multipart_form_data",
"(",
"boundary",
":",
"bytes",
",",
"data",
":",
"bytes",
",",
"arguments",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"bytes",
"]",
"]",
",",
"files",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"HTTPFile",
"]",
"]... | Parses a ``multipart/form-data`` body.
The ``boundary`` and ``data`` parameters are both byte strings.
The dictionaries given in the arguments and files parameters
will be updated with the contents of the body.
.. versionchanged:: 5.1
Now recognizes non-ASCII filenames in RFC 2231/5987
... | [
"Parses",
"a",
"multipart",
"/",
"form",
"-",
"data",
"body",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L813-L868 | train |
tornadoweb/tornado | tornado/httputil.py | format_timestamp | def format_timestamp(
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>... | python | def format_timestamp(
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>... | [
"def",
"format_timestamp",
"(",
"ts",
":",
"Union",
"[",
"int",
",",
"float",
",",
"tuple",
",",
"time",
".",
"struct_time",
",",
"datetime",
".",
"datetime",
"]",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"ts",
",",
"(",
"int",
",",
"float",
... | Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT' | [
"Formats",
"a",
"timestamp",
"in",
"the",
"format",
"used",
"by",
"HTTP",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L871-L891 | train |
tornadoweb/tornado | tornado/httputil.py | parse_request_start_line | def parse_request_start_line(line: str) -> RequestStartLine:
"""Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a `collections.namedtuple`.
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
"""
... | python | def parse_request_start_line(line: str) -> RequestStartLine:
"""Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a `collections.namedtuple`.
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
"""
... | [
"def",
"parse_request_start_line",
"(",
"line",
":",
"str",
")",
"->",
"RequestStartLine",
":",
"try",
":",
"method",
",",
"path",
",",
"version",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"except",
"ValueError",
":",
"# https://tools.ietf.org/html/rfc7230#s... | Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is a `collections.namedtuple`.
>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1') | [
"Returns",
"a",
"(",
"method",
"path",
"version",
")",
"tuple",
"for",
"an",
"HTTP",
"1",
".",
"x",
"request",
"line",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L899-L917 | train |
tornadoweb/tornado | tornado/httputil.py | parse_response_start_line | def parse_response_start_line(line: str) -> ResponseStartLine:
"""Returns a (version, code, reason) tuple for an HTTP 1.x response line.
The response is a `collections.namedtuple`.
>>> parse_response_start_line("HTTP/1.1 200 OK")
ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
"""
... | python | def parse_response_start_line(line: str) -> ResponseStartLine:
"""Returns a (version, code, reason) tuple for an HTTP 1.x response line.
The response is a `collections.namedtuple`.
>>> parse_response_start_line("HTTP/1.1 200 OK")
ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
"""
... | [
"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... | Returns a (version, code, reason) tuple for an HTTP 1.x response line.
The response is a `collections.namedtuple`.
>>> parse_response_start_line("HTTP/1.1 200 OK")
ResponseStartLine(version='HTTP/1.1', code=200, reason='OK') | [
"Returns",
"a",
"(",
"version",
"code",
"reason",
")",
"tuple",
"for",
"an",
"HTTP",
"1",
".",
"x",
"response",
"line",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L925-L937 | train |
tornadoweb/tornado | tornado/httputil.py | _parse_header | def _parse_header(line: str) -> Tuple[str, Dict[str, str]]:
r"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
>>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st"
>>> ct, d = _parse_header(d)
>>> ct
'form-data'
>>> d['file'] == r'T\... | python | def _parse_header(line: str) -> Tuple[str, Dict[str, str]]:
r"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
>>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st"
>>> ct, d = _parse_header(d)
>>> ct
'form-data'
>>> d['file'] == r'T\... | [
"def",
"_parse_header",
"(",
"line",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"parts",
"=",
"_parseparam",
"(",
"\";\"",
"+",
"line",
")",
"key",
"=",
"next",
"(",
"parts",
")",
"# decode_param... | r"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
>>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st"
>>> ct, d = _parse_header(d)
>>> ct
'form-data'
>>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape')
True
>... | [
"r",
"Parse",
"a",
"Content",
"-",
"type",
"like",
"header",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L961-L993 | train |
tornadoweb/tornado | tornado/httputil.py | _encode_header | def _encode_header(key: str, pdict: Dict[str, str]) -> str:
"""Inverse of _parse_header.
>>> _encode_header('permessage-deflate',
... {'client_max_window_bits': 15, 'client_no_context_takeover': None})
'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
"""
if not pd... | python | def _encode_header(key: str, pdict: Dict[str, str]) -> str:
"""Inverse of _parse_header.
>>> _encode_header('permessage-deflate',
... {'client_max_window_bits': 15, 'client_no_context_takeover': None})
'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
"""
if not pd... | [
"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.",
... | Inverse of _parse_header.
>>> _encode_header('permessage-deflate',
... {'client_max_window_bits': 15, 'client_no_context_takeover': None})
'permessage-deflate; client_max_window_bits=15; client_no_context_takeover' | [
"Inverse",
"of",
"_parse_header",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L996-L1013 | train |
tornadoweb/tornado | tornado/httputil.py | encode_username_password | def encode_username_password(
username: Union[str, bytes], password: Union[str, bytes]
) -> bytes:
"""Encodes a username/password pair in the format used by HTTP auth.
The return value is a byte string in the form ``username:password``.
.. versionadded:: 5.1
"""
if isinstance(username, unicode... | python | def encode_username_password(
username: Union[str, bytes], password: Union[str, bytes]
) -> bytes:
"""Encodes a username/password pair in the format used by HTTP auth.
The return value is a byte string in the form ``username:password``.
.. versionadded:: 5.1
"""
if isinstance(username, unicode... | [
"def",
"encode_username_password",
"(",
"username",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"password",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"bytes",
":",
"if",
"isinstance",
"(",
"username",
",",
"unicode_type",
")",
":",
... | Encodes a username/password pair in the format used by HTTP auth.
The return value is a byte string in the form ``username:password``.
.. versionadded:: 5.1 | [
"Encodes",
"a",
"username",
"/",
"password",
"pair",
"in",
"the",
"format",
"used",
"by",
"HTTP",
"auth",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1016-L1029 | train |
tornadoweb/tornado | tornado/httputil.py | split_host_and_port | def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]:
"""Returns ``(host, port)`` tuple from ``netloc``.
Returned ``port`` will be ``None`` if not present.
.. versionadded:: 4.1
"""
match = re.match(r"^(.+):(\d+)$", netloc)
if match:
host = match.group(1)
port = in... | python | def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]:
"""Returns ``(host, port)`` tuple from ``netloc``.
Returned ``port`` will be ``None`` if not present.
.. versionadded:: 4.1
"""
match = re.match(r"^(.+):(\d+)$", netloc)
if match:
host = match.group(1)
port = in... | [
"def",
"split_host_and_port",
"(",
"netloc",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"int",
"]",
"]",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^(.+):(\\d+)$\"",
",",
"netloc",
")",
"if",
"match",
":",
"host",
"=",
"ma... | Returns ``(host, port)`` tuple from ``netloc``.
Returned ``port`` will be ``None`` if not present.
.. versionadded:: 4.1 | [
"Returns",
"(",
"host",
"port",
")",
"tuple",
"from",
"netloc",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1039-L1053 | train |
tornadoweb/tornado | tornado/httputil.py | qs_to_qsl | def qs_to_qsl(qs: Dict[str, List[AnyStr]]) -> Iterable[Tuple[str, AnyStr]]:
"""Generator converting a result of ``parse_qs`` back to name-value pairs.
.. versionadded:: 5.0
"""
for k, vs in qs.items():
for v in vs:
yield (k, v) | python | def qs_to_qsl(qs: Dict[str, List[AnyStr]]) -> Iterable[Tuple[str, AnyStr]]:
"""Generator converting a result of ``parse_qs`` back to name-value pairs.
.. versionadded:: 5.0
"""
for k, vs in qs.items():
for v in vs:
yield (k, v) | [
"def",
"qs_to_qsl",
"(",
"qs",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"AnyStr",
"]",
"]",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"AnyStr",
"]",
"]",
":",
"for",
"k",
",",
"vs",
"in",
"qs",
".",
"items",
"(",
")",
":",
"for"... | Generator converting a result of ``parse_qs`` back to name-value pairs.
.. versionadded:: 5.0 | [
"Generator",
"converting",
"a",
"result",
"of",
"parse_qs",
"back",
"to",
"name",
"-",
"value",
"pairs",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1056-L1063 | train |
tornadoweb/tornado | tornado/httputil.py | _unquote_cookie | def _unquote_cookie(s: str) -> str:
"""Handle double quotes and escaping in cookie values.
This method is copied verbatim from the Python 3.5 standard
library (http.cookies._unquote) so we don't have to depend on
non-public interfaces.
"""
# If there aren't any doublequotes,
# then there ca... | python | def _unquote_cookie(s: str) -> str:
"""Handle double quotes and escaping in cookie values.
This method is copied verbatim from the Python 3.5 standard
library (http.cookies._unquote) so we don't have to depend on
non-public interfaces.
"""
# If there aren't any doublequotes,
# then there ca... | [
"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",
... | Handle double quotes and escaping in cookie values.
This method is copied verbatim from the Python 3.5 standard
library (http.cookies._unquote) so we don't have to depend on
non-public interfaces. | [
"Handle",
"double",
"quotes",
"and",
"escaping",
"in",
"cookie",
"values",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1071-L1118 | train |
tornadoweb/tornado | tornado/httputil.py | parse_cookie | def parse_cookie(cookie: str) -> Dict[str, str]:
"""Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is... | python | def parse_cookie(cookie: str) -> Dict[str, str]:
"""Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is... | [
"def",
"parse_cookie",
"(",
"cookie",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"cookiedict",
"=",
"{",
"}",
"for",
"chunk",
"in",
"cookie",
".",
"split",
"(",
"str",
"(",
"\";\"",
")",
")",
":",
"if",
"str",
"(",
"\"=\"",
... | Parse a ``Cookie`` HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;
it specifically does not follow any of the cookie-related RFCs
(because browsers don't either).
The algorithm used is identical to that used by Django version 1.9.10.
.... | [
"Parse",
"a",
"Cookie",
"HTTP",
"header",
"into",
"a",
"dict",
"of",
"name",
"/",
"value",
"pairs",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1121-L1144 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPHeaders.add | def add(self, name: str, value: str) -> None:
"""Adds a new value for the given key."""
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)
... | python | def add(self, name: str, value: str) -> None:
"""Adds a new value for the given key."""
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)
... | [
"def",
"add",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"norm_name",
"=",
"_normalized_headers",
"[",
"name",
"]",
"self",
".",
"_last_key",
"=",
"norm_name",
"if",
"norm_name",
"in",
"self",
":",
"self",
... | Adds a new value for the given key. | [
"Adds",
"a",
"new",
"value",
"for",
"the",
"given",
"key",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L162-L172 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPHeaders.get_list | def get_list(self, name: str) -> List[str]:
"""Returns all values for the given header as a list."""
norm_name = _normalized_headers[name]
return self._as_list.get(norm_name, []) | python | def get_list(self, name: str) -> List[str]:
"""Returns all values for the given header as a list."""
norm_name = _normalized_headers[name]
return self._as_list.get(norm_name, []) | [
"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. | [
"Returns",
"all",
"values",
"for",
"the",
"given",
"header",
"as",
"a",
"list",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L174-L177 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPHeaders.get_all | def get_all(self) -> Iterable[Tuple[str, str]]:
"""Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
"""
for name, values in self._as_list.items():
for value in values:
... | python | def get_all(self) -> Iterable[Tuple[str, str]]:
"""Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
"""
for name, values in self._as_list.items():
for value in values:
... | [
"def",
"get_all",
"(",
"self",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"for",
"name",
",",
"values",
"in",
"self",
".",
"_as_list",
".",
"items",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"("... | Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name. | [
"Returns",
"an",
"iterable",
"of",
"all",
"(",
"name",
"value",
")",
"pairs",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L179-L187 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPHeaders.parse_line | def parse_line(self, line: str) -> None:
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
# continuation of a multi-l... | python | def parse_line(self, line: str) -> None:
"""Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
"""
if line[0].isspace():
# continuation of a multi-l... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
":",
"str",
")",
"->",
"None",
":",
"if",
"line",
"[",
"0",
"]",
".",
"isspace",
"(",
")",
":",
"# continuation of a multi-line header",
"if",
"self",
".",
"_last_key",
"is",
"None",
":",
"raise",
"HTTPInput... | Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html' | [
"Updates",
"the",
"dictionary",
"with",
"a",
"single",
"header",
"line",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L189-L209 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPHeaders.parse | def parse(cls, headers: str) -> "HTTPHeaders":
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
.. versionchanged:: 5... | python | def parse(cls, headers: str) -> "HTTPHeaders":
"""Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
.. versionchanged:: 5... | [
"def",
"parse",
"(",
"cls",
",",
"headers",
":",
"str",
")",
"->",
"\"HTTPHeaders\"",
":",
"h",
"=",
"cls",
"(",
")",
"for",
"line",
"in",
"_CRLF_RE",
".",
"split",
"(",
"headers",
")",
":",
"if",
"line",
":",
"h",
".",
"parse_line",
"(",
"line",
... | Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
.. versionchanged:: 5.1
Raises `HTTPInputError` on malformed header... | [
"Returns",
"a",
"dictionary",
"from",
"HTTP",
"header",
"text",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L212-L229 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPServerRequest.cookies | def cookies(self) -> Dict[str, http.cookies.Morsel]:
"""A dictionary of ``http.cookies.Morsel`` objects."""
if not hasattr(self, "_cookies"):
self._cookies = http.cookies.SimpleCookie()
if "Cookie" in self.headers:
try:
parsed = parse_cookie(se... | python | def cookies(self) -> Dict[str, http.cookies.Morsel]:
"""A dictionary of ``http.cookies.Morsel`` objects."""
if not hasattr(self, "_cookies"):
self._cookies = http.cookies.SimpleCookie()
if "Cookie" in self.headers:
try:
parsed = parse_cookie(se... | [
"def",
"cookies",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"http",
".",
"cookies",
".",
"Morsel",
"]",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_cookies\"",
")",
":",
"self",
".",
"_cookies",
"=",
"http",
".",
"cookies",
".",
"Simp... | A dictionary of ``http.cookies.Morsel`` objects. | [
"A",
"dictionary",
"of",
"http",
".",
"cookies",
".",
"Morsel",
"objects",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L410-L428 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPServerRequest.request_time | def request_time(self) -> float:
"""Returns the amount of time it took for this request to execute."""
if self._finish_time is None:
return time.time() - self._start_time
else:
return self._finish_time - self._start_time | python | def request_time(self) -> float:
"""Returns the amount of time it took for this request to execute."""
if self._finish_time is None:
return time.time() - self._start_time
else:
return self._finish_time - self._start_time | [
"def",
"request_time",
"(",
"self",
")",
"->",
"float",
":",
"if",
"self",
".",
"_finish_time",
"is",
"None",
":",
"return",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_start_time",
"else",
":",
"return",
"self",
".",
"_finish_time",
"-",
"self"... | Returns the amount of time it took for this request to execute. | [
"Returns",
"the",
"amount",
"of",
"time",
"it",
"took",
"for",
"this",
"request",
"to",
"execute",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L434-L439 | train |
tornadoweb/tornado | tornado/httputil.py | HTTPServerRequest.get_ssl_certificate | def get_ssl_certificate(
self, binary_form: bool = False
) -> Union[None, Dict, bytes]:
"""Returns the client's SSL certificate, if any.
To use client certificates, the HTTPServer's
`ssl.SSLContext.verify_mode` field must be set, e.g.::
ssl_ctx = ssl.create_default_cont... | python | def get_ssl_certificate(
self, binary_form: bool = False
) -> Union[None, Dict, bytes]:
"""Returns the client's SSL certificate, if any.
To use client certificates, the HTTPServer's
`ssl.SSLContext.verify_mode` field must be set, e.g.::
ssl_ctx = ssl.create_default_cont... | [
"def",
"get_ssl_certificate",
"(",
"self",
",",
"binary_form",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"None",
",",
"Dict",
",",
"bytes",
"]",
":",
"try",
":",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"return",
"None",
"# TODO: a... | Returns the client's SSL certificate, if any.
To use client certificates, the HTTPServer's
`ssl.SSLContext.verify_mode` field must be set, e.g.::
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain("foo.crt", "foo.key")
ssl_ctx.load... | [
"Returns",
"the",
"client",
"s",
"SSL",
"certificate",
"if",
"any",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L441-L470 | train |
tornadoweb/tornado | tornado/netutil.py | bind_sockets | 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]:
"""Creates listening sockets bound to the given port and address.
Returns a list of ... | python | 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]:
"""Creates listening sockets bound to the given port and address.
Returns a list of ... | [
"def",
"bind_sockets",
"(",
"port",
":",
"int",
",",
"address",
":",
"str",
"=",
"None",
",",
"family",
":",
"socket",
".",
"AddressFamily",
"=",
"socket",
".",
"AF_UNSPEC",
",",
"backlog",
":",
"int",
"=",
"_DEFAULT_BACKLOG",
",",
"flags",
":",
"int",
... | Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if
the given address maps to multiple IP addresses, which is most common
for mixed IPv4 and IPv6 use).
Address may be either an IP address or hostname. If it's a hostname,
... | [
"Creates",
"listening",
"sockets",
"bound",
"to",
"the",
"given",
"port",
"and",
"address",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L68-L178 | train |
tornadoweb/tornado | tornado/netutil.py | add_accept_handler | def add_accept_handler(
sock: socket.socket, callback: Callable[[socket.socket, Any], None]
) -> Callable[[], None]:
"""Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object,... | python | def add_accept_handler(
sock: socket.socket, callback: Callable[[socket.socket, Any], None]
) -> Callable[[], None]:
"""Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object,... | [
"def",
"add_accept_handler",
"(",
"sock",
":",
"socket",
".",
"socket",
",",
"callback",
":",
"Callable",
"[",
"[",
"socket",
".",
"socket",
",",
"Any",
"]",
",",
"None",
"]",
")",
"->",
"Callable",
"[",
"[",
"]",
",",
"None",
"]",
":",
"io_loop",
... | Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the connection). Note that this signature
is different from the ``c... | [
"Adds",
"an",
".",
"IOLoop",
"event",
"handler",
"to",
"accept",
"new",
"connections",
"on",
"sock",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L220-L280 | train |
tornadoweb/tornado | tornado/netutil.py | is_valid_ip | def is_valid_ip(ip: str) -> bool:
"""Returns ``True`` if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
if not ip or "\x00" in ip:
# getaddrinfo resolves empty strings to localhost, and truncates
# on zero bytes.
return False
try:
res = soc... | python | def is_valid_ip(ip: str) -> bool:
"""Returns ``True`` if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
if not ip or "\x00" in ip:
# getaddrinfo resolves empty strings to localhost, and truncates
# on zero bytes.
return False
try:
res = soc... | [
"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",... | Returns ``True`` if the given string is a well-formed IP address.
Supports IPv4 and IPv6. | [
"Returns",
"True",
"if",
"the",
"given",
"string",
"is",
"a",
"well",
"-",
"formed",
"IP",
"address",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L283-L301 | train |
tornadoweb/tornado | tornado/netutil.py | ssl_options_to_context | def ssl_options_to_context(
ssl_options: Union[Dict[str, Any], ssl.SSLContext]
) -> ssl.SSLContext:
"""Try to convert an ``ssl_options`` dictionary to an
`~ssl.SSLContext` object.
The ``ssl_options`` dictionary contains keywords to be passed to
`ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext`... | python | def ssl_options_to_context(
ssl_options: Union[Dict[str, Any], ssl.SSLContext]
) -> ssl.SSLContext:
"""Try to convert an ``ssl_options`` dictionary to an
`~ssl.SSLContext` object.
The ``ssl_options`` dictionary contains keywords to be passed to
`ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext`... | [
"def",
"ssl_options_to_context",
"(",
"ssl_options",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"ssl",
".",
"SSLContext",
"]",
")",
"->",
"ssl",
".",
"SSLContext",
":",
"if",
"isinstance",
"(",
"ssl_options",
",",
"ssl",
".",
"SSLContex... | Try to convert an ``ssl_options`` dictionary to an
`~ssl.SSLContext` object.
The ``ssl_options`` dictionary contains keywords to be passed to
`ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can
be used instead. This function converts the dict form to its
`~ssl.SSLContext` equivalent... | [
"Try",
"to",
"convert",
"an",
"ssl_options",
"dictionary",
"to",
"an",
"~ssl",
".",
"SSLContext",
"object",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L552-L588 | train |
tornadoweb/tornado | tornado/netutil.py | ssl_wrap_socket | def ssl_wrap_socket(
socket: socket.socket,
ssl_options: Union[Dict[str, Any], ssl.SSLContext],
server_hostname: str = None,
**kwargs: Any
) -> ssl.SSLSocket:
"""Returns an ``ssl.SSLSocket`` wrapping the given socket.
``ssl_options`` may be either an `ssl.SSLContext` object or a
dictionary ... | python | def ssl_wrap_socket(
socket: socket.socket,
ssl_options: Union[Dict[str, Any], ssl.SSLContext],
server_hostname: str = None,
**kwargs: Any
) -> ssl.SSLSocket:
"""Returns an ``ssl.SSLSocket`` wrapping the given socket.
``ssl_options`` may be either an `ssl.SSLContext` object or a
dictionary ... | [
"def",
"ssl_wrap_socket",
"(",
"socket",
":",
"socket",
".",
"socket",
",",
"ssl_options",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"ssl",
".",
"SSLContext",
"]",
",",
"server_hostname",
":",
"str",
"=",
"None",
",",
"*",
"*",
"kw... | Returns an ``ssl.SSLSocket`` wrapping the given socket.
``ssl_options`` may be either an `ssl.SSLContext` object or a
dictionary (as accepted by `ssl_options_to_context`). Additional
keyword arguments are passed to ``wrap_socket`` (either the
`~ssl.SSLContext` method or the `ssl` module function as
... | [
"Returns",
"an",
"ssl",
".",
"SSLSocket",
"wrapping",
"the",
"given",
"socket",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L591-L614 | train |
tornadoweb/tornado | tornado/concurrent.py | run_on_executor | def run_on_executor(*args: Any, **kwargs: Any) -> Callable:
"""Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ... | python | def run_on_executor(*args: Any, **kwargs: Any) -> Callable:
"""Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ... | [
"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_de... | Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ``self``. To use a different attribute name, pass a
keyword arg... | [
"Decorator",
"to",
"run",
"a",
"synchronous",
"method",
"asynchronously",
"on",
"an",
"executor",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L74-L135 | train |
tornadoweb/tornado | tornado/concurrent.py | chain_future | def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
"""Chain two futures together so that when one completes, so does the other.
The result (success or failure) of ``a`` will be copied to ``b``, unless
``b`` has already been completed or cancelled by the time ``a`` finishes.
.. versionchanged:... | python | def chain_future(a: "Future[_T]", b: "Future[_T]") -> None:
"""Chain two futures together so that when one completes, so does the other.
The result (success or failure) of ``a`` will be copied to ``b``, unless
``b`` has already been completed or cancelled by the time ``a`` finishes.
.. versionchanged:... | [
"def",
"chain_future",
"(",
"a",
":",
"\"Future[_T]\"",
",",
"b",
":",
"\"Future[_T]\"",
")",
"->",
"None",
":",
"def",
"copy",
"(",
"future",
":",
"\"Future[_T]\"",
")",
"->",
"None",
":",
"assert",
"future",
"is",
"a",
"if",
"b",
".",
"done",
"(",
... | Chain two futures together so that when one completes, so does the other.
The result (success or failure) of ``a`` will be copied to ``b``, unless
``b`` has already been completed or cancelled by the time ``a`` finishes.
.. versionchanged:: 5.0
Now accepts both Tornado/asyncio `Future` objects and... | [
"Chain",
"two",
"futures",
"together",
"so",
"that",
"when",
"one",
"completes",
"so",
"does",
"the",
"other",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L141-L171 | train |
tornadoweb/tornado | tornado/concurrent.py | future_set_exception_unless_cancelled | def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly che... | python | def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly che... | [
"def",
"future_set_exception_unless_cancelled",
"(",
"future",
":",
"\"Union[futures.Future[_T], Future[_T]]\"",
",",
"exc",
":",
"BaseException",
")",
"->",
"None",
":",
"if",
"not",
"future",
".",
"cancelled",
"(",
")",
":",
"future",
".",
"set_exception",
"(",
... | Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly check
the state of the Future and call ``Future.set_exception`` instead of
this wrapper.
Avoids ``asyncio.InvalidStateError... | [
"Set",
"the",
"given",
"exc",
"as",
"the",
"Future",
"s",
"exception",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L188-L207 | train |
tornadoweb/tornado | tornado/concurrent.py | future_set_exc_info | def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in ... | python | def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in ... | [
"def",
"future_set_exc_info",
"(",
"future",
":",
"\"Union[futures.Future[_T], Future[_T]]\"",
",",
"exc_info",
":",
"Tuple",
"[",
"Optional",
"[",
"type",
"]",
",",
"Optional",
"[",
"BaseException",
"]",
",",
"Optional",
"[",
"types",
".",
"TracebackType",
"]",
... | Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
... | [
"Set",
"the",
"given",
"exc_info",
"as",
"the",
"Future",
"s",
"exception",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L210-L231 | train |
tornadoweb/tornado | tornado/concurrent.py | future_add_done_callback | def future_add_done_callback( # noqa: F811
future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None]
) -> None:
"""Arrange to call ``callback`` when ``future`` is complete.
``callback`` is invoked with one argument, the ``future``.
If ``future`` is already done, ``callback`` is i... | python | def future_add_done_callback( # noqa: F811
future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None]
) -> None:
"""Arrange to call ``callback`` when ``future`` is complete.
``callback`` is invoked with one argument, the ``future``.
If ``future`` is already done, ``callback`` is i... | [
"def",
"future_add_done_callback",
"(",
"# noqa: F811",
"future",
":",
"\"Union[futures.Future[_T], Future[_T]]\"",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"None",
"]",
")",
"->",
"None",
":",
"if",
"future",
".",
"done",
"(",
")",
":",
"callback",
... | Arrange to call ``callback`` when ``future`` is complete.
``callback`` is invoked with one argument, the ``future``.
If ``future`` is already done, ``callback`` is invoked immediately.
This may differ from the behavior of ``Future.add_done_callback``,
which makes no such guarantee.
.. versionadde... | [
"Arrange",
"to",
"call",
"callback",
"when",
"future",
"is",
"complete",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L248-L264 | train |
tornadoweb/tornado | tornado/template.py | filter_whitespace | def filter_whitespace(mode: str, text: str) -> str:
"""Transform whitespace in ``text`` according to ``mode``.
Available modes are:
* ``all``: Return all whitespace unmodified.
* ``single``: Collapse consecutive whitespace with a single whitespace
character, preserving newlines.
* ``oneline`... | python | def filter_whitespace(mode: str, text: str) -> str:
"""Transform whitespace in ``text`` according to ``mode``.
Available modes are:
* ``all``: Return all whitespace unmodified.
* ``single``: Collapse consecutive whitespace with a single whitespace
character, preserving newlines.
* ``oneline`... | [
"def",
"filter_whitespace",
"(",
"mode",
":",
"str",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"if",
"mode",
"==",
"\"all\"",
":",
"return",
"text",
"elif",
"mode",
"==",
"\"single\"",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"([\\t ]+)\"",
... | Transform whitespace in ``text`` according to ``mode``.
Available modes are:
* ``all``: Return all whitespace unmodified.
* ``single``: Collapse consecutive whitespace with a single whitespace
character, preserving newlines.
* ``oneline``: Collapse all runs of whitespace into a single space
... | [
"Transform",
"whitespace",
"in",
"text",
"according",
"to",
"mode",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L226-L248 | train |
tornadoweb/tornado | tornado/template.py | Template.generate | def generate(self, **kwargs: Any) -> bytes:
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
... | python | def generate(self, **kwargs: Any) -> bytes:
"""Generate this template with the given arguments."""
namespace = {
"escape": escape.xhtml_escape,
"xhtml_escape": escape.xhtml_escape,
"url_escape": escape.url_escape,
"json_encode": escape.json_encode,
... | [
"def",
"generate",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"bytes",
":",
"namespace",
"=",
"{",
"\"escape\"",
":",
"escape",
".",
"xhtml_escape",
",",
"\"xhtml_escape\"",
":",
"escape",
".",
"xhtml_escape",
",",
"\"url_escape\"",
":",
... | Generate this template with the given arguments. | [
"Generate",
"this",
"template",
"with",
"the",
"given",
"arguments",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L336-L361 | train |
tornadoweb/tornado | tornado/template.py | BaseLoader.load | def load(self, name: str, parent_path: str = None) -> Template:
"""Loads a 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)
return self.te... | python | def load(self, name: str, parent_path: str = None) -> Template:
"""Loads a 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)
return self.te... | [
"def",
"load",
"(",
"self",
",",
"name",
":",
"str",
",",
"parent_path",
":",
"str",
"=",
"None",
")",
"->",
"Template",
":",
"name",
"=",
"self",
".",
"resolve_path",
"(",
"name",
",",
"parent_path",
"=",
"parent_path",
")",
"with",
"self",
".",
"lo... | Loads a template. | [
"Loads",
"a",
"template",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L440-L446 | train |
tornadoweb/tornado | tornado/gen.py | coroutine | def coroutine(
func: Callable[..., "Generator[Any, Any, _T]"]
) -> Callable[..., "Future[_T]"]:
"""Decorator for asynchronous generators.
For compatibility with older versions of Python, coroutines may
also "return" by raising the special exception `Return(value)
<Return>`.
Functions with this... | python | def coroutine(
func: Callable[..., "Generator[Any, Any, _T]"]
) -> Callable[..., "Future[_T]"]:
"""Decorator for asynchronous generators.
For compatibility with older versions of Python, coroutines may
also "return" by raising the special exception `Return(value)
<Return>`.
Functions with this... | [
"def",
"coroutine",
"(",
"func",
":",
"Callable",
"[",
"...",
",",
"\"Generator[Any, Any, _T]\"",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"\"Future[_T]\"",
"]",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args... | Decorator for asynchronous generators.
For compatibility with older versions of Python, coroutines may
also "return" by raising the special exception `Return(value)
<Return>`.
Functions with this decorator return a `.Future`.
.. warning::
When exceptions occur inside a coroutine, the exce... | [
"Decorator",
"for",
"asynchronous",
"generators",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L156-L245 | train |
tornadoweb/tornado | tornado/gen.py | multi | def multi(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
"""Runs multiple asynchronous operations in parallel.
``children`` may either be a list or a dict whose values are... | python | def multi(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
"""Runs multiple asynchronous operations in parallel.
``children`` may either be a list or a dict whose values are... | [
"def",
"multi",
"(",
"children",
":",
"Union",
"[",
"List",
"[",
"_Yieldable",
"]",
",",
"Dict",
"[",
"Any",
",",
"_Yieldable",
"]",
"]",
",",
"quiet_exceptions",
":",
"\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"",
"=",
"(",
")",
",",
")",
"->",
... | Runs multiple asynchronous operations in parallel.
``children`` may either be a list or a dict whose values are
yieldable objects. ``multi()`` returns a new yieldable
object that resolves to a parallel structure containing their
results. If ``children`` is a list, the result is a list of
results in... | [
"Runs",
"multiple",
"asynchronous",
"operations",
"in",
"parallel",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L409-L457 | train |
tornadoweb/tornado | tornado/gen.py | multi_future | def multi_future(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
"""Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same... | python | def multi_future(
children: Union[List[_Yieldable], Dict[Any, _Yieldable]],
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> "Union[Future[List], Future[Dict]]":
"""Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same... | [
"def",
"multi_future",
"(",
"children",
":",
"Union",
"[",
"List",
"[",
"_Yieldable",
"]",
",",
"Dict",
"[",
"Any",
",",
"_Yieldable",
"]",
"]",
",",
"quiet_exceptions",
":",
"\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"",
"=",
"(",
")",
",",
")",
"... | Wait for multiple asynchronous futures in parallel.
Since Tornado 6.0, this function is exactly the same as `multi`.
.. versionadded:: 4.0
.. versionchanged:: 4.2
If multiple ``Futures`` fail, any exceptions after the first (which is
raised) will be logged. Added the ``quiet_exceptions``
... | [
"Wait",
"for",
"multiple",
"asynchronous",
"futures",
"in",
"parallel",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L463-L523 | train |
tornadoweb/tornado | tornado/gen.py | maybe_future | def maybe_future(x: Any) -> Future:
"""Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` o... | python | def maybe_future(x: Any) -> Future:
"""Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` o... | [
"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`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` or not.
.. deprecated:: 4.3
This... | [
"Converts",
"x",
"into",
"a",
".",
"Future",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L526-L544 | train |
tornadoweb/tornado | tornado/gen.py | with_timeout | def with_timeout(
timeout: Union[float, datetime.timedelta],
future: _Yieldable,
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> Future:
"""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
... | python | def with_timeout(
timeout: Union[float, datetime.timedelta],
future: _Yieldable,
quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (),
) -> Future:
"""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
... | [
"def",
"with_timeout",
"(",
"timeout",
":",
"Union",
"[",
"float",
",",
"datetime",
".",
"timedelta",
"]",
",",
"future",
":",
"_Yieldable",
",",
"quiet_exceptions",
":",
"\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"",
"=",
"(",
")",
",",
")",
"->",
"... | Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
... | [
"Wraps",
"a",
".",
"Future",
"(",
"or",
"other",
"yieldable",
"object",
")",
"in",
"a",
"timeout",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L547-L616 | train |
tornadoweb/tornado | tornado/gen.py | sleep | def sleep(duration: float) -> "Future[None]":
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
... | python | def sleep(duration: float) -> "Future[None]":
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
... | [
"def",
"sleep",
"(",
"duration",
":",
"float",
")",
"->",
"\"Future[None]\"",
":",
"f",
"=",
"_create_future",
"(",
")",
"IOLoop",
".",
"current",
"(",
")",
".",
"call_later",
"(",
"duration",
",",
"lambda",
":",
"future_set_result_unless_cancelled",
"(",
"f... | Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
Note that calling this function on its own does n... | [
"Return",
"a",
".",
"Future",
"that",
"resolves",
"after",
"the",
"given",
"number",
"of",
"seconds",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L619-L637 | train |
tornadoweb/tornado | tornado/gen.py | convert_yielded | def convert_yielded(yielded: _Yieldable) -> Future:
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and
Futures. This has the side effect of starting any coroutines that
did not start themselves, similar to `asyncio.ensure_future`.
If the `~fun... | python | def convert_yielded(yielded: _Yieldable) -> Future:
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and
Futures. This has the side effect of starting any coroutines that
did not start themselves, similar to `asyncio.ensure_future`.
If the `~fun... | [
"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",
"i... | Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and
Futures. This has the side effect of starting any coroutines that
did not start themselves, similar to `asyncio.ensure_future`.
If the `~functools.singledispatch` library is available, this function
... | [
"Convert",
"a",
"yielded",
"object",
"into",
"a",
".",
"Future",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L808-L836 | train |
tornadoweb/tornado | tornado/gen.py | WaitIterator.next | def next(self) -> Future:
"""Returns a `.Future` that will yield the next available result.
Note that this `.Future` will not be the same object as any of
the inputs.
"""
self._running_future = Future()
if self._finished:
self._return_result(self._finished.p... | python | def next(self) -> Future:
"""Returns a `.Future` that will yield the next available result.
Note that this `.Future` will not be the same object as any of
the inputs.
"""
self._running_future = Future()
if self._finished:
self._return_result(self._finished.p... | [
"def",
"next",
"(",
"self",
")",
"->",
"Future",
":",
"self",
".",
"_running_future",
"=",
"Future",
"(",
")",
"if",
"self",
".",
"_finished",
":",
"self",
".",
"_return_result",
"(",
"self",
".",
"_finished",
".",
"popleft",
"(",
")",
")",
"return",
... | Returns a `.Future` that will yield the next available result.
Note that this `.Future` will not be the same object as any of
the inputs. | [
"Returns",
"a",
".",
"Future",
"that",
"will",
"yield",
"the",
"next",
"available",
"result",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L369-L380 | train |
tornadoweb/tornado | tornado/gen.py | Runner.run | def run(self) -> None:
"""Starts or resumes the generator, running until it reaches a
yield point that is not ready.
"""
if self.running or self.finished:
return
try:
self.running = True
while True:
future = self.future
... | python | def run(self) -> None:
"""Starts or resumes the generator, running until it reaches a
yield point that is not ready.
"""
if self.running or self.finished:
return
try:
self.running = True
while True:
future = self.future
... | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"running",
"or",
"self",
".",
"finished",
":",
"return",
"try",
":",
"self",
".",
"running",
"=",
"True",
"while",
"True",
":",
"future",
"=",
"self",
".",
"future",
"if",
"futur... | Starts or resumes the generator, running until it reaches a
yield point that is not ready. | [
"Starts",
"or",
"resumes",
"the",
"generator",
"running",
"until",
"it",
"reaches",
"a",
"yield",
"point",
"that",
"is",
"not",
"ready",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L710-L762 | train |
tornadoweb/tornado | tornado/iostream.py | _StreamBuffer.append | def append(self, data: Union[bytes, bytearray, memoryview]) -> None:
"""
Append the given piece of data (should be a buffer-compatible object).
"""
size = len(data)
if size > self._large_buf_threshold:
if not isinstance(data, memoryview):
data = memory... | python | def append(self, data: Union[bytes, bytearray, memoryview]) -> None:
"""
Append the given piece of data (should be a buffer-compatible object).
"""
size = len(data)
if size > self._large_buf_threshold:
if not isinstance(data, memoryview):
data = memory... | [
"def",
"append",
"(",
"self",
",",
"data",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
",",
"memoryview",
"]",
")",
"->",
"None",
":",
"size",
"=",
"len",
"(",
"data",
")",
"if",
"size",
">",
"self",
".",
"_large_buf_threshold",
":",
"if",
"not",
... | Append the given piece of data (should be a buffer-compatible object). | [
"Append",
"the",
"given",
"piece",
"of",
"data",
"(",
"should",
"be",
"a",
"buffer",
"-",
"compatible",
"object",
")",
"."
] | b8b481770bcdb333a69afde5cce7eaa449128326 | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L159-L179 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.