partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
main
Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`.
tornado/autoreload.py
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ # Remember that we were launched with autoreload as main. # The main module can be tricky; set the variables both in our globals # (which may be __main__) and the real importable version. import tornado.autoreload global _autoreload_is_main global _original_argv, _original_spec tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv tornado.autoreload._original_argv = _original_argv = original_argv original_spec = getattr(sys.modules["__main__"], "__spec__", None) tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" module = sys.argv[2] del sys.argv[1:3] elif len(sys.argv) >= 2: mode = "script" script = sys.argv[1] sys.argv = sys.argv[1:] else: print(_USAGE, file=sys.stderr) sys.exit(1) try: if mode == "module": import runpy runpy.run_module(module, run_name="__main__", alter_sys=True) elif mode == "script": with open(script) as f: # Execute the script in our namespace instead of creating # a new one so that something that tries to import __main__ # (e.g. the unittest module) will see names defined in the # script instead of just those defined in this module. global __file__ __file__ = script # If __package__ is defined, imports may be incorrectly # interpreted as relative to this module. global __package__ del __package__ exec_in(f.read(), globals(), globals()) except SystemExit as e: logging.basicConfig() gen_log.info("Script exited with status %s", e.code) except Exception as e: logging.basicConfig() gen_log.warning("Script exited with uncaught exception", exc_info=True) # If an exception occurred at import time, the file with the error # never made it into sys.modules and so we won't know to watch it. # Just to make sure we've covered everything, walk the stack trace # from the exception and watch every file. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]): watch(filename) if isinstance(e, SyntaxError): # SyntaxErrors are special: their innermost stack frame is fake # so extract_tb won't see it and we have to get the filename # from the exception object. watch(e.filename) else: logging.basicConfig() gen_log.info("Script exited normally") # restore sys.argv so subsequent executions will include autoreload sys.argv = original_argv if mode == "module": # runpy did a fake import of the module as __main__, but now it's # no longer in sys.modules. Figure out where it is and watch it. loader = pkgutil.get_loader(module) if loader is not None: watch(loader.get_filename()) # type: ignore wait()
def main() -> None: """Command-line wrapper to re-run a script whenever its source changes. Scripts may be specified by filename or module name:: python -m tornado.autoreload -m tornado.test.runtests python -m tornado.autoreload tornado/test/runtests.py Running a script with this wrapper is similar to calling `tornado.autoreload.wait` at the end of the script, but this wrapper can catch import-time problems like syntax errors that would otherwise prevent the script from reaching its call to `wait`. """ # Remember that we were launched with autoreload as main. # The main module can be tricky; set the variables both in our globals # (which may be __main__) and the real importable version. import tornado.autoreload global _autoreload_is_main global _original_argv, _original_spec tornado.autoreload._autoreload_is_main = _autoreload_is_main = True original_argv = sys.argv tornado.autoreload._original_argv = _original_argv = original_argv original_spec = getattr(sys.modules["__main__"], "__spec__", None) tornado.autoreload._original_spec = _original_spec = original_spec sys.argv = sys.argv[:] if len(sys.argv) >= 3 and sys.argv[1] == "-m": mode = "module" module = sys.argv[2] del sys.argv[1:3] elif len(sys.argv) >= 2: mode = "script" script = sys.argv[1] sys.argv = sys.argv[1:] else: print(_USAGE, file=sys.stderr) sys.exit(1) try: if mode == "module": import runpy runpy.run_module(module, run_name="__main__", alter_sys=True) elif mode == "script": with open(script) as f: # Execute the script in our namespace instead of creating # a new one so that something that tries to import __main__ # (e.g. the unittest module) will see names defined in the # script instead of just those defined in this module. global __file__ __file__ = script # If __package__ is defined, imports may be incorrectly # interpreted as relative to this module. global __package__ del __package__ exec_in(f.read(), globals(), globals()) except SystemExit as e: logging.basicConfig() gen_log.info("Script exited with status %s", e.code) except Exception as e: logging.basicConfig() gen_log.warning("Script exited with uncaught exception", exc_info=True) # If an exception occurred at import time, the file with the error # never made it into sys.modules and so we won't know to watch it. # Just to make sure we've covered everything, walk the stack trace # from the exception and watch every file. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]): watch(filename) if isinstance(e, SyntaxError): # SyntaxErrors are special: their innermost stack frame is fake # so extract_tb won't see it and we have to get the filename # from the exception object. watch(e.filename) else: logging.basicConfig() gen_log.info("Script exited normally") # restore sys.argv so subsequent executions will include autoreload sys.argv = original_argv if mode == "module": # runpy did a fake import of the module as __main__, but now it's # no longer in sys.modules. Figure out where it is and watch it. loader = pkgutil.get_loader(module) if loader is not None: watch(loader.get_filename()) # type: ignore wait()
[ "Command", "-", "line", "wrapper", "to", "re", "-", "run", "a", "script", "whenever", "its", "source", "changes", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/autoreload.py#L272-L358
[ "def", "main", "(", ")", "->", "None", ":", "# Remember that we were launched with autoreload as main.", "# The main module can be tricky; set the variables both in our globals", "# (which may be __main__) and the real importable version.", "import", "tornado", ".", "autoreload", "global...
b8b481770bcdb333a69afde5cce7eaa449128326
train
_Connector.split
Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families).
tornado/tcpclient.py
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """ primary = [] secondary = [] primary_af = addrinfo[0][0] for af, addr in addrinfo: if af == primary_af: primary.append((af, addr)) else: secondary.append((af, addr)) return primary, secondary
def split( addrinfo: List[Tuple] ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """ primary = [] secondary = [] primary_af = addrinfo[0][0] for af, addr in addrinfo: if af == primary_af: primary.append((af, addr)) else: secondary.append((af, addr)) return primary, secondary
[ "Partition", "the", "addrinfo", "list", "by", "address", "family", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L81-L103
[ "def", "split", "(", "addrinfo", ":", "List", "[", "Tuple", "]", ")", "->", "Tuple", "[", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple", "]", "]", ",", "List", "[", "Tuple", "[", "socket", ".", "AddressFamily", ",", "Tuple",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
TCPClient.connect
Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `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`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument.
tornado/tcpclient.py
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float, datetime.timedelta] = None, ) -> IOStream: """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `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`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument. """ if timeout is not None: if isinstance(timeout, numbers.Real): timeout = IOLoop.current().time() + timeout elif isinstance(timeout, datetime.timedelta): timeout = IOLoop.current().time() + timeout.total_seconds() else: raise TypeError("Unsupported timeout %r" % timeout) if timeout is not None: addrinfo = await gen.with_timeout( timeout, self.resolver.resolve(host, port, af) ) else: addrinfo = await self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, functools.partial( self._create_stream, max_buffer_size, source_ip=source_ip, source_port=source_port, ), ) af, addr, stream = await connector.start(connect_timeout=timeout) # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: if timeout is not None: stream = await gen.with_timeout( timeout, stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ), ) else: stream = await stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ) return stream
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, max_buffer_size: int = None, source_ip: str = None, source_port: int = None, timeout: Union[float, datetime.timedelta] = None, ) -> IOStream: """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handled outside of Tornado as this depends very much on the platform. Raises `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`) Similarly, when the user requires a certain source port, it can be specified using the ``source_port`` arg. .. versionchanged:: 4.5 Added the ``source_ip`` and ``source_port`` arguments. .. versionchanged:: 5.0 Added the ``timeout`` argument. """ if timeout is not None: if isinstance(timeout, numbers.Real): timeout = IOLoop.current().time() + timeout elif isinstance(timeout, datetime.timedelta): timeout = IOLoop.current().time() + timeout.total_seconds() else: raise TypeError("Unsupported timeout %r" % timeout) if timeout is not None: addrinfo = await gen.with_timeout( timeout, self.resolver.resolve(host, port, af) ) else: addrinfo = await self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, functools.partial( self._create_stream, max_buffer_size, source_ip=source_ip, source_port=source_port, ), ) af, addr, stream = await connector.start(connect_timeout=timeout) # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: if timeout is not None: stream = await gen.with_timeout( timeout, stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ), ) else: stream = await stream.start_tls( False, ssl_options=ssl_options, server_hostname=host ) return stream
[ "Connect", "to", "the", "given", "host", "and", "port", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/tcpclient.py#L222-L296
[ "async", "def", "connect", "(", "self", ",", "host", ":", "str", ",", "port", ":", "int", ",", "af", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
HTTPServer.close_all_connections
Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``.
tornado/httpserver.py
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``. """ while self._connections: # Peek at an arbitrary element of the set conn = next(iter(self._connections)) await conn.close()
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop accepting new connections, then ``await close_all_connections()`` to wait for existing connections to finish. This method does not currently close open websocket connections. Note that this method is a coroutine and must be caled with ``await``. """ while self._connections: # Peek at an arbitrary element of the set conn = next(iter(self._connections)) await conn.close()
[ "Close", "all", "open", "connections", "and", "asynchronously", "wait", "for", "them", "to", "finish", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L204-L221
[ "async", "def", "close_all_connections", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_connections", ":", "# Peek at an arbitrary element of the set", "conn", "=", "next", "(", "iter", "(", "self", ".", "_connections", ")", ")", "await", "conn", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
_HTTPRequestContext._apply_xheaders
Rewrite the ``remote_ip`` and ``protocol`` fields.
tornado/httpserver.py
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list for ip in (cand.strip() for cand in reversed(ip.split(","))): if ip not in self.trusted_downstream: break ip = headers.get("X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto_header = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", self.protocol) ) if proto_header: # use only the last proto entry if there is more than one # TODO: support trusting mutiple layers of proxied protocol proto_header = proto_header.split(",")[-1].strip() if proto_header in ("http", "https"): self.protocol = proto_header
def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None: """Rewrite the ``remote_ip`` and ``protocol`` fields.""" # Squid uses X-Forwarded-For, others use X-Real-Ip ip = headers.get("X-Forwarded-For", self.remote_ip) # Skip trusted downstream hosts in X-Forwarded-For list for ip in (cand.strip() for cand in reversed(ip.split(","))): if ip not in self.trusted_downstream: break ip = headers.get("X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto_header = headers.get( "X-Scheme", headers.get("X-Forwarded-Proto", self.protocol) ) if proto_header: # use only the last proto entry if there is more than one # TODO: support trusting mutiple layers of proxied protocol proto_header = proto_header.split(",")[-1].strip() if proto_header in ("http", "https"): self.protocol = proto_header
[ "Rewrite", "the", "remote_ip", "and", "protocol", "fields", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L332-L352
[ "def", "_apply_xheaders", "(", "self", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ")", "->", "None", ":", "# Squid uses X-Forwarded-For, others use X-Real-Ip", "ip", "=", "headers", ".", "get", "(", "\"X-Forwarded-For\"", ",", "self", ".", "remote_ip", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
_HTTPRequestContext._unapply_xheaders
Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection.
tornado/httpserver.py
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
def _unapply_xheaders(self) -> None: """Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection. """ self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
[ "Undo", "changes", "from", "_apply_xheaders", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httpserver.py#L354-L361
[ "def", "_unapply_xheaders", "(", "self", ")", "->", "None", ":", "self", ".", "remote_ip", "=", "self", ".", "_orig_remote_ip", "self", ".", "protocol", "=", "self", ".", "_orig_protocol" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
set_default_locale
Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale.
tornado/locale.py
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale. """ global _default_locale global _supported_locales _default_locale = code _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale. """ global _default_locale global _supported_locales _default_locale = code _supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
[ "Sets", "the", "default", "locale", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L77-L88
[ "def", "set_default_locale", "(", "code", ":", "str", ")", "->", "None", ":", "global", "_default_locale", "global", "_supported_locales", "_default_locale", "=", "code", "_supported_locales", "=", "frozenset", "(", "list", "(", "_translations", ".", "keys", "(", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
load_translations
Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM.
tornado/locale.py
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM. """ global _translations global _supported_locales _translations = {} for path in os.listdir(directory): if not path.endswith(".csv"): continue locale, extension = path.split(".") if not re.match("[a-z]+(_[A-Z]+)?$", locale): gen_log.error( "Unrecognized locale %r (path: %s)", locale, os.path.join(directory, path), ) continue full_path = os.path.join(directory, path) if encoding is None: # Try to autodetect encoding based on the BOM. with open(full_path, "rb") as bf: data = bf.read(len(codecs.BOM_UTF16_LE)) if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): encoding = "utf-16" else: # utf-8-sig is "utf-8 with optional BOM". It's discouraged # in most cases but is common with CSV files because Excel # cannot read utf-8 files without a BOM. encoding = "utf-8-sig" # python 3: csv.reader requires a file open in text mode. # Specify an encoding to avoid dependence on $LANG environment variable. with open(full_path, encoding=encoding) as f: _translations[locale] = {} for i, row in enumerate(csv.reader(f)): if not row or len(row) < 2: continue row = [escape.to_unicode(c).strip() for c in row] english, translation = row[:2] if len(row) > 2: plural = row[2] or "unknown" else: plural = "unknown" if plural not in ("plural", "singular", "unknown"): gen_log.error( "Unrecognized plural indicator %r in %s line %d", plural, path, i + 1, ) continue _translations[locale].setdefault(plural, {})[english] = translation _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) gen_log.debug("Supported locales: %s", sorted(_supported_locales))
def load_translations(directory: str, encoding: str = None) -> None: """Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three columns: string, translation, and an optional plural indicator. Plural indicators should be one of "plural" or "singular". A given string can have both singular and plural forms. For example ``%(name)s liked this`` may have a different verb conjugation depending on whether %(name)s is one name or a list of names. There should be two rows in the CSV file for that string, one with plural indicator "singular", and one "plural". For strings with no verbs that would change on translation, simply use "unknown" or the empty string (or don't include the column at all). The file is read using the `csv` module in the default "excel" dialect. In this format there should not be spaces after the commas. If no ``encoding`` parameter is given, the encoding will be detected automatically (among UTF-8 and UTF-16) if the file contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM is present. Example translation ``es_LA.csv``:: "I love you","Te amo" "%(name)s liked this","A %(name)s les gustó esto","plural" "%(name)s liked this","A %(name)s le gustó esto","singular" .. versionchanged:: 4.3 Added ``encoding`` parameter. Added support for BOM-based encoding detection, UTF-16, and UTF-8-with-BOM. """ global _translations global _supported_locales _translations = {} for path in os.listdir(directory): if not path.endswith(".csv"): continue locale, extension = path.split(".") if not re.match("[a-z]+(_[A-Z]+)?$", locale): gen_log.error( "Unrecognized locale %r (path: %s)", locale, os.path.join(directory, path), ) continue full_path = os.path.join(directory, path) if encoding is None: # Try to autodetect encoding based on the BOM. with open(full_path, "rb") as bf: data = bf.read(len(codecs.BOM_UTF16_LE)) if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): encoding = "utf-16" else: # utf-8-sig is "utf-8 with optional BOM". It's discouraged # in most cases but is common with CSV files because Excel # cannot read utf-8 files without a BOM. encoding = "utf-8-sig" # python 3: csv.reader requires a file open in text mode. # Specify an encoding to avoid dependence on $LANG environment variable. with open(full_path, encoding=encoding) as f: _translations[locale] = {} for i, row in enumerate(csv.reader(f)): if not row or len(row) < 2: continue row = [escape.to_unicode(c).strip() for c in row] english, translation = row[:2] if len(row) > 2: plural = row[2] or "unknown" else: plural = "unknown" if plural not in ("plural", "singular", "unknown"): gen_log.error( "Unrecognized plural indicator %r in %s line %d", plural, path, i + 1, ) continue _translations[locale].setdefault(plural, {})[english] = translation _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) gen_log.debug("Supported locales: %s", sorted(_supported_locales))
[ "Loads", "translations", "from", "CSV", "files", "in", "a", "directory", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L91-L175
[ "def", "load_translations", "(", "directory", ":", "str", ",", "encoding", ":", "str", "=", "None", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "_translations", "=", "{", "}", "for", "path", "in", "os", ".", "listdir", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
load_gettext_translations
Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo
tornado/locale.py
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo """ global _translations global _supported_locales global _use_gettext _translations = {} for lang in os.listdir(directory): if lang.startswith("."): continue # skip .svn, etc if os.path.isfile(os.path.join(directory, lang)): continue try: os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo")) _translations[lang] = gettext.translation( domain, directory, languages=[lang] ) except Exception as e: gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) continue _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) _use_gettext = True gen_log.debug("Supported locales: %s", sorted(_supported_locales))
def load_gettext_translations(directory: str, domain: str) -> None: """Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc 2. Merge against existing POT file:: msgmerge old.po mydomain.po > new.po 3. Compile:: msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo """ global _translations global _supported_locales global _use_gettext _translations = {} for lang in os.listdir(directory): if lang.startswith("."): continue # skip .svn, etc if os.path.isfile(os.path.join(directory, lang)): continue try: os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo")) _translations[lang] = gettext.translation( domain, directory, languages=[lang] ) except Exception as e: gen_log.error("Cannot load translation for '%s': %s", lang, str(e)) continue _supported_locales = frozenset(list(_translations.keys()) + [_default_locale]) _use_gettext = True gen_log.debug("Supported locales: %s", sorted(_supported_locales))
[ "Loads", "translations", "from", "gettext", "s", "locale", "tree" ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L178-L218
[ "def", "load_gettext_translations", "(", "directory", ":", "str", ",", "domain", ":", "str", ")", "->", "None", ":", "global", "_translations", "global", "_supported_locales", "global", "_use_gettext", "_translations", "=", "{", "}", "for", "lang", "in", "os", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.get_closest
Returns the closest match for the given locale code.
tornado/locale.py
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: continue elif len(parts) == 2: code = parts[0].lower() + "_" + parts[1].upper() if code in _supported_locales: return cls.get(code) if parts[0].lower() in _supported_locales: return cls.get(parts[0].lower()) return cls.get(_default_locale)
def get_closest(cls, *locale_codes: str) -> "Locale": """Returns the closest match for the given locale code.""" for code in locale_codes: if not code: continue code = code.replace("-", "_") parts = code.split("_") if len(parts) > 2: continue elif len(parts) == 2: code = parts[0].lower() + "_" + parts[1].upper() if code in _supported_locales: return cls.get(code) if parts[0].lower() in _supported_locales: return cls.get(parts[0].lower()) return cls.get(_default_locale)
[ "Returns", "the", "closest", "match", "for", "the", "given", "locale", "code", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L236-L251
[ "def", "get_closest", "(", "cls", ",", "*", "locale_codes", ":", "str", ")", "->", "\"Locale\"", ":", "for", "code", "in", "locale_codes", ":", "if", "not", "code", ":", "continue", "code", "=", "code", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.get
Returns the Locale for the given locale code. If it is not supported, we raise an exception.
tornado/locale.py
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if translations is None: locale = CSVLocale(code, {}) # type: Locale elif _use_gettext: locale = GettextLocale(code, translations) else: locale = CSVLocale(code, translations) cls._cache[code] = locale return cls._cache[code]
def get(cls, code: str) -> "Locale": """Returns the Locale for the given locale code. If it is not supported, we raise an exception. """ if code not in cls._cache: assert code in _supported_locales translations = _translations.get(code, None) if translations is None: locale = CSVLocale(code, {}) # type: Locale elif _use_gettext: locale = GettextLocale(code, translations) else: locale = CSVLocale(code, translations) cls._cache[code] = locale return cls._cache[code]
[ "Returns", "the", "Locale", "for", "the", "given", "locale", "code", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L254-L269
[ "def", "get", "(", "cls", ",", "code", ":", "str", ")", "->", "\"Locale\"", ":", "if", "code", "not", "in", "cls", ".", "_cache", ":", "assert", "code", "in", "_supported_locales", "translations", "=", "_translations", ".", "get", "(", "code", ",", "No...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.translate
Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``.
tornado/locale.py
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``. """ raise NotImplementedError()
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and we return the singular form for the given message when ``count == 1``. """ raise NotImplementedError()
[ "Returns", "the", "translation", "for", "the", "given", "message", "for", "this", "locale", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L306-L316
[ "def", "translate", "(", "self", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.format_date
Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily intended for dates in the past. For dates in the future, we fall back to full format.
tornado/locale.py
def format_date( self, date: Union[int, float, datetime.datetime], gmt_offset: int = 0, relative: bool = True, shorter: bool = False, full_format: bool = False, ) -> str: """Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily intended for dates in the past. For dates in the future, we fall back to full format. """ if isinstance(date, (int, float)): date = datetime.datetime.utcfromtimestamp(date) now = datetime.datetime.utcnow() if date > now: if relative and (date - now).seconds < 60: # Due to click skew, things are some things slightly # in the future. Round timestamps in the immediate # future down to now in relative mode. date = now else: # Otherwise, future dates always use the full format. full_format = True local_date = date - datetime.timedelta(minutes=gmt_offset) local_now = now - datetime.timedelta(minutes=gmt_offset) local_yesterday = local_now - datetime.timedelta(hours=24) difference = now - date seconds = difference.seconds days = difference.days _ = self.translate format = None if not full_format: if relative and days == 0: if seconds < 50: return _("1 second ago", "%(seconds)d seconds ago", seconds) % { "seconds": seconds } if seconds < 50 * 60: minutes = round(seconds / 60.0) return _("1 minute ago", "%(minutes)d minutes ago", minutes) % { "minutes": minutes } hours = round(seconds / (60.0 * 60)) return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours} if days == 0: format = _("%(time)s") elif days == 1 and local_date.day == local_yesterday.day and relative: format = _("yesterday") if shorter else _("yesterday at %(time)s") elif days < 5: format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s") elif days < 334: # 11mo, since confusing for same month last year format = ( _("%(month_name)s %(day)s") if shorter else _("%(month_name)s %(day)s at %(time)s") ) if format is None: format = ( _("%(month_name)s %(day)s, %(year)s") if shorter else _("%(month_name)s %(day)s, %(year)s at %(time)s") ) tfhour_clock = self.code not in ("en", "en_US", "zh_CN") if tfhour_clock: str_time = "%d:%02d" % (local_date.hour, local_date.minute) elif self.code == "zh_CN": str_time = "%s%d:%02d" % ( (u"\u4e0a\u5348", u"\u4e0b\u5348")[local_date.hour >= 12], local_date.hour % 12 or 12, local_date.minute, ) else: str_time = "%d:%02d %s" % ( local_date.hour % 12 or 12, local_date.minute, ("am", "pm")[local_date.hour >= 12], ) return format % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), "year": str(local_date.year), "time": str_time, }
def format_date( self, date: Union[int, float, datetime.datetime], gmt_offset: int = 0, relative: bool = True, shorter: bool = False, full_format: bool = False, ) -> str: """Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily intended for dates in the past. For dates in the future, we fall back to full format. """ if isinstance(date, (int, float)): date = datetime.datetime.utcfromtimestamp(date) now = datetime.datetime.utcnow() if date > now: if relative and (date - now).seconds < 60: # Due to click skew, things are some things slightly # in the future. Round timestamps in the immediate # future down to now in relative mode. date = now else: # Otherwise, future dates always use the full format. full_format = True local_date = date - datetime.timedelta(minutes=gmt_offset) local_now = now - datetime.timedelta(minutes=gmt_offset) local_yesterday = local_now - datetime.timedelta(hours=24) difference = now - date seconds = difference.seconds days = difference.days _ = self.translate format = None if not full_format: if relative and days == 0: if seconds < 50: return _("1 second ago", "%(seconds)d seconds ago", seconds) % { "seconds": seconds } if seconds < 50 * 60: minutes = round(seconds / 60.0) return _("1 minute ago", "%(minutes)d minutes ago", minutes) % { "minutes": minutes } hours = round(seconds / (60.0 * 60)) return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours} if days == 0: format = _("%(time)s") elif days == 1 and local_date.day == local_yesterday.day and relative: format = _("yesterday") if shorter else _("yesterday at %(time)s") elif days < 5: format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s") elif days < 334: # 11mo, since confusing for same month last year format = ( _("%(month_name)s %(day)s") if shorter else _("%(month_name)s %(day)s at %(time)s") ) if format is None: format = ( _("%(month_name)s %(day)s, %(year)s") if shorter else _("%(month_name)s %(day)s, %(year)s at %(time)s") ) tfhour_clock = self.code not in ("en", "en_US", "zh_CN") if tfhour_clock: str_time = "%d:%02d" % (local_date.hour, local_date.minute) elif self.code == "zh_CN": str_time = "%s%d:%02d" % ( (u"\u4e0a\u5348", u"\u4e0b\u5348")[local_date.hour >= 12], local_date.hour % 12 or 12, local_date.minute, ) else: str_time = "%d:%02d %s" % ( local_date.hour % 12 or 12, local_date.minute, ("am", "pm")[local_date.hour >= 12], ) return format % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), "year": str(local_date.year), "time": str_time, }
[ "Formats", "the", "given", "date", "(", "which", "should", "be", "GMT", ")", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L323-L421
[ "def", "format_date", "(", "self", ",", "date", ":", "Union", "[", "int", ",", "float", ",", "datetime", ".", "datetime", "]", ",", "gmt_offset", ":", "int", "=", "0", ",", "relative", ":", "bool", "=", "True", ",", "shorter", ":", "bool", "=", "Fa...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.format_day
Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``.
tornado/locale.py
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(minutes=gmt_offset) _ = self.translate if dow: return _("%(weekday)s, %(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), } else: return _("%(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "day": str(local_date.day), }
def format_day( self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True ) -> bool: """Formats the given date as a day of week. Example: "Monday, January 22". You can remove the day of week with ``dow=False``. """ local_date = date - datetime.timedelta(minutes=gmt_offset) _ = self.translate if dow: return _("%(weekday)s, %(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "weekday": self._weekdays[local_date.weekday()], "day": str(local_date.day), } else: return _("%(month_name)s %(day)s") % { "month_name": self._months[local_date.month - 1], "day": str(local_date.day), }
[ "Formats", "the", "given", "date", "as", "a", "day", "of", "week", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L423-L443
[ "def", "format_day", "(", "self", ",", "date", ":", "datetime", ".", "datetime", ",", "gmt_offset", ":", "int", "=", "0", ",", "dow", ":", "bool", "=", "True", ")", "->", "bool", ":", "local_date", "=", "date", "-", "datetime", ".", "timedelta", "(",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.list
Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1.
tornado/locale.py
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: return parts[0] comma = u" \u0648 " if self.code.startswith("fa") else u", " return _("%(commas)s and %(last)s") % { "commas": comma.join(parts[:-1]), "last": parts[len(parts) - 1], }
def list(self, parts: Any) -> str: """Returns a comma-separated list for the given list of parts. The format is, e.g., "A, B and C", "A and B" or just "A" for lists of size 1. """ _ = self.translate if len(parts) == 0: return "" if len(parts) == 1: return parts[0] comma = u" \u0648 " if self.code.startswith("fa") else u", " return _("%(commas)s and %(last)s") % { "commas": comma.join(parts[:-1]), "last": parts[len(parts) - 1], }
[ "Returns", "a", "comma", "-", "separated", "list", "for", "the", "given", "list", "of", "parts", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L445-L460
[ "def", "list", "(", "self", ",", "parts", ":", "Any", ")", "->", "str", ":", "_", "=", "self", ".", "translate", "if", "len", "(", "parts", ")", "==", "0", ":", "return", "\"\"", "if", "len", "(", "parts", ")", "==", "1", ":", "return", "parts"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Locale.friendly_number
Returns a comma-separated number for the given integer.
tornado/locale.py
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return ",".join(reversed(parts))
def friendly_number(self, value: int) -> str: """Returns a comma-separated number for the given integer.""" if self.code not in ("en", "en_US"): return str(value) s = str(value) parts = [] while s: parts.append(s[-3:]) s = s[:-3] return ",".join(reversed(parts))
[ "Returns", "a", "comma", "-", "separated", "number", "for", "the", "given", "integer", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L462-L471
[ "def", "friendly_number", "(", "self", ",", "value", ":", "int", ")", "->", "str", ":", "if", "self", ".", "code", "not", "in", "(", "\"en\"", ",", "\"en_US\"", ")", ":", "return", "str", "(", "value", ")", "s", "=", "str", "(", "value", ")", "pa...
b8b481770bcdb333a69afde5cce7eaa449128326
train
GettextLocale.pgettext
Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2
tornado/locale.py
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2 """ if plural_message is not None: assert count is not None msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, message), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message), count, ) result = self.ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = self.ngettext(message, plural_message, count) return result else: msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = self.gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message return result
def pgettext( self, context: str, message: str, plural_message: str = None, count: int = None ) -> str: """Allows to set context for translation, accepts plural forms. Usage example:: pgettext("law", "right") pgettext("good", "right") Plural message example:: pgettext("organization", "club", "clubs", len(clubs)) pgettext("stick", "club", "clubs", len(clubs)) To generate POT file with context, add following options to step 1 of `load_gettext_translations` sequence:: xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3 .. versionadded:: 4.2 """ if plural_message is not None: assert count is not None msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, message), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message), count, ) result = self.ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = self.ngettext(message, plural_message, count) return result else: msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = self.gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message return result
[ "Allows", "to", "set", "context", "for", "translation", "accepts", "plural", "forms", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L522-L562
[ "def", "pgettext", "(", "self", ",", "context", ":", "str", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "if", "plural_message", "is", "not", "None", ":", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
_unquote_or_none
None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use.
tornado/routing.py
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_unescape(s, encoding=None, plus=False)
def _unquote_or_none(s: Optional[str]) -> Optional[bytes]: # noqa: F811 """None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use. """ if s is None: return s return url_unescape(s, encoding=None, plus=False)
[ "None", "-", "safe", "wrapper", "around", "url_unescape", "to", "handle", "unmatched", "optional", "groups", "correctly", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L702-L711
[ "def", "_unquote_or_none", "(", "s", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "bytes", "]", ":", "# noqa: F811", "if", "s", "is", "None", ":", "return", "s", "return", "url_unescape", "(", "s", ",", "encoding", "=", "None", ",", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Router.find_handler
Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request.
tornado/routing.py
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request. """ raise NotImplementedError()
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional keyword arguments passed by routing implementation. :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to process the request. """ raise NotImplementedError()
[ "Must", "be", "implemented", "to", "return", "an", "appropriate", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "the", "request", ".", "Routing", "implementations", "may", "pass", "additional", "kwargs", "to", "exten...
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L193-L205
[ "def", "find_handler", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "raise", "NotImplementedError", "(", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RuleRouter.add_rules
Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor).
tornado/routing.py
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): assert len(rule) in (2, 3, 4) if isinstance(rule[0], basestring_type): rule = Rule(PathMatches(rule[0]), *rule[1:]) else: rule = Rule(*rule) self.rules.append(self.process_rule(rule))
def add_rules(self, rules: _RuleList) -> None: """Appends new rules to the router. :arg rules: a list of Rule instances (or tuples of arguments, which are passed to Rule constructor). """ for rule in rules: if isinstance(rule, (tuple, list)): assert len(rule) in (2, 3, 4) if isinstance(rule[0], basestring_type): rule = Rule(PathMatches(rule[0]), *rule[1:]) else: rule = Rule(*rule) self.rules.append(self.process_rule(rule))
[ "Appends", "new", "rules", "to", "the", "router", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L334-L348
[ "def", "add_rules", "(", "self", ",", "rules", ":", "_RuleList", ")", "->", "None", ":", "for", "rule", "in", "rules", ":", "if", "isinstance", "(", "rule", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "len", "(", "rule", ")", "in", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RuleRouter.get_target_delegate
Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation.
tornado/routing.py
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): assert request.connection is not None return target.start_request(request.server_connection, request.connection) elif callable(target): assert request.connection is not None return _CallableAdapter( partial(target, **target_params), request.connection ) return None
def get_target_delegate( self, target: Any, request: httputil.HTTPServerRequest, **target_params: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Returns an instance of `~.httputil.HTTPMessageDelegate` for a Rule's target. This method is called by `~.find_handler` and can be extended to provide additional target types. :arg target: a Rule's target. :arg httputil.HTTPServerRequest request: current request. :arg target_params: additional parameters that can be useful for `~.httputil.HTTPMessageDelegate` creation. """ if isinstance(target, Router): return target.find_handler(request, **target_params) elif isinstance(target, httputil.HTTPServerConnectionDelegate): assert request.connection is not None return target.start_request(request.server_connection, request.connection) elif callable(target): assert request.connection is not None return _CallableAdapter( partial(target, **target_params), request.connection ) return None
[ "Returns", "an", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "for", "a", "Rule", "s", "target", ".", "This", "method", "is", "called", "by", "~", ".", "find_handler", "and", "can", "be", "extended", "to", "provide", "additional", "t...
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L376-L401
[ "def", "get_target_delegate", "(", "self", ",", "target", ":", "Any", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "target_params", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "if", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Matcher.match
Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.
tornado/routing.py
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.""" raise NotImplementedError()
def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]: """Matches current instance against the request. :arg httputil.HTTPServerRequest request: current HTTP request :returns: a dict of parameters to be passed to the target handler (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs`` can be passed for proper `~.web.RequestHandler` instantiation). An empty dict is a valid (and common) return value to indicate a match when the argument-passing features are not used. ``None`` must be returned to indicate that there is no match.""" raise NotImplementedError()
[ "Matches", "current", "instance", "against", "the", "request", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L493-L503
[ "def", "match", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "raise", "NotImplementedError", "(", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
PathMatches._find_groups
Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2).
tornado/routing.py
def _find_groups(self) -> Tuple[Optional[str], Optional[int]]: """Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2). """ pattern = self.regex.pattern if pattern.startswith("^"): pattern = pattern[1:] if pattern.endswith("$"): pattern = pattern[:-1] if self.regex.groups != pattern.count("("): # The pattern is too complicated for our simplistic matching, # so we can't support reversing it. return None, None pieces = [] for fragment in pattern.split("("): if ")" in fragment: paren_loc = fragment.index(")") if paren_loc >= 0: pieces.append("%s" + fragment[paren_loc + 1 :]) else: try: unescaped_fragment = re_unescape(fragment) except ValueError: # If we can't unescape part of it, we can't # reverse this url. return (None, None) pieces.append(unescaped_fragment) return "".join(pieces), self.regex.groups
def _find_groups(self) -> Tuple[Optional[str], Optional[int]]: """Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2). """ pattern = self.regex.pattern if pattern.startswith("^"): pattern = pattern[1:] if pattern.endswith("$"): pattern = pattern[:-1] if self.regex.groups != pattern.count("("): # The pattern is too complicated for our simplistic matching, # so we can't support reversing it. return None, None pieces = [] for fragment in pattern.split("("): if ")" in fragment: paren_loc = fragment.index(")") if paren_loc >= 0: pieces.append("%s" + fragment[paren_loc + 1 :]) else: try: unescaped_fragment = re_unescape(fragment) except ValueError: # If we can't unescape part of it, we can't # reverse this url. return (None, None) pieces.append(unescaped_fragment) return "".join(pieces), self.regex.groups
[ "Returns", "a", "tuple", "(", "reverse", "string", "group", "count", ")", "for", "a", "url", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L608-L640
[ "def", "_find_groups", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "int", "]", "]", ":", "pattern", "=", "self", ".", "regex", ".", "pattern", "if", "pattern", ".", "startswith", "(", "\"^\"", ")", ":", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
get_links_from_url
Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'.
demos/webspider/webspider.py
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ 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)]
async def get_links_from_url(url): """Download the page at `url` and parse it for links. Returned links have had the fragment after `#` removed, and have been made absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes 'http://www.tornadoweb.org/en/stable/gen.html'. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/webspider/webspider.py#L15-L26
[ "async", "def", "get_links_from_url", "(", "url", ")", ":", "response", "=", "await", "httpclient", ".", "AsyncHTTPClient", "(", ")", ".", "fetch", "(", "url", ")", "print", "(", "\"fetched %s\"", "%", "url", ")", "html", "=", "response", ".", "body", "....
b8b481770bcdb333a69afde5cce7eaa449128326
train
MessageBuffer.get_messages_since
Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received.
demos/chat/chatdemo.py
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break results.append(msg) results.reverse() return results
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/demos/chat/chatdemo.py#L38-L49
[ "def", "get_messages_since", "(", "self", ",", "cursor", ")", ":", "results", "=", "[", "]", "for", "msg", "in", "reversed", "(", "self", ".", "cache", ")", ":", "if", "msg", "[", "\"id\"", "]", "==", "cursor", ":", "break", "results", ".", "append",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
import_object
Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module
tornado/util.py
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module """ 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: raise ImportError("No module named %s" % parts[-1])
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') is tornado.escape.utf8 True >>> import_object('tornado') is tornado True >>> import_object('tornado.missing_module') Traceback (most recent call last): ... ImportError: No module named missing_module """ 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: raise ImportError("No module named %s" % parts[-1])
[ "Imports", "an", "object", "by", "name", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L131-L157
[ "def", "import_object", "(", "name", ":", "str", ")", "->", "Any", ":", "if", "name", ".", "count", "(", "\".\"", ")", "==", "0", ":", "return", "__import__", "(", "name", ")", "parts", "=", "name", ".", "split", "(", "\".\"", ")", "obj", "=", "_...
b8b481770bcdb333a69afde5cce7eaa449128326
train
errno_from_exception
Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno.
tornado/util.py
def errno_from_exception(e: BaseException) -> Optional[int]: """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno. """ if hasattr(e, "errno"): return e.errno # type: ignore elif e.args: return e.args[0] else: return None
def errno_from_exception(e: BaseException) -> Optional[int]: """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L188-L203
[ "def", "errno_from_exception", "(", "e", ":", "BaseException", ")", "->", "Optional", "[", "int", "]", ":", "if", "hasattr", "(", "e", ",", "\"errno\"", ")", ":", "return", "e", ".", "errno", "# type: ignore", "elif", "e", ".", "args", ":", "return", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
_websocket_mask_python
Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available.
tornado/util.py
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ 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()
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L439-L452
[ "def", "_websocket_mask_python", "(", "mask", ":", "bytes", ",", "data", ":", "bytes", ")", "->", "bytes", ":", "mask_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "mask", ")", "unmasked_arr", "=", "array", ".", "array", "(", "\"B\"", ",", "data...
b8b481770bcdb333a69afde5cce7eaa449128326
train
GzipDecompressor.decompress
Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty.
tornado/util.py
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty. """ return self.decompressobj.decompress(value, max_length)
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass it back to a future call to `decompress` if it is not empty. """ return self.decompressobj.decompress(value, max_length)
[ "Decompress", "a", "chunk", "returning", "newly", "-", "available", "data", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L103-L114
[ "def", "decompress", "(", "self", ",", "value", ":", "bytes", ",", "max_length", ":", "int", "=", "0", ")", "->", "bytes", ":", "return", "self", ".", "decompressobj", ".", "decompress", "(", "value", ",", "max_length", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
Configurable.configure
Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters.
tornado/util.py
def configure(cls, impl, **kwargs): # type: (Union[None, str, Type[Configurable]], Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters. """ base = cls.configurable_base() if isinstance(impl, str): impl = typing.cast(Type[Configurable], import_object(impl)) if impl is not None and not issubclass(impl, cls): raise ValueError("Invalid subclass of %s" % cls) base.__impl_class = impl base.__impl_kwargs = kwargs
def configure(cls, impl, **kwargs): # type: (Union[None, str, Type[Configurable]], Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters. """ base = cls.configurable_base() if isinstance(impl, str): impl = typing.cast(Type[Configurable], import_object(impl)) if impl is not None and not issubclass(impl, cls): raise ValueError("Invalid subclass of %s" % cls) base.__impl_class = impl base.__impl_kwargs = kwargs
[ "Sets", "the", "class", "to", "use", "when", "the", "base", "class", "is", "instantiated", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L320-L334
[ "def", "configure", "(", "cls", ",", "impl", ",", "*", "*", "kwargs", ")", ":", "# type: (Union[None, str, Type[Configurable]], Any) -> None", "base", "=", "cls", ".", "configurable_base", "(", ")", "if", "isinstance", "(", "impl", ",", "str", ")", ":", "impl"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
ArgReplacer.get_old_value
Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present.
tornado/util.py
def get_old_value( self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None ) -> Any: """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.arg_pos: return args[self.arg_pos] else: return kwargs.get(self.name, default)
def get_old_value( self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None ) -> Any: """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.arg_pos: return args[self.arg_pos] else: return kwargs.get(self.name, default)
[ "Returns", "the", "old", "value", "of", "the", "named", "argument", "without", "replacing", "it", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L397-L407
[ "def", "get_old_value", "(", "self", ",", "args", ":", "Sequence", "[", "Any", "]", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ",", "default", ":", "Any", "=", "None", ")", "->", "Any", ":", "if", "self", ".", "arg_pos", "is", "not"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
ArgReplacer.replace
Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``.
tornado/util.py
def replace( self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any] ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]: """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``. """ if self.arg_pos is not None and len(args) > self.arg_pos: # The arg to replace is passed positionally old_value = args[self.arg_pos] args = list(args) # *args is normally a tuple args[self.arg_pos] = new_value else: # The arg to replace is either omitted or passed by keyword. old_value = kwargs.get(self.name) kwargs[self.name] = new_value return old_value, args, kwargs
def replace( self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any] ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]: """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``. """ if self.arg_pos is not None and len(args) > self.arg_pos: # The arg to replace is passed positionally old_value = args[self.arg_pos] args = list(args) # *args is normally a tuple args[self.arg_pos] = new_value else: # The arg to replace is either omitted or passed by keyword. old_value = kwargs.get(self.name) kwargs[self.name] = new_value return old_value, args, kwargs
[ "Replace", "the", "named", "argument", "in", "args", "kwargs", "with", "new_value", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/util.py#L409-L430
[ "def", "replace", "(", "self", ",", "new_value", ":", "Any", ",", "args", ":", "Sequence", "[", "Any", "]", ",", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Any", ",", "Sequence", "[", "Any", "]", ",", "Dict", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
WSGIContainer.environ
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
tornado/wsgi.py
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: """Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. """ hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str( escape.url_unescape(request.path, encoding=None, plus=False) ), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": BytesIO(escape.utf8(request.body)), "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ
[ "Converts", "a", "tornado", ".", "httputil", ".", "HTTPServerRequest", "to", "a", "WSGI", "environment", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/wsgi.py#L148-L183
[ "def", "environ", "(", "request", ":", "httputil", ".", "HTTPServerRequest", ")", "->", "Dict", "[", "Text", ",", "Any", "]", ":", "hostport", "=", "request", ".", "host", ".", "split", "(", "\":\"", ")", "if", "len", "(", "hostport", ")", "==", "2",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
stream_request_body
Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage.
tornado/web.py
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1824-L1848
[ "def", "stream_request_body", "(", "cls", ":", "Type", "[", "RequestHandler", "]", ")", "->", "Type", "[", "RequestHandler", "]", ":", "# noqa: E501", "if", "not", "issubclass", "(", "cls", ",", "RequestHandler", ")", ":", "raise", "TypeError", "(", "\"expec...
b8b481770bcdb333a69afde5cce7eaa449128326
train
removeslash
Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator.
tornado/web.py
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if self.request.path.endswith("/"): if self.request.method in ("GET", "HEAD"): uri = self.request.path.rstrip("/") if uri: # don't try to redirect '/' to '' if self.request.query: uri += "?" + self.request.query self.redirect(uri, permanent=True) return None else: raise HTTPError(404) return method(self, *args, **kwargs) return wrapper
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if self.request.path.endswith("/"): if self.request.method in ("GET", "HEAD"): uri = self.request.path.rstrip("/") if uri: # don't try to redirect '/' to '' if self.request.query: uri += "?" + self.request.query self.redirect(uri, permanent=True) return None else: raise HTTPError(404) return method(self, *args, **kwargs) return wrapper
[ "Use", "this", "decorator", "to", "remove", "trailing", "slashes", "from", "the", "request", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1857-L1883
[ "def", "removeslash", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
authenticated
Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in.
tornado/web.py
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urllib.parse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: assert self.request.uri is not None next_url = self.request.uri url += "?" + urlencode(dict(next=next_url)) self.redirect(url) return None raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urllib.parse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: assert self.request.uri is not None next_url = self.request.uri url += "?" + urlencode(dict(next=next_url)) self.redirect(url) return None raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
[ "Decorate", "methods", "with", "this", "to", "require", "that", "the", "user", "be", "logged", "in", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L3142-L3176
[ "def", "authenticated", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.on_connection_close
Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
tornado/web.py
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection. """ 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_future.exception()
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection. """ 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_future.exception()
[ "Called", "in", "async", "handlers", "if", "the", "client", "closed", "the", "connection", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L300-L317
[ "def", "on_connection_close", "(", "self", ")", "->", "None", ":", "if", "_has_stream_request_body", "(", "self", ".", "__class__", ")", ":", "if", "not", "self", ".", "request", ".", "_body_future", ".", "done", "(", ")", ":", "self", ".", "request", "....
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.clear
Resets all headers and content for this response.
tornado/web.py
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timestamp(time.time()), } ) self.set_default_headers() self._write_buffer = [] # type: List[bytes] self._status_code = 200 self._reason = httputil.responses[200]
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timestamp(time.time()), } ) self.set_default_headers() self._write_buffer = [] # type: List[bytes] self._status_code = 200 self._reason = httputil.responses[200]
[ "Resets", "all", "headers", "and", "content", "for", "this", "response", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L319-L331
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_headers", "=", "httputil", ".", "HTTPHeaders", "(", "{", "\"Server\"", ":", "\"TornadoServer/%s\"", "%", "tornado", ".", "version", ",", "\"Content-Type\"", ":", "\"text/html; charset=UTF-8\"", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.set_status
Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`.
tornado/web.py
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`. """ self._status_code = status_code if reason is not None: self._reason = escape.native_str(reason) else: self._reason = httputil.responses.get(status_code, "Unknown")
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`. """ self._status_code = status_code if reason is not None: self._reason = escape.native_str(reason) else: self._reason = httputil.responses.get(status_code, "Unknown")
[ "Sets", "the", "status", "code", "for", "our", "response", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L343-L360
[ "def", "set_status", "(", "self", ",", "status_code", ":", "int", ",", "reason", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "_status_code", "=", "status_code", "if", "reason", "is", "not", "None", ":", "self", ".", "_reason", "=", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.set_header
Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header).
tornado/web.py
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[name] = self._convert_header_value(value)
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[name] = self._convert_header_value(value)
[ "Sets", "the", "given", "response", "header", "name", "and", "value", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L366-L374
[ "def", "set_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", "[", "name", "]", "=", "self", ".", "_convert_header_value", "(", "value", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.add_header
Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header.
tornado/web.py
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
[ "Adds", "the", "given", "response", "header", "and", "value", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L376-L382
[ "def", "add_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", ".", "add", "(", "name", ",", "self", ".", "_convert_header_value", "(", "value", ")", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.clear_header
Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`.
tornado/web.py
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
[ "Clears", "an", "outgoing", "header", "undoing", "a", "previous", "set_header", "call", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L384-L391
[ "def", "clear_header", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "name", "in", "self", ".", "_headers", ":", "del", "self", ".", "_headers", "[", "name", "]" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_argument
Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments.
tornado/web.py
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments. """ return self._get_argument(name, default, self.request.arguments, strip)
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the request more than once, we return the last value. This method searches both the query and body arguments. """ return self._get_argument(name, default, self.request.arguments, strip)
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L439-L455
[ "def", "get_argument", "(", "# noqa: F811", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_arguments
Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments.
tornado/web.py
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # 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 isinstance(strip, bool) return self._get_arguments(name, self.request.arguments, strip)
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # 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 isinstance(strip, bool) return self._get_arguments(name, self.request.arguments, strip)
[ "Returns", "a", "list", "of", "the", "arguments", "with", "the", "given", "name", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L457-L470
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_body_argument
Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2
tornado/web.py
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.body_arguments, strip)
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.body_arguments, strip)
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "body", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L472-L489
[ "def", "get_body_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_body_arguments
Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
tornado/web.py
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, strip)
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, strip)
[ "Returns", "a", "list", "of", "the", "body", "arguments", "with", "the", "given", "name", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L491-L498
[ "def", "get_body_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "body_arguments"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_query_argument
Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2
tornado/web.py
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.query_arguments, strip)
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.query_arguments, strip)
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "query", "string", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L500-L517
[ "def", "get_query_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_query_arguments
Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
tornado/web.py
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_arguments, strip)
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_arguments, strip)
[ "Returns", "a", "list", "of", "the", "query", "arguments", "with", "the", "given", "name", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L519-L526
[ "def", "get_query_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "query_argument...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.decode_argument
Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
tornado/web.py
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex). """ try: return _unicode(value) except UnicodeDecodeError: raise HTTPError( 400, "Invalid unicode in %s: %r" % (name or "url", value[:40]) )
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex). """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L557-L575
[ "def", "decode_argument", "(", "self", ",", "value", ":", "bytes", ",", "name", ":", "str", "=", "None", ")", "->", "str", ":", "try", ":", "return", "_unicode", "(", "value", ")", "except", "UnicodeDecodeError", ":", "raise", "HTTPError", "(", "400", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.cookies
An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.
tornado/web.py
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
def cookies(self) -> Dict[str, http.cookies.Morsel]: """An alias for `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.""" return self.request.cookies
[ "An", "alias", "for", "self", ".", "request", ".", "cookies", "<", ".", "httputil", ".", "HTTPServerRequest", ".", "cookies", ">", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L578-L581
[ "def", "cookies", "(", "self", ")", "->", "Dict", "[", "str", ",", "http", ".", "cookies", ".", "Morsel", "]", ":", "return", "self", ".", "request", ".", "cookies" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_cookie
Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler.
tornado/web.py
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler. """ if self.request.cookies is not None and name in self.request.cookies: return self.request.cookies[name].value return default
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L583-L594
[ "def", "get_cookie", "(", "self", ",", "name", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "request", ".", "cookies", "is", "not", "None", "and", "name", "in", "self", ".", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.set_cookie
Sets an outgoing cookie name/value with the given options. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes.
tornado/web.py
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. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes. """ # The cookie library only accepts type str, in both python 2 and 3 name = escape.native_str(name) value = escape.native_str(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookie"): self._new_cookie = http.cookies.SimpleCookie() if name in self._new_cookie: del self._new_cookie[name] self._new_cookie[name] = value morsel = self._new_cookie[name] if domain: morsel["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: morsel["expires"] = httputil.format_timestamp(expires) if path: morsel["path"] = path for k, v in kwargs.items(): if k == "max_age": k = "max-age" # skip falsy values for httponly and secure flags because # SimpleCookie sets them regardless if k in ["httponly", "secure"] and not v: continue morsel[k] = v
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. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes. """ # The cookie library only accepts type str, in both python 2 and 3 name = escape.native_str(name) value = escape.native_str(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookie"): self._new_cookie = http.cookies.SimpleCookie() if name in self._new_cookie: del self._new_cookie[name] self._new_cookie[name] = value morsel = self._new_cookie[name] if domain: morsel["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: morsel["expires"] = httputil.format_timestamp(expires) if path: morsel["path"] = path for k, v in kwargs.items(): if k == "max_age": k = "max-age" # skip falsy values for httponly and secure flags because # SimpleCookie sets them regardless if k in ["httponly", "secure"] and not v: continue morsel[k] = v
[ "Sets", "an", "outgoing", "cookie", "name", "/", "value", "with", "the", "given", "options", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L596-L649
[ "def", "set_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "domain", ":", "str", "=", "None", ",", "expires", ":", "Union", "[", "float", ",", "Tuple", ",", "datetime", ".", "datetime"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.clear_cookie
Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request.
tornado/web.py
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request. """ expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain)
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L651-L663
[ "def", "clear_cookie", "(", "self", ",", "name", ":", "str", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "expires", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "datetime...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.clear_all_cookies
Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters.
tornado/web.py
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters. """ for name in self.request.cookies: self.clear_cookie(name, path=path, domain=domain)
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters. """ for name in self.request.cookies: self.clear_cookie(name, path=path, domain=domain)
[ "Deletes", "all", "the", "cookies", "the", "user", "sent", "with", "this", "request", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L665-L679
[ "def", "clear_all_cookies", "(", "self", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "for", "name", "in", "self", ".", "request", ".", "cookies", ":", "self", ".", "clear_cookie", "(", "name"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.set_secure_cookie
Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default.
tornado/web.py
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.set_cookie( name, self.create_signed_value(name, value, version=version), expires_days=expires_days, **kwargs )
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.set_cookie( name, self.create_signed_value(name, value, version=version), expires_days=expires_days, **kwargs )
[ "Signs", "and", "timestamps", "a", "cookie", "so", "it", "cannot", "be", "forged", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L681-L717
[ "def", "set_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "expires_days", ":", "int", "=", "30", ",", "version", ":", "int", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.create_signed_value
Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default.
tornado/web.py
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.require_setting("cookie_secret", "secure cookies") secret = self.application.settings["cookie_secret"] key_version = None if isinstance(secret, dict): if self.application.settings.get("key_version") is None: raise Exception("key_version setting must be used for secret_key dicts") key_version = self.application.settings["key_version"] return create_signed_value( secret, name, value, version=version, key_version=key_version )
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.require_setting("cookie_secret", "secure cookies") secret = self.application.settings["cookie_secret"] key_version = None if isinstance(secret, dict): if self.application.settings.get("key_version") is None: raise Exception("key_version setting must be used for secret_key dicts") key_version = self.application.settings["key_version"] return create_signed_value( secret, name, value, version=version, key_version=key_version )
[ "Signs", "and", "timestamps", "a", "string", "so", "it", "cannot", "be", "forged", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L719-L743
[ "def", "create_signed_value", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "version", ":", "int", "=", "None", ")", "->", "bytes", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_secure_cookie
Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.
tornado/web.py
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) return decode_signed_value( self.application.settings["cookie_secret"], name, value, max_age_days=max_age_days, min_version=min_version, )
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) return decode_signed_value( self.application.settings["cookie_secret"], name, value, max_age_days=max_age_days, min_version=min_version, )
[ "Returns", "the", "given", "signed", "cookie", "if", "it", "validates", "or", "None", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L745-L775
[ "def", "get_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ",", "max_age_days", ":", "int", "=", "31", ",", "min_version", ":", "int", "=", "None", ",", ")", "->", "Optional", "[", "bytes", "]", ":", "s...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_secure_cookie_key_version
Returns the signing key version of the secure cookie. The version is returned as int.
tornado/web.py
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) if value is None: return None return get_signature_key_version(value)
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) if value is None: return None return get_signature_key_version(value)
[ "Returns", "the", "signing", "key", "version", "of", "the", "secure", "cookie", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L777-L789
[ "def", "get_secure_cookie_key_version", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ")", "->", "Optional", "[", "int", "]", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", ",", "\"secure cookies\"", ")", "if", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.redirect
Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the ``permanent`` argument. The default is 302 (temporary).
tornado/web.py
def redirect(self, url: str, permanent: bool = False, status: int = None) -> None: """Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the ``permanent`` argument. The default is 302 (temporary). """ if self._headers_written: raise Exception("Cannot redirect after headers have been written") if status is None: status = 301 if permanent else 302 else: assert isinstance(status, int) and 300 <= status <= 399 self.set_status(status) self.set_header("Location", utf8(url)) self.finish()
def redirect(self, url: str, permanent: bool = False, status: int = None) -> None: """Sends a redirect to the given (optionally relative) URL. If the ``status`` argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the ``permanent`` argument. The default is 302 (temporary). """ if self._headers_written: raise Exception("Cannot redirect after headers have been written") if status is None: status = 301 if permanent else 302 else: assert isinstance(status, int) and 300 <= status <= 399 self.set_status(status) self.set_header("Location", utf8(url)) self.finish()
[ "Sends", "a", "redirect", "to", "the", "given", "(", "optionally", "relative", ")", "URL", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L791-L807
[ "def", "redirect", "(", "self", ",", "url", ":", "str", ",", "permanent", ":", "bool", "=", "False", ",", "status", ":", "int", "=", "None", ")", "->", "None", ":", "if", "self", ".", "_headers_written", ":", "raise", "Exception", "(", "\"Cannot redire...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.write
Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009
tornado/web.py
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009 """ if self._finished: raise RuntimeError("Cannot write() after finish()") if not isinstance(chunk, (bytes, unicode_type, dict)): message = "write() only accepts bytes, unicode, and dict objects" if isinstance(chunk, list): message += ( ". Lists not accepted for security reasons; see " + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 ) raise TypeError(message) if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009 """ if self._finished: raise RuntimeError("Cannot write() after finish()") if not isinstance(chunk, (bytes, unicode_type, dict)): message = "write() only accepts bytes, unicode, and dict objects" if isinstance(chunk, list): message += ( ". Lists not accepted for security reasons; see " + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 ) raise TypeError(message) if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
[ "Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L809-L839
[ "def", "write", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", ")", "->", "None", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot write() after finish()\"", ")", "if", "not", "isinst...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render
Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``.
tornado/web.py
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) # Insert the additional JS and CSS added by the modules on the page js_embed = [] js_files = [] css_embed = [] css_files = [] html_heads = [] html_bodies = [] for module in getattr(self, "_active_modules", {}).values(): embed_part = module.embedded_javascript() if embed_part: js_embed.append(utf8(embed_part)) file_part = module.javascript_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): js_files.append(_unicode(file_part)) else: js_files.extend(file_part) embed_part = module.embedded_css() if embed_part: css_embed.append(utf8(embed_part)) file_part = module.css_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): css_files.append(_unicode(file_part)) else: css_files.extend(file_part) head_part = module.html_head() if head_part: html_heads.append(utf8(head_part)) body_part = module.html_body() if body_part: html_bodies.append(utf8(body_part)) if js_files: # Maintain order of JavaScript files given by modules js = self.render_linked_js(js_files) sloc = html.rindex(b"</body>") html = html[:sloc] + utf8(js) + b"\n" + html[sloc:] if js_embed: js_bytes = self.render_embed_js(js_embed) sloc = html.rindex(b"</body>") html = html[:sloc] + js_bytes + b"\n" + html[sloc:] if css_files: css = self.render_linked_css(css_files) hloc = html.index(b"</head>") html = html[:hloc] + utf8(css) + b"\n" + html[hloc:] if css_embed: css_bytes = self.render_embed_css(css_embed) hloc = html.index(b"</head>") html = html[:hloc] + css_bytes + b"\n" + html[hloc:] if html_heads: hloc = html.index(b"</head>") html = html[:hloc] + b"".join(html_heads) + b"\n" + html[hloc:] if html_bodies: hloc = html.index(b"</body>") html = html[:hloc] + b"".join(html_bodies) + b"\n" + html[hloc:] return self.finish(html)
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) # Insert the additional JS and CSS added by the modules on the page js_embed = [] js_files = [] css_embed = [] css_files = [] html_heads = [] html_bodies = [] for module in getattr(self, "_active_modules", {}).values(): embed_part = module.embedded_javascript() if embed_part: js_embed.append(utf8(embed_part)) file_part = module.javascript_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): js_files.append(_unicode(file_part)) else: js_files.extend(file_part) embed_part = module.embedded_css() if embed_part: css_embed.append(utf8(embed_part)) file_part = module.css_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): css_files.append(_unicode(file_part)) else: css_files.extend(file_part) head_part = module.html_head() if head_part: html_heads.append(utf8(head_part)) body_part = module.html_body() if body_part: html_bodies.append(utf8(body_part)) if js_files: # Maintain order of JavaScript files given by modules js = self.render_linked_js(js_files) sloc = html.rindex(b"</body>") html = html[:sloc] + utf8(js) + b"\n" + html[sloc:] if js_embed: js_bytes = self.render_embed_js(js_embed) sloc = html.rindex(b"</body>") html = html[:sloc] + js_bytes + b"\n" + html[sloc:] if css_files: css = self.render_linked_css(css_files) hloc = html.index(b"</head>") html = html[:hloc] + utf8(css) + b"\n" + html[hloc:] if css_embed: css_bytes = self.render_embed_css(css_embed) hloc = html.index(b"</head>") html = html[:hloc] + css_bytes + b"\n" + html[hloc:] if html_heads: hloc = html.index(b"</head>") html = html[:hloc] + b"".join(html_heads) + b"\n" + html[hloc:] if html_bodies: hloc = html.index(b"</body>") html = html[:hloc] + b"".join(html_bodies) + b"\n" + html[hloc:] return self.finish(html)
[ "Renders", "the", "template", "with", "the", "given", "arguments", "as", "the", "response", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L841-L914
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot render() after finish()\"", ")", "html", "="...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render_linked_js
Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output.
tornado/web.py
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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 unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths )
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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 unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths )
[ "Default", "method", "used", "to", "render", "the", "final", "js", "links", "for", "the", "rendered", "webpage", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L916-L937
[ "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_a...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render_embed_js
Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output.
tornado/web.py
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<![CDATA[\n' + b"\n".join(js_embed) + b"\n//]]>\n</script>" )
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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", "rendered", "webpage", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L939-L949
[ "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</s...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render_linked_css
Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output.
tornado/web.py
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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 in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<link href="' + escape.xhtml_escape(p) + '" ' 'type="text/css" rel="stylesheet"/>' for p in paths )
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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 in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<link href="' + escape.xhtml_escape(p) + '" ' 'type="text/css" rel="stylesheet"/>' for p in paths )
[ "Default", "method", "used", "to", "render", "the", "final", "css", "links", "for", "the", "rendered", "webpage", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L951-L971
[ "def", "render_linked_css", "(", "self", ",", "css_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "css_files", ":", "if", "not", "i...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render_embed_css
Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output.
tornado/web.py
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>"
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ 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", "rendered", "webpage", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L973-L979
[ "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>\"" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.render_string
Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
tornado/web.py
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # 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) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # 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) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
[ "Generate", "the", "given", "template", "with", "the", "given", "arguments", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L981-L1005
[ "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", "(", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_template_namespace
Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`.
tornado/web.py
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`. """ namespace = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, pgettext=self.locale.pgettext, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.reverse_url, ) namespace.update(self.ui) return namespace
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`. """ namespace = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, pgettext=self.locale.pgettext, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.reverse_url, ) namespace.update(self.ui) return namespace
[ "Returns", "a", "dictionary", "to", "be", "used", "as", "the", "default", "template", "namespace", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1007-L1028
[ "def", "get_template_namespace", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "namespace", "=", "dict", "(", "handler", "=", "self", ",", "request", "=", "self", ".", "request", ",", "current_user", "=", "self", ".", "current_user", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.create_template_loader
Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead.
tornado/web.py
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead. """ settings = self.application.settings if "template_loader" in settings: return settings["template_loader"] kwargs = {} if "autoescape" in settings: # autoescape=None means "no escaping", so we have to be sure # to only pass this kwarg if the user asked for it. kwargs["autoescape"] = settings["autoescape"] if "template_whitespace" in settings: kwargs["whitespace"] = settings["template_whitespace"] return template.Loader(template_path, **kwargs)
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead. """ settings = self.application.settings if "template_loader" in settings: return settings["template_loader"] kwargs = {} if "autoescape" in settings: # autoescape=None means "no escaping", so we have to be sure # to only pass this kwarg if the user asked for it. kwargs["autoescape"] = settings["autoescape"] if "template_whitespace" in settings: kwargs["whitespace"] = settings["template_whitespace"] return template.Loader(template_path, **kwargs)
[ "Returns", "a", "new", "template", "loader", "for", "the", "given", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1030-L1049
[ "def", "create_template_loader", "(", "self", ",", "template_path", ":", "str", ")", "->", "template", ".", "BaseLoader", ":", "settings", "=", "self", ".", "application", ".", "settings", "if", "\"template_loader\"", "in", "settings", ":", "return", "settings",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.flush
Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed.
tornado/web.py
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ assert self.request.connection is not None chunk = b"".join(self._write_buffer) self._write_buffer = [] if not self._headers_written: self._headers_written = True for transform in self._transforms: assert chunk is not None self._status_code, self._headers, chunk = transform.transform_first_chunk( self._status_code, self._headers, chunk, include_footers ) # Ignore the chunk and only write the headers for HEAD requests if self.request.method == "HEAD": chunk = b"" # Finalize the cookie headers (which have been stored in a side # object so an outgoing cookie could be overwritten before it # is sent). if hasattr(self, "_new_cookie"): for cookie in self._new_cookie.values(): self.add_header("Set-Cookie", cookie.OutputString(None)) start_line = httputil.ResponseStartLine("", self._status_code, self._reason) return self.request.connection.write_headers( start_line, self._headers, chunk ) else: for transform in self._transforms: chunk = transform.transform_chunk(chunk, include_footers) # Ignore the chunk and only write the headers for HEAD requests if self.request.method != "HEAD": return self.request.connection.write(chunk) else: future = Future() # type: Future[None] future.set_result(None) return future
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ assert self.request.connection is not None chunk = b"".join(self._write_buffer) self._write_buffer = [] if not self._headers_written: self._headers_written = True for transform in self._transforms: assert chunk is not None self._status_code, self._headers, chunk = transform.transform_first_chunk( self._status_code, self._headers, chunk, include_footers ) # Ignore the chunk and only write the headers for HEAD requests if self.request.method == "HEAD": chunk = b"" # Finalize the cookie headers (which have been stored in a side # object so an outgoing cookie could be overwritten before it # is sent). if hasattr(self, "_new_cookie"): for cookie in self._new_cookie.values(): self.add_header("Set-Cookie", cookie.OutputString(None)) start_line = httputil.ResponseStartLine("", self._status_code, self._reason) return self.request.connection.write_headers( start_line, self._headers, chunk ) else: for transform in self._transforms: chunk = transform.transform_chunk(chunk, include_footers) # Ignore the chunk and only write the headers for HEAD requests if self.request.method != "HEAD": return self.request.connection.write(chunk) else: future = Future() # type: Future[None] future.set_result(None) return future
[ "Flushes", "the", "current", "output", "buffer", "to", "the", "network", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1051-L1101
[ "def", "flush", "(", "self", ",", "include_footers", ":", "bool", "=", "False", ")", "->", "\"Future[None]\"", ":", "assert", "self", ".", "request", ".", "connection", "is", "not", "None", "chunk", "=", "b\"\"", ".", "join", "(", "self", ".", "_write_bu...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.finish
Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` which may optionally be awaited to track the sending of the response to the client. This `.Future` resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``.
tornado/web.py
def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]": """Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` which may optionally be awaited to track the sending of the response to the client. This `.Future` resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("finish() called twice") if chunk is not None: self.write(chunk) # Automatically support ETags and add the Content-Length header if # we have not flushed any content yet. if not self._headers_written: if ( self._status_code == 200 and self.request.method in ("GET", "HEAD") and "Etag" not in self._headers ): self.set_etag_header() if self.check_etag_header(): self._write_buffer = [] self.set_status(304) if self._status_code in (204, 304) or ( self._status_code >= 100 and self._status_code < 200 ): assert not self._write_buffer, ( "Cannot send body with %s" % self._status_code ) self._clear_headers_for_304() elif "Content-Length" not in self._headers: content_length = sum(len(part) for part in self._write_buffer) self.set_header("Content-Length", content_length) assert self.request.connection is not None # Now that the request is finished, clear the callback we # set on the HTTPConnection (which would otherwise prevent the # garbage collection of the RequestHandler when there # are keepalive connections) self.request.connection.set_close_callback(None) # type: ignore future = self.flush(include_footers=True) self.request.connection.finish() self._log() self._finished = True self.on_finish() self._break_cycles() return future
def finish(self, chunk: Union[str, bytes, dict] = None) -> "Future[None]": """Finishes this response, ending the HTTP request. Passing a ``chunk`` to ``finish()`` is equivalent to passing that chunk to ``write()`` and then calling ``finish()`` with no arguments. Returns a `.Future` which may optionally be awaited to track the sending of the response to the client. This `.Future` resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("finish() called twice") if chunk is not None: self.write(chunk) # Automatically support ETags and add the Content-Length header if # we have not flushed any content yet. if not self._headers_written: if ( self._status_code == 200 and self.request.method in ("GET", "HEAD") and "Etag" not in self._headers ): self.set_etag_header() if self.check_etag_header(): self._write_buffer = [] self.set_status(304) if self._status_code in (204, 304) or ( self._status_code >= 100 and self._status_code < 200 ): assert not self._write_buffer, ( "Cannot send body with %s" % self._status_code ) self._clear_headers_for_304() elif "Content-Length" not in self._headers: content_length = sum(len(part) for part in self._write_buffer) self.set_header("Content-Length", content_length) assert self.request.connection is not None # Now that the request is finished, clear the callback we # set on the HTTPConnection (which would otherwise prevent the # garbage collection of the RequestHandler when there # are keepalive connections) self.request.connection.set_close_callback(None) # type: ignore future = self.flush(include_footers=True) self.request.connection.finish() self._log() self._finished = True self.on_finish() self._break_cycles() return future
[ "Finishes", "this", "response", "ending", "the", "HTTP", "request", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1103-L1160
[ "def", "finish", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", "=", "None", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"finish() called twice\"", ")", "i...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.detach
Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supported when HTTP/1.1 is used. .. versionadded:: 5.1
tornado/web.py
def detach(self) -> iostream.IOStream: """Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supported when HTTP/1.1 is used. .. versionadded:: 5.1 """ self._finished = True # TODO: add detach to HTTPConnection? return self.request.connection.detach()
def detach(self) -> iostream.IOStream: """Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake. This method is only supported when HTTP/1.1 is used. .. versionadded:: 5.1 """ self._finished = True # TODO: add detach to HTTPConnection? return self.request.connection.detach()
[ "Take", "control", "of", "the", "underlying", "stream", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1162-L1175
[ "def", "detach", "(", "self", ")", "->", "iostream", ".", "IOStream", ":", "self", ".", "_finished", "=", "True", "# TODO: add detach to HTTPConnection?", "return", "self", ".", "request", ".", "connection", ".", "detach", "(", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.send_error
Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`.
tornado/web.py
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`. """ if self._headers_written: gen_log.error("Cannot send error response after headers written") if not self._finished: # If we get an error between writing headers and finishing, # we are unlikely to be able to finish due to a # Content-Length mismatch. Try anyway to release the # socket. try: self.finish() except Exception: gen_log.error("Failed to flush partial response", exc_info=True) return self.clear() reason = kwargs.get("reason") if "exc_info" in kwargs: exception = kwargs["exc_info"][1] if isinstance(exception, HTTPError) and exception.reason: reason = exception.reason self.set_status(status_code, reason=reason) try: self.write_error(status_code, **kwargs) except Exception: app_log.error("Uncaught exception in write_error", exc_info=True) if not self._finished: self.finish()
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`. """ if self._headers_written: gen_log.error("Cannot send error response after headers written") if not self._finished: # If we get an error between writing headers and finishing, # we are unlikely to be able to finish due to a # Content-Length mismatch. Try anyway to release the # socket. try: self.finish() except Exception: gen_log.error("Failed to flush partial response", exc_info=True) return self.clear() reason = kwargs.get("reason") if "exc_info" in kwargs: exception = kwargs["exc_info"][1] if isinstance(exception, HTTPError) and exception.reason: reason = exception.reason self.set_status(status_code, reason=reason) try: self.write_error(status_code, **kwargs) except Exception: app_log.error("Uncaught exception in write_error", exc_info=True) if not self._finished: self.finish()
[ "Sends", "the", "given", "HTTP", "error", "code", "to", "the", "browser", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1182-L1218
[ "def", "send_error", "(", "self", ",", "status_code", ":", "int", "=", "500", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "_headers_written", ":", "gen_log", ".", "error", "(", "\"Cannot send error response after headers w...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.write_error
Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``.
tornado/web.py
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ 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 line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish( "<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % {"code": status_code, "message": self._reason} )
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ 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 line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish( "<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % {"code": status_code, "message": self._reason} )
[ "Override", "to", "implement", "custom", "error", "pages", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1220-L1243
[ "def", "write_error", "(", "self", ",", "status_code", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "settings", ".", "get", "(", "\"serve_traceback\"", ")", "and", "\"exc_info\"", "in", "kwargs", ":", "# i...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.locale
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter.
tornado/web.py
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter. """ 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() assert self._locale return self._locale
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter. """ 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() assert self._locale return self._locale
[ "The", "locale", "for", "the", "current", "session", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1246-L1264
[ "def", "locale", "(", "self", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "not", "hasattr", "(", "self", ",", "\"_locale\"", ")", ":", "loc", "=", "self", ".", "get_user_locale", "(", ")", "if", "loc", "is", "not", "None", ":", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.get_browser_locale
Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
tornado/web.py
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 locales.append((parts[0], score)) if locales: locales.sort(key=lambda pair: pair[1], reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 locales.append((parts[0], score)) if locales: locales.sort(key=lambda pair: pair[1], reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)
[ "Determines", "the", "user", "s", "locale", "from", "Accept", "-", "Language", "header", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1280-L1302
[ "def", "get_browser_locale", "(", "self", ",", "default", ":", "str", "=", "\"en_US\"", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "\"Accept-Language\"", "in", "self", ".", "request", ".", "headers", ":", "languages", "=", "self", ".", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.current_user
The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing.
tornado/web.py
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing. """ if not hasattr(self, "_current_user"): self._current_user = self.get_current_user() return self._current_user
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing. """ if not hasattr(self, "_current_user"): self._current_user = self.get_current_user() return self._current_user
[ "The", "authenticated", "user", "for", "this", "request", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1305-L1338
[ "def", "current_user", "(", "self", ")", "->", "Any", ":", "if", "not", "hasattr", "(", "self", ",", "\"_current_user\"", ")", ":", "self", ".", "_current_user", "=", "self", ".", "get_current_user", "(", ")", "return", "self", ".", "_current_user" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.xsrf_token
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 http://en.wikipedia.org/wiki/Cross-site_request_forgery This property is of type `bytes`, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8. .. versionchanged:: 3.2.2 The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the ``xsrf_cookie_version`` `Application` setting is set to 1. .. versionchanged:: 4.3 The ``xsrf_cookie_kwargs`` `Application` setting may be used to supply additional cookie options (which will be passed directly to `set_cookie`). For example, ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)`` will set the ``secure`` and ``httponly`` flags on the ``_xsrf`` cookie.
tornado/web.py
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 as a potential forgery. See http://en.wikipedia.org/wiki/Cross-site_request_forgery This property is of type `bytes`, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8. .. versionchanged:: 3.2.2 The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the ``xsrf_cookie_version`` `Application` setting is set to 1. .. versionchanged:: 4.3 The ``xsrf_cookie_kwargs`` `Application` setting may be used to supply additional cookie options (which will be passed directly to `set_cookie`). For example, ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)`` will set the ``secure`` and ``httponly`` flags on the ``_xsrf`` cookie. """ 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("xsrf_cookie_kwargs", {}) if output_version == 1: self._xsrf_token = binascii.b2a_hex(token) elif output_version == 2: mask = os.urandom(4) self._xsrf_token = b"|".join( [ b"2", binascii.b2a_hex(mask), binascii.b2a_hex(_websocket_mask(mask, token)), utf8(str(int(timestamp))), ] ) else: raise ValueError("unknown xsrf cookie version %d", output_version) if version is None: if self.current_user and "expires_days" not in cookie_kwargs: cookie_kwargs["expires_days"] = 30 self.set_cookie("_xsrf", self._xsrf_token, **cookie_kwargs) return self._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 as a potential forgery. See http://en.wikipedia.org/wiki/Cross-site_request_forgery This property is of type `bytes`, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8. .. versionchanged:: 3.2.2 The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the ``xsrf_cookie_version`` `Application` setting is set to 1. .. versionchanged:: 4.3 The ``xsrf_cookie_kwargs`` `Application` setting may be used to supply additional cookie options (which will be passed directly to `set_cookie`). For example, ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)`` will set the ``secure`` and ``httponly`` flags on the ``_xsrf`` cookie. """ 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("xsrf_cookie_kwargs", {}) if output_version == 1: self._xsrf_token = binascii.b2a_hex(token) elif output_version == 2: mask = os.urandom(4) self._xsrf_token = b"|".join( [ b"2", binascii.b2a_hex(mask), binascii.b2a_hex(_websocket_mask(mask, token)), utf8(str(int(timestamp))), ] ) else: raise ValueError("unknown xsrf cookie version %d", output_version) if version is None: if self.current_user and "expires_days" not in cookie_kwargs: cookie_kwargs["expires_days"] = 30 self.set_cookie("_xsrf", self._xsrf_token, **cookie_kwargs) return self._xsrf_token
[ "The", "XSRF", "-", "prevention", "token", "for", "the", "current", "user", "/", "session", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1368-L1422
[ "def", "xsrf_token", "(", "self", ")", "->", "bytes", ":", "if", "not", "hasattr", "(", "self", ",", "\"_xsrf_token\"", ")", ":", "version", ",", "token", ",", "timestamp", "=", "self", ".", "_get_raw_xsrf_token", "(", ")", "output_version", "=", "self", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler._get_raw_xsrf_token
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. * timestamp: the time this token was generated (will not be accurate for version 1 cookies)
tornado/web.py
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. * token: the raw token data; random (non-ascii) bytes. * timestamp: the time this token was generated (will not be accurate for version 1 cookies) """ if not hasattr(self, "_raw_xsrf_token"): cookie = self.get_cookie("_xsrf") if cookie: version, token, timestamp = self._decode_xsrf_token(cookie) else: version, token, timestamp = None, None, None if token is None: version = None token = os.urandom(16) timestamp = time.time() assert token is not None assert timestamp is not None self._raw_xsrf_token = (version, token, timestamp) return self._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. * token: the raw token data; random (non-ascii) bytes. * timestamp: the time this token was generated (will not be accurate for version 1 cookies) """ if not hasattr(self, "_raw_xsrf_token"): cookie = self.get_cookie("_xsrf") if cookie: version, token, timestamp = self._decode_xsrf_token(cookie) else: version, token, timestamp = None, None, None if token is None: version = None token = os.urandom(16) timestamp = time.time() assert token is not None assert timestamp is not None self._raw_xsrf_token = (version, token, timestamp) return self._raw_xsrf_token
[ "Read", "or", "generate", "the", "xsrf", "token", "in", "its", "raw", "form", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1424-L1448
[ "def", "_get_raw_xsrf_token", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "int", "]", ",", "bytes", ",", "float", "]", ":", "if", "not", "hasattr", "(", "self", ",", "\"_raw_xsrf_token\"", ")", ":", "cookie", "=", "self", ".", "get_cookie", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler._decode_xsrf_token
Convert a cookie string into a the tuple form returned by _get_raw_xsrf_token.
tornado/web.py
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: version = int(m.group(1)) if version == 2: _, mask_str, masked_token, timestamp_str = cookie.split("|") mask = binascii.a2b_hex(utf8(mask_str)) token = _websocket_mask(mask, binascii.a2b_hex(utf8(masked_token))) timestamp = int(timestamp_str) return version, token, timestamp else: # Treat unknown versions as not present instead of failing. raise Exception("Unknown xsrf cookie version") else: version = 1 try: token = binascii.a2b_hex(utf8(cookie)) except (binascii.Error, TypeError): token = utf8(cookie) # We don't have a usable timestamp in older versions. timestamp = int(time.time()) return (version, token, timestamp) except Exception: # Catch exceptions and return nothing instead of failing. gen_log.debug("Uncaught exception in _decode_xsrf_token", exc_info=True) return None, None, None
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: version = int(m.group(1)) if version == 2: _, mask_str, masked_token, timestamp_str = cookie.split("|") mask = binascii.a2b_hex(utf8(mask_str)) token = _websocket_mask(mask, binascii.a2b_hex(utf8(masked_token))) timestamp = int(timestamp_str) return version, token, timestamp else: # Treat unknown versions as not present instead of failing. raise Exception("Unknown xsrf cookie version") else: version = 1 try: token = binascii.a2b_hex(utf8(cookie)) except (binascii.Error, TypeError): token = utf8(cookie) # We don't have a usable timestamp in older versions. timestamp = int(time.time()) return (version, token, timestamp) except Exception: # Catch exceptions and return nothing instead of failing. gen_log.debug("Uncaught exception in _decode_xsrf_token", exc_info=True) return None, None, None
[ "Convert", "a", "cookie", "string", "into", "a", "the", "tuple", "form", "returned", "by", "_get_raw_xsrf_token", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1450-L1484
[ "def", "_decode_xsrf_token", "(", "self", ",", "cookie", ":", "str", ")", "->", "Tuple", "[", "Optional", "[", "int", "]", ",", "Optional", "[", "bytes", "]", ",", "Optional", "[", "float", "]", "]", ":", "try", ":", "m", "=", "_signed_value_version_re...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.check_xsrf_cookie
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. The ``_xsrf`` value may be set as either a form field named ``_xsrf`` or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken`` (the latter is accepted for compatibility with Django). See http://en.wikipedia.org/wiki/Cross-site_request_forgery .. versionchanged:: 3.2.2 Added support for cookie version 2. Both versions 1 and 2 are supported.
tornado/web.py
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 reject the form submission as a potential forgery. The ``_xsrf`` value may be set as either a form field named ``_xsrf`` or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken`` (the latter is accepted for compatibility with Django). See http://en.wikipedia.org/wiki/Cross-site_request_forgery .. versionchanged:: 3.2.2 Added support for cookie version 2. Both versions 1 and 2 are supported. """ # 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 please see # http://www.djangoproject.com/weblog/2011/feb/08/security/ # http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails token = ( self.get_argument("_xsrf", None) or self.request.headers.get("X-Xsrftoken") or self.request.headers.get("X-Csrftoken") ) if not token: raise HTTPError(403, "'_xsrf' argument missing from POST") _, token, _ = self._decode_xsrf_token(token) _, expected_token, _ = self._get_raw_xsrf_token() if not token: raise HTTPError(403, "'_xsrf' argument has invalid format") if not hmac.compare_digest(utf8(token), utf8(expected_token)): raise HTTPError(403, "XSRF cookie does not match POST argument")
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 reject the form submission as a potential forgery. The ``_xsrf`` value may be set as either a form field named ``_xsrf`` or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken`` (the latter is accepted for compatibility with Django). See http://en.wikipedia.org/wiki/Cross-site_request_forgery .. versionchanged:: 3.2.2 Added support for cookie version 2. Both versions 1 and 2 are supported. """ # 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 please see # http://www.djangoproject.com/weblog/2011/feb/08/security/ # http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails token = ( self.get_argument("_xsrf", None) or self.request.headers.get("X-Xsrftoken") or self.request.headers.get("X-Csrftoken") ) if not token: raise HTTPError(403, "'_xsrf' argument missing from POST") _, token, _ = self._decode_xsrf_token(token) _, expected_token, _ = self._get_raw_xsrf_token() if not token: raise HTTPError(403, "'_xsrf' argument has invalid format") if not hmac.compare_digest(utf8(token), utf8(expected_token)): raise HTTPError(403, "XSRF cookie does not match POST argument")
[ "Verifies", "that", "the", "_xsrf", "cookie", "matches", "the", "_xsrf", "argument", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1486-L1522
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.static_url
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>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument.
tornado/web.py
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). This method returns a versioned url (by default appending ``?v=<signature>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") get_url = self.settings.get( "static_handler_class", StaticFileHandler ).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
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). This method returns a versioned url (by default appending ``?v=<signature>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") get_url = self.settings.get( "static_handler_class", StaticFileHandler ).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
[ "Returns", "a", "static", "URL", "for", "the", "given", "relative", "static", "file", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1543-L1577
[ "def", "static_url", "(", "self", ",", "path", ":", "str", ",", "include_host", ":", "bool", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "str", ":", "self", ".", "require_setting", "(", "\"static_path\"", ",", "\"static_url\"", ")", "g...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.require_setting
Raises an exception if the given app setting is not defined.
tornado/web.py
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 " "application to use %s" % (name, feature) )
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 " "application to use %s" % (name, feature) )
[ "Raises", "an", "exception", "if", "the", "given", "app", "setting", "is", "not", "defined", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1579-L1585
[ "def", "require_setting", "(", "self", ",", "name", ":", "str", ",", "feature", ":", "str", "=", "\"this feature\"", ")", "->", "None", ":", "if", "not", "self", ".", "application", ".", "settings", ".", "get", "(", "name", ")", ":", "raise", "Exceptio...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.reverse_url
Alias for `Application.reverse_url`.
tornado/web.py
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: """Alias for `Application.reverse_url`.""" return self.application.reverse_url(name, *args)
[ "Alias", "for", "Application", ".", "reverse_url", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1587-L1589
[ "def", "reverse_url", "(", "self", ",", "name", ":", "str", ",", "*", "args", ":", "Any", ")", "->", "str", ":", "return", "self", ".", "application", ".", "reverse_url", "(", "name", ",", "*", "args", ")" ]
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.compute_etag
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.
tornado/web.py
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. """ hasher = hashlib.sha1() for part in self._write_buffer: hasher.update(part) return '"%s"' % hasher.hexdigest()
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. """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1591-L1602
[ "def", "compute_etag", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "hasher", "=", "hashlib", ".", "sha1", "(", ")", "for", "part", "in", "self", ".", "_write_buffer", ":", "hasher", ".", "update", "(", "part", ")", "return", "'\"%s\"'", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.check_etag_header
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 This method is called automatically when the request is finished, but may be called earlier for applications that override `compute_etag` and want to do an early check for ``If-None-Match`` before completing the request. The ``Etag`` header should be set (perhaps with `set_etag_header`) before calling this method.
tornado/web.py
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.set_status(304) return This method is called automatically when the request is finished, but may be called earlier for applications that override `compute_etag` and want to do an early check for ``If-None-Match`` before completing the request. The ``Etag`` header should be set (perhaps with `set_etag_header`) before calling this method. """ 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.findall( br'\*|(?:W/)?"[^"]*"', utf8(self.request.headers.get("If-None-Match", "")) ) if not computed_etag or not etags: return False match = False if etags[0] == b"*": match = True else: # Use a weak comparison when comparing entity-tags. def val(x: bytes) -> bytes: return x[2:] if x.startswith(b"W/") else x for etag in etags: if val(etag) == val(computed_etag): match = True break return match
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.set_status(304) return This method is called automatically when the request is finished, but may be called earlier for applications that override `compute_etag` and want to do an early check for ``If-None-Match`` before completing the request. The ``Etag`` header should be set (perhaps with `set_etag_header`) before calling this method. """ 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.findall( br'\*|(?:W/)?"[^"]*"', utf8(self.request.headers.get("If-None-Match", "")) ) if not computed_etag or not etags: return False match = False if etags[0] == b"*": match = True else: # Use a weak comparison when comparing entity-tags. def val(x: bytes) -> bytes: return x[2:] if x.startswith(b"W/") else x for etag in etags: if val(etag) == val(computed_etag): match = True break return match
[ "Checks", "the", "Etag", "header", "against", "requests", "s", "If", "-", "None", "-", "Match", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1615-L1653
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler._execute
Executes this request with the given output transforms.
tornado/web.py
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: raise HTTPError(405) self.path_args = [self.decode_argument(arg) for arg in args] self.path_kwargs = dict( (k, self.decode_argument(v, name=k)) for (k, v) in kwargs.items() ) # If XSRF cookies are turned on, reject form submissions without # the proper cookie if self.request.method not in ( "GET", "HEAD", "OPTIONS", ) and self.application.settings.get("xsrf_cookies"): self.check_xsrf_cookie() result = self.prepare() if result is not None: result = await result if self._prepared_future is not None: # Tell the Application we've finished with prepare() # and are ready for the body to arrive. future_set_result_unless_cancelled(self._prepared_future, None) if self._finished: return if _has_stream_request_body(self.__class__): # In streaming mode request.body is a Future that signals # the body has been completely received. The Future has no # result; the data has been passed to self.data_received # instead. try: await self.request._body_future except iostream.StreamClosedError: return method = getattr(self, self.request.method.lower()) result = method(*self.path_args, **self.path_kwargs) if result is not None: result = await result if self._auto_finish and not self._finished: self.finish() except Exception as e: try: self._handle_request_exception(e) except Exception: app_log.error("Exception in exception handler", exc_info=True) finally: # Unset result to avoid circular references result = None if self._prepared_future is not None and not self._prepared_future.done(): # In case we failed before setting _prepared_future, do it # now (to unblock the HTTP server). Note that this is not # in a finally block to avoid GC issues prior to Python 3.4. self._prepared_future.set_result(None)
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: raise HTTPError(405) self.path_args = [self.decode_argument(arg) for arg in args] self.path_kwargs = dict( (k, self.decode_argument(v, name=k)) for (k, v) in kwargs.items() ) # If XSRF cookies are turned on, reject form submissions without # the proper cookie if self.request.method not in ( "GET", "HEAD", "OPTIONS", ) and self.application.settings.get("xsrf_cookies"): self.check_xsrf_cookie() result = self.prepare() if result is not None: result = await result if self._prepared_future is not None: # Tell the Application we've finished with prepare() # and are ready for the body to arrive. future_set_result_unless_cancelled(self._prepared_future, None) if self._finished: return if _has_stream_request_body(self.__class__): # In streaming mode request.body is a Future that signals # the body has been completely received. The Future has no # result; the data has been passed to self.data_received # instead. try: await self.request._body_future except iostream.StreamClosedError: return method = getattr(self, self.request.method.lower()) result = method(*self.path_args, **self.path_kwargs) if result is not None: result = await result if self._auto_finish and not self._finished: self.finish() except Exception as e: try: self._handle_request_exception(e) except Exception: app_log.error("Exception in exception handler", exc_info=True) finally: # Unset result to avoid circular references result = None if self._prepared_future is not None and not self._prepared_future.done(): # In case we failed before setting _prepared_future, do it # now (to unblock the HTTP server). Note that this is not # in a finally block to avoid GC issues prior to Python 3.4. self._prepared_future.set_result(None)
[ "Executes", "this", "request", "with", "the", "given", "output", "transforms", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1655-L1714
[ "async", "def", "_execute", "(", "self", ",", "transforms", ":", "List", "[", "\"OutputTransform\"", "]", ",", "*", "args", ":", "bytes", ",", "*", "*", "kwargs", ":", "bytes", ")", "->", "None", ":", "self", ".", "_transforms", "=", "transforms", "try...
b8b481770bcdb333a69afde5cce7eaa449128326
train
RequestHandler.log_exception
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.1
tornado/web.py
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 traces (on the ``tornado.general`` logger), and all other exceptions as errors with stack traces (on the ``tornado.application`` logger). .. versionadded:: 3.1 """ if isinstance(value, HTTPError): if value.log_message: format = "%d %s: " + value.log_message args = [value.status_code, self._request_summary()] + list(value.args) gen_log.warning(format, *args) else: app_log.error( # type: ignore "Uncaught exception %s\n%r", self._request_summary(), self.request, exc_info=(typ, value, tb), )
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 traces (on the ``tornado.general`` logger), and all other exceptions as errors with stack traces (on the ``tornado.application`` logger). .. versionadded:: 3.1 """ if isinstance(value, HTTPError): if value.log_message: format = "%d %s: " + value.log_message args = [value.status_code, self._request_summary()] + list(value.args) gen_log.warning(format, *args) else: app_log.error( # type: ignore "Uncaught exception %s\n%r", self._request_summary(), self.request, exc_info=(typ, value, tb), )
[ "Override", "to", "customize", "logging", "of", "uncaught", "exceptions", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1763-L1789
[ "def", "log_exception", "(", "self", ",", "typ", ":", "\"Optional[Type[BaseException]]\"", ",", "value", ":", "Optional", "[", "BaseException", "]", ",", "tb", ":", "Optional", "[", "TracebackType", "]", ",", ")", "->", "None", ":", "if", "isinstance", "(", ...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Application.listen
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 advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. Returns the `.HTTPServer` object. .. versionchanged:: 4.3 Now returns the `.HTTPServer` object.
tornado/web.py
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.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. Returns the `.HTTPServer` object. .. versionchanged:: 4.3 Now returns the `.HTTPServer` object. """ server = HTTPServer(self, **kwargs) server.listen(port, address) return server
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.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. Returns the `.HTTPServer` object. .. versionchanged:: 4.3 Now returns the `.HTTPServer` object. """ server = HTTPServer(self, **kwargs) server.listen(port, address) return server
[ "Starts", "an", "HTTP", "server", "for", "this", "application", "on", "the", "given", "port", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2092-L2113
[ "def", "listen", "(", "self", ",", "port", ":", "int", ",", "address", ":", "str", "=", "\"\"", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "HTTPServer", ":", "server", "=", "HTTPServer", "(", "self", ",", "*", "*", "kwargs", ")", "server", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Application.add_handlers
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.
tornado/web.py
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_pattern) rule = Rule(host_matcher, _ApplicationRouter(self, host_handlers)) self.default_router.rules.insert(-1, rule) if self.default_host is not None: self.wildcard_router.add_rules( [(DefaultHostMatches(self, host_matcher.host_pattern), host_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_pattern) rule = Rule(host_matcher, _ApplicationRouter(self, host_handlers)) self.default_router.rules.insert(-1, rule) if self.default_host is not None: self.wildcard_router.add_rules( [(DefaultHostMatches(self, host_matcher.host_pattern), host_handlers)] )
[ "Appends", "the", "given", "handlers", "to", "our", "handler", "list", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2115-L2129
[ "def", "add_handlers", "(", "self", ",", "host_pattern", ":", "str", ",", "host_handlers", ":", "_RuleList", ")", "->", "None", ":", "host_matcher", "=", "HostMatches", "(", "host_pattern", ")", "rule", "=", "Rule", "(", "host_matcher", ",", "_ApplicationRoute...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Application.get_handler_delegate
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 ``target_class`` constructor. :arg list path_args: positional arguments for ``target_class`` HTTP method that will be executed while handling a request (``get``, ``post`` or any other). :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method.
tornado/web.py
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.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 ``target_class`` constructor. :arg list path_args: positional arguments for ``target_class`` HTTP method that will be executed while handling a request (``get``, ``post`` or any other). :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method. """ return _HandlerDelegate( self, request, target_class, target_kwargs, path_args, path_kwargs )
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.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 ``target_class`` constructor. :arg list path_args: positional arguments for ``target_class`` HTTP method that will be executed while handling a request (``get``, ``post`` or any other). :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method. """ return _HandlerDelegate( self, request, target_class, target_kwargs, path_args, path_kwargs )
[ "Returns", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "a", "request", "for", "application", "and", "RequestHandler", "subclass", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2187-L2207
[ "def", "get_handler_delegate", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "target_class", ":", "Type", "[", "RequestHandler", "]", ",", "target_kwargs", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "path_args"...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Application.reverse_url
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.
tornado/web.py
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, encoded as utf8, and url-escaped. """ 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)
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, encoded as utf8, and url-escaped. """ 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" ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2209-L2222
[ "def", "reverse_url", "(", "self", ",", "name", ":", "str", ",", "*", "args", ":", "Any", ")", "->", "str", ":", "reversed_url", "=", "self", ".", "default_router", ".", "reverse_url", "(", "name", ",", "*", "args", ")", "if", "reversed_url", "is", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
Application.log_request
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``.
tornado/web.py
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 as ``log_function``. """ if "log_function" in self.settings: self.settings["log_function"](handler) return if handler.get_status() < 400: log_method = access_log.info elif handler.get_status() < 500: log_method = access_log.warning else: log_method = access_log.error request_time = 1000.0 * handler.request.request_time() log_method( "%d %s %.2fms", handler.get_status(), handler._request_summary(), request_time, )
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 as ``log_function``. """ if "log_function" in self.settings: self.settings["log_function"](handler) return if handler.get_status() < 400: log_method = access_log.info elif handler.get_status() < 500: log_method = access_log.warning else: log_method = access_log.error request_time = 1000.0 * handler.request.request_time() log_method( "%d %s %.2fms", handler.get_status(), handler._request_summary(), request_time, )
[ "Writes", "a", "completed", "HTTP", "request", "to", "the", "logs", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2224-L2247
[ "def", "log_request", "(", "self", ",", "handler", ":", "RequestHandler", ")", "->", "None", ":", "if", "\"log_function\"", "in", "self", ".", "settings", ":", "self", ".", "settings", "[", "\"log_function\"", "]", "(", "handler", ")", "return", "if", "han...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.compute_etag
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
tornado/web.py
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). .. versionadded:: 3.1 """ 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,)
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). .. versionadded:: 3.1 """ 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", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2655-L2668
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.set_headers
Sets the content and caching headers on the response. .. versionadded:: 3.1
tornado/web.py
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) content_type = self.get_content_type() if content_type: self.set_header("Content-Type", content_type) cache_time = self.get_cache_time(self.path, self.modified, content_type) if cache_time > 0: self.set_header( "Expires", datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time), ) self.set_header("Cache-Control", "max-age=" + str(cache_time)) self.set_extra_headers(self.path)
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) content_type = self.get_content_type() if content_type: self.set_header("Content-Type", content_type) cache_time = self.get_cache_time(self.path, self.modified, content_type) if cache_time > 0: self.set_header( "Expires", datetime.datetime.utcnow() + datetime.timedelta(seconds=cache_time), ) self.set_header("Cache-Control", "max-age=" + str(cache_time)) self.set_extra_headers(self.path)
[ "Sets", "the", "content", "and", "caching", "headers", "on", "the", "response", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2670-L2693
[ "def", "set_headers", "(", "self", ")", "->", "None", ":", "self", ".", "set_header", "(", "\"Accept-Ranges\"", ",", "\"bytes\"", ")", "self", ".", "set_etag_header", "(", ")", "if", "self", ".", "modified", "is", "not", "None", ":", "self", ".", "set_he...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.should_return_304
Returns True if the headers indicate that we should return 304. .. versionadded:: 3.1
tornado/web.py
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_header() # Check the If-Modified-Since, and don't send the result if the # content has not been modified ims_value = self.request.headers.get("If-Modified-Since") if ims_value is not None: date_tuple = email.utils.parsedate(ims_value) if date_tuple is not None: if_since = datetime.datetime(*date_tuple[:6]) assert self.modified is not None if if_since >= self.modified: return True return False
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_header() # Check the If-Modified-Since, and don't send the result if the # content has not been modified ims_value = self.request.headers.get("If-Modified-Since") if ims_value is not None: date_tuple = email.utils.parsedate(ims_value) if date_tuple is not None: if_since = datetime.datetime(*date_tuple[:6]) assert self.modified is not None if if_since >= self.modified: return True return False
[ "Returns", "True", "if", "the", "headers", "indicate", "that", "we", "should", "return", "304", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2695-L2715
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.get_absolute_path
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 strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1
tornado/web.py
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 subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath
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 subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath
[ "Returns", "the", "absolute", "location", "of", "path", "relative", "to", "root", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2718-L2732
[ "def", "get_absolute_path", "(", "cls", ",", "root", ":", "str", ",", "path", ":", "str", ")", "->", "str", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "path", ")", ")", "return",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.validate_absolute_path
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.redirect` (return None after redirecting to halt further processing). This is where 404 errors for missing files are generated. This method may modify the path before returning it, but note that any such modifications will not be understood by `make_static_url`. In instance methods, this method's result is available as ``self.absolute_path``. .. versionadded:: 3.1
tornado/web.py
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 processing, so it may raise `HTTPError` or use methods like `RequestHandler.redirect` (return None after redirecting to halt further processing). This is where 404 errors for missing files are generated. This method may modify the path before returning it, but note that any such modifications will not be understood by `make_static_url`. In instance methods, this method's result is available as ``self.absolute_path``. .. versionadded:: 3.1 """ # 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 # that prefix. root = os.path.abspath(root) if not root.endswith(os.path.sep): # abspath always removes a trailing slash, except when # root is '/'. This is an unusual case, but several projects # have independently discovered this technique to disable # Tornado's path validation and (hopefully) do their own, # so we need to support it. root += os.path.sep # The trailing slash also needs to be temporarily added back # the requested path so a request to root/ will match. if not (absolute_path + os.path.sep).startswith(root): raise HTTPError(403, "%s is not in root static directory", self.path) if os.path.isdir(absolute_path) and self.default_filename is not None: # need to look at the request.path here for when path is empty # but there is some prefix to the path that was already # trimmed by the routing if not self.request.path.endswith("/"): self.redirect(self.request.path + "/", permanent=True) return None absolute_path = os.path.join(absolute_path, self.default_filename) if not os.path.exists(absolute_path): raise HTTPError(404) if not os.path.isfile(absolute_path): raise HTTPError(403, "%s is not a file", self.path) return 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 processing, so it may raise `HTTPError` or use methods like `RequestHandler.redirect` (return None after redirecting to halt further processing). This is where 404 errors for missing files are generated. This method may modify the path before returning it, but note that any such modifications will not be understood by `make_static_url`. In instance methods, this method's result is available as ``self.absolute_path``. .. versionadded:: 3.1 """ # 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 # that prefix. root = os.path.abspath(root) if not root.endswith(os.path.sep): # abspath always removes a trailing slash, except when # root is '/'. This is an unusual case, but several projects # have independently discovered this technique to disable # Tornado's path validation and (hopefully) do their own, # so we need to support it. root += os.path.sep # The trailing slash also needs to be temporarily added back # the requested path so a request to root/ will match. if not (absolute_path + os.path.sep).startswith(root): raise HTTPError(403, "%s is not in root static directory", self.path) if os.path.isdir(absolute_path) and self.default_filename is not None: # need to look at the request.path here for when path is empty # but there is some prefix to the path that was already # trimmed by the routing if not self.request.path.endswith("/"): self.redirect(self.request.path + "/", permanent=True) return None absolute_path = os.path.join(absolute_path, self.default_filename) if not os.path.exists(absolute_path): raise HTTPError(404) if not os.path.isfile(absolute_path): raise HTTPError(403, "%s is not a file", self.path) return absolute_path
[ "Validate", "and", "return", "the", "absolute", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2734-L2782
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.get_content
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 ``abspath`` is able to stand on its own as a cache key. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation. .. versionadded:: 3.1
tornado/web.py
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 signature is different from other overridable class methods (no ``settings`` argument); this is deliberate to ensure that ``abspath`` is able to stand on its own as a cache key. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation. .. versionadded:: 3.1 """ with open(abspath, "rb") as file: if start is not None: file.seek(start) if end is not None: remaining = end - (start or 0) # type: Optional[int] else: remaining = None while True: chunk_size = 64 * 1024 if remaining is not None and remaining < chunk_size: chunk_size = remaining chunk = file.read(chunk_size) if chunk: if remaining is not None: remaining -= len(chunk) yield chunk else: if remaining is not None: assert remaining == 0 return
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 signature is different from other overridable class methods (no ``settings`` argument); this is deliberate to ensure that ``abspath`` is able to stand on its own as a cache key. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation. .. versionadded:: 3.1 """ with open(abspath, "rb") as file: if start is not None: file.seek(start) if end is not None: remaining = end - (start or 0) # type: Optional[int] else: remaining = None while True: chunk_size = 64 * 1024 if remaining is not None and remaining < chunk_size: chunk_size = remaining chunk = file.read(chunk_size) if chunk: if remaining is not None: remaining -= len(chunk) yield chunk else: if remaining is not None: assert remaining == 0 return
[ "Retrieve", "the", "content", "of", "the", "requested", "resource", "which", "is", "located", "at", "the", "given", "absolute", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2785-L2821
[ "def", "get_content", "(", "cls", ",", "abspath", ":", "str", ",", "start", ":", "int", "=", "None", ",", "end", ":", "int", "=", "None", ")", "->", "Generator", "[", "bytes", ",", "None", ",", "None", "]", ":", "with", "open", "(", "abspath", ",...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.get_content_version
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
tornado/web.py
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_content(abspath) hasher = hashlib.md5() if isinstance(data, bytes): hasher.update(data) else: for chunk in data: hasher.update(chunk) return hasher.hexdigest()
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_content(abspath) hasher = hashlib.md5() if isinstance(data, bytes): hasher.update(data) else: for chunk in data: hasher.update(chunk) return hasher.hexdigest()
[ "Returns", "a", "version", "string", "for", "the", "resource", "at", "the", "given", "path", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2824-L2839
[ "def", "get_content_version", "(", "cls", ",", "abspath", ":", "str", ")", "->", "str", ":", "data", "=", "cls", ".", "get_content", "(", "abspath", ")", "hasher", "=", "hashlib", ".", "md5", "(", ")", "if", "isinstance", "(", "data", ",", "bytes", "...
b8b481770bcdb333a69afde5cce7eaa449128326
train
StaticFileHandler.get_modified_time
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
tornado/web.py
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() # NOTE: Historically, this used stat_result[stat.ST_MTIME], # which truncates the fractional portion of the timestamp. It # was changed from that form to stat_result.st_mtime to # satisfy mypy (which disallows the bracket operator), but the # latter form returns a float instead of an int. For # consistency with the past (and because we have a unit test # that relies on this), we truncate the float here, although # I'm not sure that's the right thing to do. modified = datetime.datetime.utcfromtimestamp(int(stat_result.st_mtime)) return modified
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() # NOTE: Historically, this used stat_result[stat.ST_MTIME], # which truncates the fractional portion of the timestamp. It # was changed from that form to stat_result.st_mtime to # satisfy mypy (which disallows the bracket operator), but the # latter form returns a float instead of an int. For # consistency with the past (and because we have a unit test # that relies on this), we truncate the float here, although # I'm not sure that's the right thing to do. modified = datetime.datetime.utcfromtimestamp(int(stat_result.st_mtime)) return modified
[ "Returns", "the", "time", "that", "self", ".", "absolute_path", "was", "last", "modified", "." ]
tornadoweb/tornado
python
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2861-L2879
[ "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...
b8b481770bcdb333a69afde5cce7eaa449128326