Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def pgettext(
self, context: str, message: str, plural_message: str = None, count: int = None
) -> str:
if plural_message is not None:
assert count is not None
msgs_with_ctxt = (
"%s%s%s" % (context, CONTEX... | [
"Allows to set context for translation, accepts plural forms.\n\n Usage example::\n\n pgettext(\"law\", \"right\")\n pgettext(\"good\", \"right\")\n\n Plural message example::\n\n pgettext(\"organization\", \"club\", \"clubs\", len(clubs))\n pgettext(\"stick... |
Please provide a description of the function:def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811
if s is None:
return s
return url_unescape(s, encoding=None, plus=False) | [
"None-safe wrapper around url_unescape to handle unmatched optional\n groups correctly.\n\n Note that args are passed as bytes so the handler can decide what\n encoding to use.\n "
] |
Please provide a description of the function:def find_handler(
self, request: httputil.HTTPServerRequest, **kwargs: Any
) -> Optional[httputil.HTTPMessageDelegate]:
raise NotImplementedError() | [
"Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate`\n that can serve the request.\n Routing implementations may pass additional kwargs to extend the routing logic.\n\n :arg httputil.HTTPServerRequest request: current HTTP request.\n :arg kwargs: add... |
Please provide a description of the function:def add_rules(self, rules: _RuleList) -> None:
for rule in rules:
if isinstance(rule, (tuple, list)):
assert len(rule) in (2, 3, 4)
if isinstance(rule[0], basestring_type):
rule = Rule(PathMatch... | [
"Appends new rules to the router.\n\n :arg rules: a list of Rule instances (or tuples of arguments, which are\n passed to Rule constructor).\n "
] |
Please provide a description of the function:def get_target_delegate(
self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any
) -> Optional[httputil.HTTPMessageDelegate]:
if isinstance(target, Router):
return target.find_handler(request, **target_params)
... | [
"Returns an instance of `~.httputil.HTTPMessageDelegate` for a\n Rule's target. This method is called by `~.find_handler` and can be\n extended to provide additional target types.\n\n :arg target: a Rule's target.\n :arg httputil.HTTPServerRequest request: current request.\n :arg ... |
Please provide a description of the function:def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
raise NotImplementedError() | [
"Matches current instance against the request.\n\n :arg httputil.HTTPServerRequest request: current HTTP request\n :returns: a dict of parameters to be passed to the target handler\n (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``\n can be passed for proper `~.we... |
Please provide a description of the function:def _find_groups(self) -> Tuple[Optional[str], Optional[int]]:
pattern = self.regex.pattern
if pattern.startswith("^"):
pattern = pattern[1:]
if pattern.endswith("$"):
pattern = pattern[:-1]
if self.regex.grou... | [
"Returns a tuple (reverse string, group count) for a url.\n\n For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method\n would return ('/%s/%s/', 2).\n "
] |
Please provide a description of the function:async def get_links_from_url(url):
response = await httpclient.AsyncHTTPClient().fetch(url)
print("fetched %s" % url)
html = response.body.decode(errors="ignore")
return [urljoin(url, remove_fragment(new_url)) for new_url in get_links(html)] | [
"Download the page at `url` and parse it for links.\n\n Returned links have had the fragment after `#` removed, and have been made\n absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes\n 'http://www.tornadoweb.org/en/stable/gen.html'.\n "
] |
Please provide a description of the function:def get_messages_since(self, cursor):
results = []
for msg in reversed(self.cache):
if msg["id"] == cursor:
break
results.append(msg)
results.reverse()
return results | [
"Returns a list of messages newer than the given cursor.\n\n ``cursor`` should be the ``id`` of the last message received.\n "
] |
Please provide a description of the function:def import_object(name: str) -> Any:
if name.count(".") == 0:
return __import__(name)
parts = name.split(".")
obj = __import__(".".join(parts[:-1]), fromlist=[parts[-1]])
try:
return getattr(obj, parts[-1])
except AttributeError:
... | [
"Imports an object by name.\n\n ``import_object('x')`` is equivalent to ``import x``.\n ``import_object('x.y.z')`` is equivalent to ``from x.y import z``.\n\n >>> import tornado.escape\n >>> import_object('tornado.escape') is tornado.escape\n True\n >>> import_object('tornado.escape.utf8') is torn... |
Please provide a description of the function:def errno_from_exception(e: BaseException) -> Optional[int]:
if hasattr(e, "errno"):
return e.errno # type: ignore
elif e.args:
return e.args[0]
else:
return None | [
"Provides the errno from an Exception object.\n\n There are cases that the errno attribute was not set so we pull\n the errno out of the args but if someone instantiates an Exception\n without any args you will get a tuple error. So this function\n abstracts all that behavior to give you a safe way to g... |
Please provide a description of the function:def _websocket_mask_python(mask: bytes, data: bytes) -> bytes:
mask_arr = array.array("B", mask)
unmasked_arr = array.array("B", data)
for i in range(len(data)):
unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
return unmasked_arr.tobytes() | [
"Websocket masking function.\n\n `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n Returns a `bytes` object of the same length as `data` with the mask applied\n as specified in section 5.3 of RFC 6455.\n\n This pure-python implementation may be replaced by an optimized ... |
Please provide a description of the function:def decompress(self, value: bytes, max_length: int = 0) -> bytes:
return self.decompressobj.decompress(value, max_length) | [
"Decompress a chunk, returning newly-available data.\n\n Some data may be buffered for later processing; `flush` must\n be called when there is no more input data to ensure that\n all data was processed.\n\n If ``max_length`` is given, some input data may be left over\n in ``uncon... |
Please provide a description of the function:def configure(cls, impl, **kwargs):
# type: (Union[None, str, Type[Configurable]], Any) -> None
base = cls.configurable_base()
if isinstance(impl, str):
impl = typing.cast(Type[Configurable], import_object(impl))
if impl i... | [
"Sets the class to use when the base class is instantiated.\n\n Keyword arguments will be saved and added to the arguments passed\n to the constructor. This can be used to set global defaults for\n some parameters.\n "
] |
Please provide a description of the function:def get_old_value(
self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None
) -> Any:
if self.arg_pos is not None and len(args) > self.arg_pos:
return args[self.arg_pos]
else:
return kwargs.get(self.n... | [
"Returns the old value of the named argument without replacing it.\n\n Returns ``default`` if the argument is not present.\n "
] |
Please provide a description of the function:def replace(
self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any]
) -> Tuple[Any, Sequence[Any], Dict[str, Any]]:
if self.arg_pos is not None and len(args) > self.arg_pos:
# The arg to replace is passed positionally
... | [
"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n Returns ``(old_value, args, kwargs)``. The returned ``args`` and\n ``kwargs`` objects may not be the same as the input objects, or\n the input objects may be mutated.\n\n If the named argument was not found, ``new_v... |
Please provide a description of the function:def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]:
hostport = request.host.split(":")
if len(hostport) == 2:
host = hostport[0]
port = int(hostport[1])
else:
host = request.host
... | [
"Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.\n "
] |
Please provide a description of the function:def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]:
# noqa: E501
if not issubclass(cls, RequestHandler):
raise TypeError("expected subclass of RequestHandler, got %r", cls)
cls._stream_request_body = True
return cls | [
"Apply to `RequestHandler` subclasses to enable streaming body support.\n\n This decorator implies the following changes:\n\n * `.HTTPServerRequest.body` is undefined, and body arguments will not\n be included in `RequestHandler.get_argument`.\n * `RequestHandler.prepare` is called when the request he... |
Please provide a description of the function:def removeslash(
method: Callable[..., Optional[Awaitable[None]]]
) -> Callable[..., Optional[Awaitable[None]]]:
@functools.wraps(method)
def wrapper( # type: ignore
self: RequestHandler, *args, **kwargs
) -> Optional[Awaitable[None]]:
... | [
"Use this decorator to remove trailing slashes from the request path.\n\n For example, a request to ``/foo/`` would redirect to ``/foo`` with this\n decorator. Your request handler mapping should use a regular expression\n like ``r'/foo/*'`` in conjunction with using the decorator.\n "
] |
Please provide a description of the function:def authenticated(
method: Callable[..., Optional[Awaitable[None]]]
) -> Callable[..., Optional[Awaitable[None]]]:
@functools.wraps(method)
def wrapper( # type: ignore
self: RequestHandler, *args, **kwargs
) -> Optional[Awaitable[None]]:
... | [
"Decorate methods with this to require that the user be logged in.\n\n If the user is not logged in, they will be redirected to the configured\n `login url <RequestHandler.get_login_url>`.\n\n If you configure a login url with a query parameter, Tornado will\n assume you know what you're doing and use i... |
Please provide a description of the function:def on_connection_close(self) -> None:
if _has_stream_request_body(self.__class__):
if not self.request._body_future.done():
self.request._body_future.set_exception(iostream.StreamClosedError())
self.request._body_... | [
"Called in async handlers if the client closed the connection.\n\n Override this to clean up resources associated with\n long-lived connections. Note that this method is called only if\n the connection was closed during asynchronous processing; if you\n need to do cleanup after every re... |
Please provide a description of the function:def clear(self) -> None:
self._headers = httputil.HTTPHeaders(
{
"Server": "TornadoServer/%s" % tornado.version,
"Content-Type": "text/html; charset=UTF-8",
"Date": httputil.format_timestamp(time.ti... | [
"Resets all headers and content for this response."
] |
Please provide a description of the function:def set_status(self, status_code: int, reason: str = None) -> None:
self._status_code = status_code
if reason is not None:
self._reason = escape.native_str(reason)
else:
self._reason = httputil.responses.get(status_cod... | [
"Sets the status code for our response.\n\n :arg int status_code: Response status code.\n :arg str reason: Human-readable reason phrase describing the status\n code. If ``None``, it will be filled in from\n `http.client.responses` or \"Unknown\".\n\n .. versionchanged:: 5.... |
Please provide a description of the function:def set_header(self, name: str, value: _HeaderTypes) -> None:
self._headers[name] = self._convert_header_value(value) | [
"Sets the given response header name and value.\n\n All header values are converted to strings (`datetime` objects\n are formatted according to the HTTP specification for the\n ``Date`` header).\n\n "
] |
Please provide a description of the function:def add_header(self, name: str, value: _HeaderTypes) -> None:
self._headers.add(name, self._convert_header_value(value)) | [
"Adds the given response header and value.\n\n Unlike `set_header`, `add_header` may be called multiple times\n to return multiple values for the same header.\n "
] |
Please provide a description of the function:def clear_header(self, name: str) -> None:
if name in self._headers:
del self._headers[name] | [
"Clears an outgoing header, undoing a previous `set_header` call.\n\n Note that this method does not apply to multi-valued headers\n set by `add_header`.\n "
] |
Please provide a description of the function:def get_argument( # noqa: F811
self,
name: str,
default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
strip: bool = True,
) -> Optional[str]:
return self._get_argument(name, default, self.request.arguments, strip) | [
"Returns the value of the argument with the given name.\n\n If default is not provided, the argument is considered to be\n required, and we raise a `MissingArgumentError` if it is missing.\n\n If the argument appears in the request more than once, we return the\n last value.\n\n T... |
Please provide a description of the function:def get_arguments(self, name: str, strip: bool = True) -> List[str]:
# Make sure `get_arguments` isn't accidentally being called with a
# positional argument that's assumed to be a default (like in
# `get_argument`.)
assert isinstanc... | [
"Returns a list of the arguments with the given name.\n\n If the argument is not present, returns an empty list.\n\n This method searches both the query and body arguments.\n "
] |
Please provide a description of the function:def get_body_argument(
self,
name: str,
default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
strip: bool = True,
) -> Optional[str]:
return self._get_argument(name, default, self.request.body_arguments, strip) | [
"Returns the value of the argument with the given name\n from the request body.\n\n If default is not provided, the argument is considered to be\n required, and we raise a `MissingArgumentError` if it is missing.\n\n If the argument appears in the url more than once, we return the\n ... |
Please provide a description of the function:def get_body_arguments(self, name: str, strip: bool = True) -> List[str]:
return self._get_arguments(name, self.request.body_arguments, strip) | [
"Returns a list of the body arguments with the given name.\n\n If the argument is not present, returns an empty list.\n\n .. versionadded:: 3.2\n "
] |
Please provide a description of the function:def get_query_argument(
self,
name: str,
default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
strip: bool = True,
) -> Optional[str]:
return self._get_argument(name, default, self.request.query_arguments, strip) | [
"Returns the value of the argument with the given name\n from the request query string.\n\n If default is not provided, the argument is considered to be\n required, and we raise a `MissingArgumentError` if it is missing.\n\n If the argument appears in the url more than once, we return th... |
Please provide a description of the function:def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
return self._get_arguments(name, self.request.query_arguments, strip) | [
"Returns a list of the query arguments with the given name.\n\n If the argument is not present, returns an empty list.\n\n .. versionadded:: 3.2\n "
] |
Please provide a description of the function:def decode_argument(self, value: bytes, name: str = None) -> str:
try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(
400, "Invalid unicode in %s: %r" % (name or "url", value[:40])
... | [
"Decodes an argument from the request.\n\n The argument has been percent-decoded and is now a byte string.\n By default, this method decodes the argument as utf-8 and returns\n a unicode string, but this may be overridden in subclasses.\n\n This method is used as a filter for both `get_a... |
Please provide a description of the function:def cookies(self) -> Dict[str, http.cookies.Morsel]:
return self.request.cookies | [
"An alias for\n `self.request.cookies <.httputil.HTTPServerRequest.cookies>`."
] |
Please provide a description of the function:def get_cookie(self, name: str, default: str = None) -> Optional[str]:
if self.request.cookies is not None and name in self.request.cookies:
return self.request.cookies[name].value
return default | [
"Returns the value of the request cookie with the given name.\n\n If the named cookie is not present, returns ``default``.\n\n This method only returns cookies that were present in the request.\n It does not see the outgoing cookies set by `set_cookie` in this\n handler.\n "
] |
Please provide a description of the function:def set_cookie(
self,
name: str,
value: Union[str, bytes],
domain: str = None,
expires: Union[float, Tuple, datetime.datetime] = None,
path: str = "/",
expires_days: int = None,
**kwargs: Any
) -> None:
... | [
"Sets an outgoing cookie name/value with the given options.\n\n Newly-set cookies are not immediately visible via `get_cookie`;\n they are not present until the next request.\n\n expires may be a numeric timestamp as returned by `time.time`,\n a time tuple as returned by `time.gmtime`, o... |
Please provide a description of the function:def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None:
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires, domain=domain) | [
"Deletes the cookie with the given name.\n\n Due to limitations of the cookie protocol, you must pass the same\n path and domain to clear a cookie as were used when that cookie\n was set (but there is no way to find out on the server side\n which values were used for a given cookie).\n\n... |
Please provide a description of the function:def clear_all_cookies(self, path: str = "/", domain: str = None) -> None:
for name in self.request.cookies:
self.clear_cookie(name, path=path, domain=domain) | [
"Deletes all the cookies the user sent with this request.\n\n See `clear_cookie` for more information on the path and domain\n parameters.\n\n Similar to `set_cookie`, the effect of this method will not be\n seen until the following request.\n\n .. versionchanged:: 3.2\n\n ... |
Please provide a description of the function:def set_secure_cookie(
self,
name: str,
value: Union[str, bytes],
expires_days: int = 30,
version: int = None,
**kwargs: Any
) -> None:
self.set_cookie(
name,
self.create_signed_valu... | [
"Signs and timestamps a cookie so it cannot be forged.\n\n You must specify the ``cookie_secret`` setting in your Application\n to use this method. It should be a long, random sequence of bytes\n to be used as the HMAC secret for the signature.\n\n To read a cookie set with this method, ... |
Please provide a description of the function:def create_signed_value(
self, name: str, value: Union[str, bytes], version: int = None
) -> bytes:
self.require_setting("cookie_secret", "secure cookies")
secret = self.application.settings["cookie_secret"]
key_version = None
... | [
"Signs and timestamps a string so it cannot be forged.\n\n Normally used via set_secure_cookie, but provided as a separate\n method for non-cookie uses. To decode a value not stored\n as a cookie use the optional value argument to get_secure_cookie.\n\n .. versionchanged:: 3.2.1\n\n ... |
Please provide a description of the function:def get_secure_cookie(
self,
name: str,
value: str = None,
max_age_days: int = 31,
min_version: int = None,
) -> Optional[bytes]:
self.require_setting("cookie_secret", "secure cookies")
if value is None:
... | [
"Returns the given signed cookie if it validates, or None.\n\n The decoded cookie value is returned as a byte string (unlike\n `get_cookie`).\n\n Similar to `get_cookie`, this method only returns cookies that\n were present in the request. It does not see outgoing cookies set by\n ... |
Please provide a description of the function:def get_secure_cookie_key_version(
self, name: str, value: str = None
) -> Optional[int]:
self.require_setting("cookie_secret", "secure cookies")
if value is None:
value = self.get_cookie(name)
if value is None:
... | [
"Returns the signing key version of the secure cookie.\n\n The version is returned as int.\n "
] |
Please provide a description of the function:def redirect(self, url: str, permanent: bool = False, status: int = None) -> None:
if self._headers_written:
raise Exception("Cannot redirect after headers have been written")
if status is None:
status = 301 if permanent else ... | [
"Sends a redirect to the given (optionally relative) URL.\n\n If the ``status`` argument is specified, that value is used as the\n HTTP status code; otherwise either 301 (permanent) or 302\n (temporary) is chosen based on the ``permanent`` argument.\n The default is 302 (temporary).\n ... |
Please provide a description of the function:def write(self, chunk: Union[str, bytes, dict]) -> None:
if self._finished:
raise RuntimeError("Cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unic... | [
"Writes the given chunk to the output buffer.\n\n To write the output to the network, use the `flush()` method below.\n\n If the given chunk is a dictionary, we write it as JSON and set\n the Content-Type of the response to be ``application/json``.\n (if you want to send JSON as a differ... |
Please provide a description of the function:def render(self, template_name: str, **kwargs: Any) -> "Future[None]":
if self._finished:
raise RuntimeError("Cannot render() after finish()")
html = self.render_string(template_name, **kwargs)
# Insert the additional JS and CSS ... | [
"Renders the template with the given arguments as the response.\n\n ``render()`` calls ``finish()``, so no other output methods can be called\n after it.\n\n Returns a `.Future` with the same semantics as the one returned by `finish`.\n Awaiting this `.Future` is optional.\n\n .. ... |
Please provide a description of the function:def render_linked_js(self, js_files: Iterable[str]) -> str:
paths = []
unique_paths = set() # type: Set[str]
for path in js_files:
if not is_absolute(path):
path = self.static_url(path)
if path not in... | [
"Default method used to render the final js links for the\n rendered webpage.\n\n Override this method in a sub-classed controller to change the output.\n "
] |
Please provide a description of the function:def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes:
return (
b'<script type="text/javascript">\n//<![CDATA[\n'
+ b"\n".join(js_embed)
+ b"\n//]]>\n</script>"
) | [
"Default method used to render the final embedded js for the\n rendered webpage.\n\n Override this method in a sub-classed controller to change the output.\n "
] |
Please provide a description of the function:def render_linked_css(self, css_files: Iterable[str]) -> str:
paths = []
unique_paths = set() # type: Set[str]
for path in css_files:
if not is_absolute(path):
path = self.static_url(path)
if path not... | [
"Default method used to render the final css links for the\n rendered webpage.\n\n Override this method in a sub-classed controller to change the output.\n "
] |
Please provide a description of the function:def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes:
return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>" | [
"Default method used to render the final embedded css for the\n rendered webpage.\n\n Override this method in a sub-classed controller to change the output.\n "
] |
Please provide a description of the function:def render_string(self, template_name: str, **kwargs: Any) -> bytes:
# If no template_path is specified, use the path of the calling file
template_path = self.get_template_path()
if not template_path:
frame = sys._getframe(0)
... | [
"Generate the given template with the given arguments.\n\n We return the generated byte string (in utf8). To generate and\n write a template as a response, use render() above.\n "
] |
Please provide a description of the function:def get_template_namespace(self) -> Dict[str, Any]:
namespace = dict(
handler=self,
request=self.request,
current_user=self.current_user,
locale=self.locale,
_=self.locale.translate,
pge... | [
"Returns a dictionary to be used as the default template namespace.\n\n May be overridden by subclasses to add or modify values.\n\n The results of this method will be combined with additional\n defaults in the `tornado.template` module and keyword arguments\n to `render` or `render_stri... |
Please provide a description of the function:def create_template_loader(self, template_path: str) -> template.BaseLoader:
settings = self.application.settings
if "template_loader" in settings:
return settings["template_loader"]
kwargs = {}
if "autoescape" in settings... | [
"Returns a new template loader for the given path.\n\n May be overridden by subclasses. By default returns a\n directory-based loader on the given path, using the\n ``autoescape`` and ``template_whitespace`` application\n settings. If a ``template_loader`` application setting is\n ... |
Please provide a description of the function:def flush(self, include_footers: bool = False) -> "Future[None]":
assert self.request.connection is not None
chunk = b"".join(self._write_buffer)
self._write_buffer = []
if not self._headers_written:
self._headers_written ... | [
"Flushes the current output buffer to the network.\n\n The ``callback`` argument, if given, can be used for flow control:\n it will be run when all flushed data has been written to the socket.\n Note that only one flush callback can be outstanding at a time;\n if another flush occurs bef... |
Please provide a description of the function:def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]":
if self._finished:
raise RuntimeError("finish() called twice")
if chunk is not None:
self.write(chunk)
# Automatically support ETags and add ... | [
"Finishes this response, ending the HTTP request.\n\n Passing a ``chunk`` to ``finish()`` is equivalent to passing that\n chunk to ``write()`` and then calling ``finish()`` with no arguments.\n\n Returns a `.Future` which may optionally be awaited to track the sending\n of the response t... |
Please provide a description of the function:def detach(self) -> iostream.IOStream:
self._finished = True
# TODO: add detach to HTTPConnection?
return self.request.connection.detach() | [
"Take control of the underlying stream.\n\n Returns the underlying `.IOStream` object and stops all\n further HTTP processing. Intended for implementing protocols\n like websockets that tunnel over an HTTP handshake.\n\n This method is only supported when HTTP/1.1 is used.\n\n .. ... |
Please provide a description of the function:def send_error(self, status_code: int = 500, **kwargs: Any) -> None:
if self._headers_written:
gen_log.error("Cannot send error response after headers written")
if not self._finished:
# If we get an error between writi... | [
"Sends the given HTTP error code to the browser.\n\n If `flush()` has already been called, it is not possible to send\n an error, so this method will simply terminate the response.\n If output has been written but not yet flushed, it will be discarded\n and replaced with the error page.\... |
Please provide a description of the function:def write_error(self, status_code: int, **kwargs: Any) -> None:
if self.settings.get("serve_traceback") and "exc_info" in kwargs:
# in debug mode, try to send a traceback
self.set_header("Content-Type", "text/plain")
for l... | [
"Override to implement custom error pages.\n\n ``write_error`` may call `write`, `render`, `set_header`, etc\n to produce output as usual.\n\n If this error was caused by an uncaught exception (including\n HTTPError), an ``exc_info`` triple will be available as\n ``kwargs[\"exc_in... |
Please provide a description of the function:def locale(self) -> tornado.locale.Locale:
if not hasattr(self, "_locale"):
loc = self.get_user_locale()
if loc is not None:
self._locale = loc
else:
self._locale = self.get_browser_locale()... | [
"The locale for the current session.\n\n Determined by either `get_user_locale`, which you can override to\n set the locale based on, e.g., a user preference stored in a\n database, or `get_browser_locale`, which uses the ``Accept-Language``\n header.\n\n .. versionchanged: 4.1\n ... |
Please provide a description of the function:def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in langu... | [
"Determines the user's locale from ``Accept-Language`` header.\n\n See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4\n "
] |
Please provide a description of the function:def current_user(self) -> Any:
if not hasattr(self, "_current_user"):
self._current_user = self.get_current_user()
return self._current_user | [
"The authenticated user for this request.\n\n This is set in one of two ways:\n\n * A subclass may override `get_current_user()`, which will be called\n automatically the first time ``self.current_user`` is accessed.\n `get_current_user()` will only be called once per request,\n ... |
Please provide a description of the function:def xsrf_token(self) -> bytes:
if not hasattr(self, "_xsrf_token"):
version, token, timestamp = self._get_raw_xsrf_token()
output_version = self.settings.get("xsrf_cookie_version", 2)
cookie_kwargs = self.settings.get("xsr... | [
"The XSRF-prevention token for the current user/session.\n\n To prevent cross-site request forgery, we set an '_xsrf' cookie\n and include the same '_xsrf' value as an argument with all POST\n requests. If the two do not match, we reject the form submission\n as a potential forgery.\n\n ... |
Please provide a description of the function:def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]:
if not hasattr(self, "_raw_xsrf_token"):
cookie = self.get_cookie("_xsrf")
if cookie:
version, token, timestamp = self._decode_xsrf_token(cookie)
... | [
"Read or generate the xsrf token in its raw form.\n\n The raw_xsrf_token is a tuple containing:\n\n * version: the version of the cookie from which this token was read,\n or None if we generated a new token in this request.\n * token: the raw token data; random (non-ascii) bytes.\n ... |
Please provide a description of the function:def _decode_xsrf_token(
self, cookie: str
) -> Tuple[Optional[int], Optional[bytes], Optional[float]]:
try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
version = int(m.group(1))
... | [
"Convert a cookie string into a the tuple form returned by\n _get_raw_xsrf_token.\n "
] |
Please provide a description of the function: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
... | [
"Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.\n\n To prevent cross-site request forgery, we set an ``_xsrf``\n cookie and include the same value as a non-cookie\n field with all ``POST`` requests. If the two do not match, we\n reject the form submission as a potenti... |
Please provide a description of the function:def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str:
self.require_setting("static_path", "static_url")
get_url = self.settings.get(
"static_handler_class", StaticFileHandler
).make_static_url
... | [
"Returns a static URL for the given relative static file path.\n\n This method requires you set the ``static_path`` setting in your\n application (which specifies the root directory of your static\n files).\n\n This method returns a versioned url (by default appending\n ``?v=<sign... |
Please provide a description of the function:def require_setting(self, name: str, feature: str = "this feature") -> None:
if not self.application.settings.get(name):
raise Exception(
"You must define the '%s' setting in your "
"application to use %s" % (name,... | [
"Raises an exception if the given app setting is not defined."
] |
Please provide a description of the function:def reverse_url(self, name: str, *args: Any) -> str:
return self.application.reverse_url(name, *args) | [
"Alias for `Application.reverse_url`."
] |
Please provide a description of the function:def compute_etag(self) -> Optional[str]:
hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
return '"%s"' % hasher.hexdigest() | [
"Computes the etag header to be used for this request.\n\n By default uses a hash of the content written so far.\n\n May be overridden to provide custom etag implementations,\n or may return None to disable tornado's default etag support.\n "
] |
Please provide a description of the function: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 allows multiple etag values in a single header.
etags = re.fi... | [
"Checks the ``Etag`` header against requests's ``If-None-Match``.\n\n Returns ``True`` if the request's Etag matches and a 304 should be\n returned. For example::\n\n self.set_etag_header()\n if self.check_etag_header():\n self.set_status(304)\n retu... |
Please provide a description of the function:async def _execute(
self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes
) -> None:
self._transforms = transforms
try:
if self.request.method not in self.SUPPORTED_METHODS:
raise HTTPError(4... | [
"Executes this request with the given output transforms."
] |
Please provide a description of the function:def log_exception(
self,
typ: "Optional[Type[BaseException]]",
value: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
if isinstance(value, HTTPError):
if value.log_message:
form... | [
"Override to customize logging of uncaught exceptions.\n\n By default logs instances of `HTTPError` as warnings without\n stack traces (on the ``tornado.general`` logger), and all\n other exceptions as errors with stack traces (on the\n ``tornado.application`` logger).\n\n .. vers... |
Please provide a description of the function:def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer:
server = HTTPServer(self, **kwargs)
server.listen(port, address)
return server | [
"Starts an HTTP server for this application on the given port.\n\n This is a convenience alias for creating an `.HTTPServer`\n object and calling its listen method. Keyword arguments not\n supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the\n `.HTTPServer` constructor... |
Please provide a description of the function:def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None:
host_matcher = HostMatches(host_pattern)
rule = Rule(host_matcher, _ApplicationRouter(self, host_handlers))
self.default_router.rules.insert(-1, rule)
if s... | [
"Appends the given handlers to our handler list.\n\n Host patterns are processed sequentially in the order they were\n added. All matching patterns will be considered.\n "
] |
Please provide a description of the function: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,
) -> "_Hand... | [
"Returns `~.httputil.HTTPMessageDelegate` that can serve a request\n for application and `RequestHandler` subclass.\n\n :arg httputil.HTTPServerRequest request: current HTTP request.\n :arg RequestHandler target_class: a `RequestHandler` class.\n :arg dict target_kwargs: keyword argument... |
Please provide a description of the function:def reverse_url(self, name: str, *args: Any) -> str:
reversed_url = self.default_router.reverse_url(name, *args)
if reversed_url is not None:
return reversed_url
raise KeyError("%s not found in named urls" % name) | [
"Returns a URL path for handler named ``name``\n\n The handler must be added to the application as a named `URLSpec`.\n\n Args will be substituted for capturing groups in the `URLSpec` regex.\n They will be converted to strings if necessary, encoded as utf8,\n and url-escaped.\n "... |
Please provide a description of the function:def log_request(self, handler: RequestHandler) -> None:
if "log_function" in self.settings:
self.settings["log_function"](handler)
return
if handler.get_status() < 400:
log_method = access_log.info
elif han... | [
"Writes a completed HTTP request to the logs.\n\n By default writes to the python root logger. To change\n this behavior either subclass Application and override this method,\n or pass a function in the application settings dictionary as\n ``log_function``.\n "
] |
Please provide a description of the function:def compute_etag(self) -> Optional[str]:
assert self.absolute_path is not None
version_hash = self._get_cached_version(self.absolute_path)
if not version_hash:
return None
return '"%s"' % (version_hash,) | [
"Sets the ``Etag`` header based on static url version.\n\n This allows efficient ``If-None-Match`` checks against cached\n versions, and sends the correct ``Etag`` for a partial response\n (i.e. the same ``Etag`` as the full file).\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def set_headers(self) -> None:
self.set_header("Accept-Ranges", "bytes")
self.set_etag_header()
if self.modified is not None:
self.set_header("Last-Modified", self.modified)
content_type = self.get_content_type()
... | [
"Sets the content and caching headers on the response.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function: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()
# Check the If-Modified-Since, and don't send the... | [
"Returns True if the headers indicate that we should return 304.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def get_absolute_path(cls, root: str, path: str) -> str:
abspath = os.path.abspath(os.path.join(root, path))
return abspath | [
"Returns the absolute location of ``path`` relative to ``root``.\n\n ``root`` is the path configured for this `StaticFileHandler`\n (in most cases the ``static_path`` `Application` setting).\n\n This class method may be overridden in subclasses. By default\n it returns a filesystem path... |
Please provide a description of the function: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 named `root` instead of files starting with
... | [
"Validate and return the absolute path.\n\n ``root`` is the configured path for the `StaticFileHandler`,\n and ``path`` is the result of `get_absolute_path`\n\n This is an instance method called during request processing,\n so it may raise `HTTPError` or use methods like\n `Reques... |
Please provide a description of the function:def get_content(
cls, abspath: str, start: int = None, end: int = None
) -> Generator[bytes, None, None]:
with open(abspath, "rb") as file:
if start is not None:
file.seek(start)
if end is not None:
... | [
"Retrieve the content of the requested resource which is located\n at the given absolute path.\n\n This class method may be overridden by subclasses. Note that its\n signature is different from other overridable class methods\n (no ``settings`` argument); this is deliberate to ensure th... |
Please provide a description of the function:def get_content_version(cls, abspath: str) -> str:
data = cls.get_content(abspath)
hasher = hashlib.md5()
if isinstance(data, bytes):
hasher.update(data)
else:
for chunk in data:
hasher.update(c... | [
"Returns a version string for the resource at the given path.\n\n This class method may be overridden by subclasses. The\n default implementation is a hash of the file's contents.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function: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 timestamp. It
# was changed from that f... | [
"Returns the time that ``self.absolute_path`` was last modified.\n\n May be overridden in subclasses. Should return a `~datetime.datetime`\n object or None.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function: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 appropriate type for a gzip compressed file
if encoding == "gzip":
... | [
"Returns the ``Content-Type`` header to be used for this request.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def get_cache_time(
self, path: str, modified: Optional[datetime.datetime], mime_type: str
) -> int:
return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0 | [
"Override to customize cache control behavior.\n\n Return a positive number of seconds to make the result\n cacheable for that amount of time or 0 to mark resource as\n cacheable for an unspecified amount of time (subject to\n browser heuristics).\n\n By default returns cache expi... |
Please provide a description of the function:def make_static_url(
cls, settings: Dict[str, Any], path: str, include_version: bool = True
) -> str:
url = settings.get("static_url_prefix", "/static/") + path
if not include_version:
return url
version_hash = cls.ge... | [
"Constructs a versioned url for the given path.\n\n This method may be overridden in subclasses (but note that it\n is a class method rather than an instance method). Subclasses\n are only required to implement the signature\n ``make_static_url(cls, settings, path)``; other keyword\n ... |
Please provide a description of the function:def parse_url_path(self, url_path: str) -> str:
if os.path.sep != "/":
url_path = url_path.replace("/", os.path.sep)
return url_path | [
"Converts a static URL path into a filesystem path.\n\n ``url_path`` is the path component of the URL with\n ``static_url_prefix`` removed. The return value should be\n filesystem path relative to ``static_path``.\n\n This is the inverse of `make_static_url`.\n "
] |
Please provide a description of the function:def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
abs_path = cls.get_absolute_path(settings["static_path"], path)
return cls._get_cached_version(abs_path) | [
"Generate the version string to be used in static URLs.\n\n ``settings`` is the `Application.settings` dictionary and ``path``\n is the relative location of the requested asset on the filesystem.\n The returned value should be a string, or ``None`` if no version\n could be determined.\n\... |
Please provide a description of the function: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."
] |
Please provide a description of the function:def xhtml_escape(value: Union[str, bytes]) -> str:
return _XHTML_ESCAPE_RE.sub(
lambda match: _XHTML_ESCAPE_DICT[match.group(0)], to_basestring(value)
) | [
"Escapes a string so it is valid within HTML or XML.\n\n Escapes the characters ``<``, ``>``, ``\"``, ``'``, and ``&``.\n When used in attribute values the escaped strings must be enclosed\n in quotes.\n\n .. versionchanged:: 3.2\n\n Added the single quote to the list of escaped characters.\n "... |
Please provide a description of the function:def xhtml_unescape(value: Union[str, bytes]) -> str:
return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value)) | [
"Un-escapes an XML-escaped string."
] |
Please provide a description of the function:def json_decode(value: Union[str, bytes]) -> Any:
return json.loads(to_basestring(value)) | [
"Returns Python objects for the given JSON string.\n\n Supports both `str` and `bytes` inputs.\n "
] |
Please provide a description of the function:def url_escape(value: Union[str, bytes], plus: bool = True) -> str:
quote = urllib.parse.quote_plus if plus else urllib.parse.quote
return quote(utf8(value)) | [
"Returns a URL-encoded version of the given value.\n\n If ``plus`` is true (the default), spaces will be represented\n as \"+\" instead of \"%20\". This is appropriate for query strings\n but not for the path component of a URL. Note that this default\n is the reverse of Python's urllib module.\n\n ... |
Please provide a description of the function:def url_unescape( # noqa: F811
value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True
) -> Union[str, bytes]:
if encoding is None:
if plus:
# unquote_to_bytes doesn't have a _plus variant
value = to_basest... | [
"Decodes the given value from a URL.\n\n The argument may be either a byte or unicode string.\n\n If encoding is None, the result will be a byte string. Otherwise,\n the result is a unicode string in the specified encoding.\n\n If ``plus`` is true (the default), plus signs will be interpreted\n as s... |
Please provide a description of the function:def parse_qs_bytes(
qs: str, keep_blank_values: bool = False, strict_parsing: bool = False
) -> Dict[str, List[bytes]]:
# This is gross, but python3 doesn't give us another way.
# Latin1 is the universal donor of character encodings.
result = urllib.pars... | [
"Parses a query string like urlparse.parse_qs, but returns the\n values as byte strings.\n\n Keys still become type str (interpreted as latin1 in python3!)\n because it's too painful to keep them as byte strings in\n python3 and in practice they're nearly always ascii anyway.\n "
] |
Please provide a description of the function:def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811
if isinstance(value, _UTF8_TYPES):
return value
if not isinstance(value, unicode_type):
raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
retur... | [
"Converts a string argument to a byte string.\n\n If the argument is already a byte string or None, it is returned unchanged.\n Otherwise it must be a unicode string and is encoded as utf8.\n "
] |
Please provide a description of the function:def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(value, bytes):
raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
re... | [
"Converts a string argument to a unicode string.\n\n If the argument is already a unicode string or None, it is returned\n unchanged. Otherwise it must be a byte string and is decoded as utf8.\n "
] |
Please provide a description of the function:def recursive_unicode(obj: Any) -> Any:
if isinstance(obj, dict):
return dict(
(recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
)
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)... | [
"Walks a simple data structure, converting byte strings to unicode.\n\n Supports lists, tuples, and dictionaries.\n "
] |
Please provide a description of the function: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:
if extra_params and not callable(extra... | [
"Converts plain text into HTML with links.\n\n For example: ``linkify(\"Hello http://tornadoweb.org!\")`` would return\n ``Hello <a href=\"http://tornadoweb.org\">http://tornadoweb.org</a>!``\n\n Parameters:\n\n * ``shorten``: Long urls will be shortened for display.\n\n * ``extra_params``: Extra tex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.