repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
tornadoweb/tornado
tornado/web.py
RequestHandler.xsrf_token
def xsrf_token(self) -> bytes: """The XSRF-prevention token for the current user/session. To prevent cross-site request forgery, we set an '_xsrf' cookie and include the same '_xsrf' value as an argument with all POST requests. If the two do not match, we reject the form submission 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
python
def xsrf_token(self) -> bytes: """The XSRF-prevention token for the current user/session. To prevent cross-site request forgery, we set an '_xsrf' cookie and include the same '_xsrf' value as an argument with all POST requests. If the two do not match, we reject the form submission 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", ":", "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. 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.
[ "The", "XSRF", "-", "prevention", "token", "for", "the", "current", "user", "/", "session", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1368-L1422
train
tornadoweb/tornado
tornado/web.py
RequestHandler._get_raw_xsrf_token
def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]: """Read or generate the xsrf token in its raw form. The raw_xsrf_token is a tuple containing: * version: the version of the cookie from which this token was read, or None if we generated a new token in this request. * 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
python
def _get_raw_xsrf_token(self) -> Tuple[Optional[int], bytes, float]: """Read or generate the xsrf token in its raw form. The raw_xsrf_token is a tuple containing: * version: the version of the cookie from which this token was read, or None if we generated a new token in this request. * 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", "]", ":", "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. 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)
[ "Read", "or", "generate", "the", "xsrf", "token", "in", "its", "raw", "form", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1424-L1448
train
tornadoweb/tornado
tornado/web.py
RequestHandler._decode_xsrf_token
def _decode_xsrf_token( self, cookie: str ) -> Tuple[Optional[int], Optional[bytes], Optional[float]]: """Convert a cookie string into a the tuple form returned by _get_raw_xsrf_token. """ try: m = _signed_value_version_re.match(utf8(cookie)) if m: 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
python
def _decode_xsrf_token( self, cookie: str ) -> Tuple[Optional[int], Optional[bytes], Optional[float]]: """Convert a cookie string into a the tuple form returned by _get_raw_xsrf_token. """ try: m = _signed_value_version_re.match(utf8(cookie)) if m: 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", "]", "]", ":", "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.
[ "Convert", "a", "cookie", "string", "into", "a", "the", "tuple", "form", "returned", "by", "_get_raw_xsrf_token", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1450-L1484
train
tornadoweb/tornado
tornado/web.py
RequestHandler.check_xsrf_cookie
def check_xsrf_cookie(self) -> None: """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. To prevent cross-site request forgery, we set an ``_xsrf`` cookie and include the same value as a non-cookie field with all ``POST`` requests. If the two do not match, we 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")
python
def check_xsrf_cookie(self) -> None: """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument. To prevent cross-site request forgery, we set an ``_xsrf`` cookie and include the same value as a non-cookie field with all ``POST`` requests. If the two do not match, we 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", ":", "# 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. 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.
[ "Verifies", "that", "the", "_xsrf", "cookie", "matches", "the", "_xsrf", "argument", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1486-L1522
train
tornadoweb/tornado
tornado/web.py
RequestHandler.static_url
def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str: """Returns a static URL for the given relative static file path. This method requires you set the ``static_path`` setting in your application (which specifies the root directory of your static files). 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)
python
def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str: """Returns a static URL for the given relative static file path. This method requires you set the ``static_path`` setting in your application (which specifies the root directory of your static files). 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", ":", "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. 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.
[ "Returns", "a", "static", "URL", "for", "the", "given", "relative", "static", "file", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1543-L1577
train
tornadoweb/tornado
tornado/web.py
RequestHandler.require_setting
def require_setting(self, name: str, feature: str = "this feature") -> None: """Raises an exception if the given app setting is not defined.""" if not self.application.settings.get(name): raise Exception( "You must define the '%s' setting in your " "application to use %s" % (name, feature) )
python
def require_setting(self, name: str, feature: str = "this feature") -> None: """Raises an exception if the given app setting is not defined.""" if not self.application.settings.get(name): raise Exception( "You must define the '%s' setting in your " "application to use %s" % (name, feature) )
[ "def", "require_setting", "(", "self", ",", "name", ":", "str", ",", "feature", ":", "str", "=", "\"this feature\"", ")", "->", "None", ":", "if", "not", "self", ".", "application", ".", "settings", ".", "get", "(", "name", ")", ":", "raise", "Exception", "(", "\"You must define the '%s' setting in your \"", "\"application to use %s\"", "%", "(", "name", ",", "feature", ")", ")" ]
Raises an exception if the given app setting is not defined.
[ "Raises", "an", "exception", "if", "the", "given", "app", "setting", "is", "not", "defined", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1579-L1585
train
tornadoweb/tornado
tornado/web.py
RequestHandler.reverse_url
def reverse_url(self, name: str, *args: Any) -> str: """Alias for `Application.reverse_url`.""" return self.application.reverse_url(name, *args)
python
def reverse_url(self, name: str, *args: Any) -> str: """Alias for `Application.reverse_url`.""" return self.application.reverse_url(name, *args)
[ "def", "reverse_url", "(", "self", ",", "name", ":", "str", ",", "*", "args", ":", "Any", ")", "->", "str", ":", "return", "self", ".", "application", ".", "reverse_url", "(", "name", ",", "*", "args", ")" ]
Alias for `Application.reverse_url`.
[ "Alias", "for", "Application", ".", "reverse_url", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1587-L1589
train
tornadoweb/tornado
tornado/web.py
RequestHandler.compute_etag
def compute_etag(self) -> Optional[str]: """Computes the etag header to be used for this request. By default uses a hash of the content written so far. May be overridden to provide custom etag implementations, or may return None to disable tornado's default etag support. """ hasher = hashlib.sha1() for part in self._write_buffer: hasher.update(part) return '"%s"' % hasher.hexdigest()
python
def compute_etag(self) -> Optional[str]: """Computes the etag header to be used for this request. By default uses a hash of the content written so far. May be overridden to provide custom etag implementations, or may return None to disable tornado's default etag support. """ hasher = hashlib.sha1() for part in self._write_buffer: hasher.update(part) return '"%s"' % hasher.hexdigest()
[ "def", "compute_etag", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "hasher", "=", "hashlib", ".", "sha1", "(", ")", "for", "part", "in", "self", ".", "_write_buffer", ":", "hasher", ".", "update", "(", "part", ")", "return", "'\"%s\"'", "%", "hasher", ".", "hexdigest", "(", ")" ]
Computes the etag header to be used for this request. By default uses a hash of the content written so far. May be overridden to provide custom etag implementations, or may return None to disable tornado's default etag support.
[ "Computes", "the", "etag", "header", "to", "be", "used", "for", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1591-L1602
train
tornadoweb/tornado
tornado/web.py
RequestHandler.check_etag_header
def check_etag_header(self) -> bool: """Checks the ``Etag`` header against requests's ``If-None-Match``. Returns ``True`` if the request's Etag matches and a 304 should be returned. For example:: self.set_etag_header() if self.check_etag_header(): self.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
python
def check_etag_header(self) -> bool: """Checks the ``Etag`` header against requests's ``If-None-Match``. Returns ``True`` if the request's Etag matches and a 304 should be returned. For example:: self.set_etag_header() if self.check_etag_header(): self.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", ":", "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``. 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.
[ "Checks", "the", "Etag", "header", "against", "requests", "s", "If", "-", "None", "-", "Match", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1615-L1653
train
tornadoweb/tornado
tornado/web.py
RequestHandler._execute
async def _execute( self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes ) -> None: """Executes this request with the given output transforms.""" self._transforms = transforms try: if self.request.method not in self.SUPPORTED_METHODS: 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)
python
async def _execute( self, transforms: List["OutputTransform"], *args: bytes, **kwargs: bytes ) -> None: """Executes this request with the given output transforms.""" self._transforms = transforms try: if self.request.method not in self.SUPPORTED_METHODS: 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", ":", "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.
[ "Executes", "this", "request", "with", "the", "given", "output", "transforms", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1655-L1714
train
tornadoweb/tornado
tornado/web.py
RequestHandler.log_exception
def log_exception( self, typ: "Optional[Type[BaseException]]", value: Optional[BaseException], tb: Optional[TracebackType], ) -> None: """Override to customize logging of uncaught exceptions. By default logs instances of `HTTPError` as warnings without stack 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), )
python
def log_exception( self, typ: "Optional[Type[BaseException]]", value: Optional[BaseException], tb: Optional[TracebackType], ) -> None: """Override to customize logging of uncaught exceptions. By default logs instances of `HTTPError` as warnings without stack 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", ":", "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. 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
[ "Override", "to", "customize", "logging", "of", "uncaught", "exceptions", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1763-L1789
train
tornadoweb/tornado
tornado/web.py
Application.listen
def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer: """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.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
python
def listen(self, port: int, address: str = "", **kwargs: Any) -> HTTPServer: """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.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", ":", "server", "=", "HTTPServer", "(", "self", ",", "*", "*", "kwargs", ")", "server", ".", "listen", "(", "port", ",", "address", ")", "return", "server" ]
Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For 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.
[ "Starts", "an", "HTTP", "server", "for", "this", "application", "on", "the", "given", "port", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2092-L2113
train
tornadoweb/tornado
tornado/web.py
Application.add_handlers
def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None: """Appends the given handlers to our handler list. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered. """ host_matcher = HostMatches(host_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)] )
python
def add_handlers(self, host_pattern: str, host_handlers: _RuleList) -> None: """Appends the given handlers to our handler list. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered. """ host_matcher = HostMatches(host_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", ":", "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. Host patterns are processed sequentially in the order they were added. All matching patterns will be considered.
[ "Appends", "the", "given", "handlers", "to", "our", "handler", "list", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2115-L2129
train
tornadoweb/tornado
tornado/web.py
Application.get_handler_delegate
def get_handler_delegate( self, request: httputil.HTTPServerRequest, target_class: Type[RequestHandler], target_kwargs: Dict[str, Any] = None, path_args: List[bytes] = None, path_kwargs: Dict[str, bytes] = None, ) -> "_HandlerDelegate": """Returns `~.httputil.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 )
python
def get_handler_delegate( self, request: httputil.HTTPServerRequest, target_class: Type[RequestHandler], target_kwargs: Dict[str, Any] = None, path_args: List[bytes] = None, path_kwargs: Dict[str, bytes] = None, ) -> "_HandlerDelegate": """Returns `~.httputil.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\"", ":", "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. :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.
[ "Returns", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "a", "request", "for", "application", "and", "RequestHandler", "subclass", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2187-L2207
train
tornadoweb/tornado
tornado/web.py
Application.reverse_url
def reverse_url(self, name: str, *args: Any) -> str: """Returns a URL path for handler named ``name`` The handler must be added to the application as a named `URLSpec`. Args will be substituted for capturing groups in the `URLSpec` regex. They will be converted to strings if necessary, 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)
python
def reverse_url(self, name: str, *args: Any) -> str: """Returns a URL path for handler named ``name`` The handler must be added to the application as a named `URLSpec`. Args will be substituted for capturing groups in the `URLSpec` regex. They will be converted to strings if necessary, 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", ":", "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`` The handler must be added to the application as a named `URLSpec`. Args will be substituted for capturing groups in the `URLSpec` regex. They will be converted to strings if necessary, encoded as utf8, and url-escaped.
[ "Returns", "a", "URL", "path", "for", "handler", "named", "name" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2209-L2222
train
tornadoweb/tornado
tornado/web.py
Application.log_request
def log_request(self, handler: RequestHandler) -> None: """Writes a completed HTTP request to the logs. By default writes to the python root logger. To change this behavior either subclass Application and override this method, or pass a function in the application settings dictionary 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, )
python
def log_request(self, handler: RequestHandler) -> None: """Writes a completed HTTP request to the logs. By default writes to the python root logger. To change this behavior either subclass Application and override this method, or pass a function in the application settings dictionary 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", ":", "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. By default writes to the python root logger. To change this behavior either subclass Application and override this method, or pass a function in the application settings dictionary as ``log_function``.
[ "Writes", "a", "completed", "HTTP", "request", "to", "the", "logs", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2224-L2247
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.compute_etag
def compute_etag(self) -> Optional[str]: """Sets the ``Etag`` header based on static url version. This allows efficient ``If-None-Match`` checks against cached versions, and sends the correct ``Etag`` for a partial response (i.e. the same ``Etag`` as the full file). .. 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,)
python
def compute_etag(self) -> Optional[str]: """Sets the ``Etag`` header based on static url version. This allows efficient ``If-None-Match`` checks against cached versions, and sends the correct ``Etag`` for a partial response (i.e. the same ``Etag`` as the full file). .. 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", "]", ":", "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. This allows efficient ``If-None-Match`` checks against cached versions, and sends the correct ``Etag`` for a partial response (i.e. the same ``Etag`` as the full file). .. versionadded:: 3.1
[ "Sets", "the", "Etag", "header", "based", "on", "static", "url", "version", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2655-L2668
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.set_headers
def set_headers(self) -> None: """Sets the content and caching headers on the response. .. versionadded:: 3.1 """ self.set_header("Accept-Ranges", "bytes") self.set_etag_header() if self.modified is not None: self.set_header("Last-Modified", self.modified) 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)
python
def set_headers(self) -> None: """Sets the content and caching headers on the response. .. versionadded:: 3.1 """ self.set_header("Accept-Ranges", "bytes") self.set_etag_header() if self.modified is not None: self.set_header("Last-Modified", self.modified) 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", ":", "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. .. versionadded:: 3.1
[ "Sets", "the", "content", "and", "caching", "headers", "on", "the", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2670-L2693
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.should_return_304
def should_return_304(self) -> bool: """Returns True if the headers indicate that we should return 304. .. versionadded:: 3.1 """ # If client sent If-None-Match, use it, ignore If-Modified-Since if self.request.headers.get("If-None-Match"): return self.check_etag_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
python
def should_return_304(self) -> bool: """Returns True if the headers indicate that we should return 304. .. versionadded:: 3.1 """ # If client sent If-None-Match, use it, ignore If-Modified-Since if self.request.headers.get("If-None-Match"): return self.check_etag_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", ":", "# 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. .. versionadded:: 3.1
[ "Returns", "True", "if", "the", "headers", "indicate", "that", "we", "should", "return", "304", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2695-L2715
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_absolute_path
def get_absolute_path(cls, root: str, path: str) -> str: """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in 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
python
def get_absolute_path(cls, root: str, path: str) -> str: """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in 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", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "path", ")", ")", "return", "abspath" ]
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
[ "Returns", "the", "absolute", "location", "of", "path", "relative", "to", "root", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2718-L2732
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.validate_absolute_path
def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]: """Validate and return the absolute path. ``root`` is the configured path for the `StaticFileHandler`, and ``path`` is the result of `get_absolute_path` This is an instance method called during request 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
python
def validate_absolute_path(self, root: str, absolute_path: str) -> Optional[str]: """Validate and return the absolute path. ``root`` is the configured path for the `StaticFileHandler`, and ``path`` is the result of `get_absolute_path` This is an instance method called during request 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", "]", ":", "# 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. ``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
[ "Validate", "and", "return", "the", "absolute", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2734-L2782
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_content
def get_content( cls, abspath: str, start: int = None, end: int = None ) -> Generator[bytes, None, None]: """Retrieve the content of the requested resource which is located at the given absolute path. This class method may be overridden by subclasses. Note that its 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
python
def get_content( cls, abspath: str, start: int = None, end: int = None ) -> Generator[bytes, None, None]: """Retrieve the content of the requested resource which is located at the given absolute path. This class method may be overridden by subclasses. Note that its 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", "]", ":", "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. 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
[ "Retrieve", "the", "content", "of", "the", "requested", "resource", "which", "is", "located", "at", "the", "given", "absolute", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2785-L2821
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_content_version
def get_content_version(cls, abspath: str) -> str: """Returns a version string for the resource at the given path. This class method may be overridden by subclasses. The default implementation is a hash of the file's contents. .. versionadded:: 3.1 """ data = cls.get_content(abspath) hasher = hashlib.md5() if isinstance(data, bytes): hasher.update(data) else: for chunk in data: hasher.update(chunk) return hasher.hexdigest()
python
def get_content_version(cls, abspath: str) -> str: """Returns a version string for the resource at the given path. This class method may be overridden by subclasses. The default implementation is a hash of the file's contents. .. versionadded:: 3.1 """ data = cls.get_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", ":", "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. This class method may be overridden by subclasses. The default implementation is a hash of the file's contents. .. versionadded:: 3.1
[ "Returns", "a", "version", "string", "for", "the", "resource", "at", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2824-L2839
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_modified_time
def get_modified_time(self) -> Optional[datetime.datetime]: """Returns the time that ``self.absolute_path`` was last modified. May be overridden in subclasses. Should return a `~datetime.datetime` object or None. .. versionadded:: 3.1 """ stat_result = self._stat() # 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
python
def get_modified_time(self) -> Optional[datetime.datetime]: """Returns the time that ``self.absolute_path`` was last modified. May be overridden in subclasses. Should return a `~datetime.datetime` object or None. .. versionadded:: 3.1 """ stat_result = self._stat() # 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", "]", ":", "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. May be overridden in subclasses. Should return a `~datetime.datetime` object or None. .. versionadded:: 3.1
[ "Returns", "the", "time", "that", "self", ".", "absolute_path", "was", "last", "modified", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2861-L2879
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_content_type
def get_content_type(self) -> str: """Returns the ``Content-Type`` header to be used for this request. .. versionadded:: 3.1 """ assert self.absolute_path is not None mime_type, encoding = mimetypes.guess_type(self.absolute_path) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. elif encoding is not None: return "application/octet-stream" elif mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream else: return "application/octet-stream"
python
def get_content_type(self) -> str: """Returns the ``Content-Type`` header to be used for this request. .. versionadded:: 3.1 """ assert self.absolute_path is not None mime_type, encoding = mimetypes.guess_type(self.absolute_path) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. elif encoding is not None: return "application/octet-stream" elif mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream else: return "application/octet-stream"
[ "def", "get_content_type", "(", "self", ")", "->", "str", ":", "assert", "self", ".", "absolute_path", "is", "not", "None", "mime_type", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "self", ".", "absolute_path", ")", "# per RFC 6713, use the appropriate type for a gzip compressed file", "if", "encoding", "==", "\"gzip\"", ":", "return", "\"application/gzip\"", "# As of 2015-07-21 there is no bzip2 encoding defined at", "# http://www.iana.org/assignments/media-types/media-types.xhtml", "# So for that (and any other encoding), use octet-stream.", "elif", "encoding", "is", "not", "None", ":", "return", "\"application/octet-stream\"", "elif", "mime_type", "is", "not", "None", ":", "return", "mime_type", "# if mime_type not detected, use application/octet-stream", "else", ":", "return", "\"application/octet-stream\"" ]
Returns the ``Content-Type`` header to be used for this request. .. versionadded:: 3.1
[ "Returns", "the", "Content", "-", "Type", "header", "to", "be", "used", "for", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2881-L2900
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_cache_time
def get_cache_time( self, path: str, modified: Optional[datetime.datetime], mime_type: str ) -> int: """Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics). By default returns cache expiry of 10 years for resources requested with ``v`` argument. """ return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0
python
def get_cache_time( self, path: str, modified: Optional[datetime.datetime], mime_type: str ) -> int: """Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics). By default returns cache expiry of 10 years for resources requested with ``v`` argument. """ return self.CACHE_MAX_AGE if "v" in self.request.arguments else 0
[ "def", "get_cache_time", "(", "self", ",", "path", ":", "str", ",", "modified", ":", "Optional", "[", "datetime", ".", "datetime", "]", ",", "mime_type", ":", "str", ")", "->", "int", ":", "return", "self", ".", "CACHE_MAX_AGE", "if", "\"v\"", "in", "self", ".", "request", ".", "arguments", "else", "0" ]
Override to customize cache control behavior. Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics). By default returns cache expiry of 10 years for resources requested with ``v`` argument.
[ "Override", "to", "customize", "cache", "control", "behavior", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2906-L2919
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.make_static_url
def make_static_url( cls, settings: Dict[str, Any], path: str, include_version: bool = True ) -> str: """Constructs a versioned url for the given path. This method may be overridden in subclasses (but note that it is a class method rather than an instance method). Subclasses are only required to implement the signature ``make_static_url(cls, settings, path)``; other keyword arguments may be passed through `~RequestHandler.static_url` but are not standard. ``settings`` is the `Application.settings` dictionary. ``path`` is the static path being requested. The url returned should be relative to the current host. ``include_version`` determines whether the generated URL should include the query string containing the version hash of the file corresponding to the given ``path``. """ url = settings.get("static_url_prefix", "/static/") + path if not include_version: return url version_hash = cls.get_version(settings, path) if not version_hash: return url return "%s?v=%s" % (url, version_hash)
python
def make_static_url( cls, settings: Dict[str, Any], path: str, include_version: bool = True ) -> str: """Constructs a versioned url for the given path. This method may be overridden in subclasses (but note that it is a class method rather than an instance method). Subclasses are only required to implement the signature ``make_static_url(cls, settings, path)``; other keyword arguments may be passed through `~RequestHandler.static_url` but are not standard. ``settings`` is the `Application.settings` dictionary. ``path`` is the static path being requested. The url returned should be relative to the current host. ``include_version`` determines whether the generated URL should include the query string containing the version hash of the file corresponding to the given ``path``. """ url = settings.get("static_url_prefix", "/static/") + path if not include_version: return url version_hash = cls.get_version(settings, path) if not version_hash: return url return "%s?v=%s" % (url, version_hash)
[ "def", "make_static_url", "(", "cls", ",", "settings", ":", "Dict", "[", "str", ",", "Any", "]", ",", "path", ":", "str", ",", "include_version", ":", "bool", "=", "True", ")", "->", "str", ":", "url", "=", "settings", ".", "get", "(", "\"static_url_prefix\"", ",", "\"/static/\"", ")", "+", "path", "if", "not", "include_version", ":", "return", "url", "version_hash", "=", "cls", ".", "get_version", "(", "settings", ",", "path", ")", "if", "not", "version_hash", ":", "return", "url", "return", "\"%s?v=%s\"", "%", "(", "url", ",", "version_hash", ")" ]
Constructs a versioned url for the given path. This method may be overridden in subclasses (but note that it is a class method rather than an instance method). Subclasses are only required to implement the signature ``make_static_url(cls, settings, path)``; other keyword arguments may be passed through `~RequestHandler.static_url` but are not standard. ``settings`` is the `Application.settings` dictionary. ``path`` is the static path being requested. The url returned should be relative to the current host. ``include_version`` determines whether the generated URL should include the query string containing the version hash of the file corresponding to the given ``path``.
[ "Constructs", "a", "versioned", "url", "for", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2922-L2951
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.parse_url_path
def parse_url_path(self, url_path: str) -> str: """Converts a static URL path into a filesystem path. ``url_path`` is the path component of the URL with ``static_url_prefix`` removed. The return value should be filesystem path relative to ``static_path``. This is the inverse of `make_static_url`. """ if os.path.sep != "/": url_path = url_path.replace("/", os.path.sep) return url_path
python
def parse_url_path(self, url_path: str) -> str: """Converts a static URL path into a filesystem path. ``url_path`` is the path component of the URL with ``static_url_prefix`` removed. The return value should be filesystem path relative to ``static_path``. This is the inverse of `make_static_url`. """ if os.path.sep != "/": url_path = url_path.replace("/", os.path.sep) return url_path
[ "def", "parse_url_path", "(", "self", ",", "url_path", ":", "str", ")", "->", "str", ":", "if", "os", ".", "path", ".", "sep", "!=", "\"/\"", ":", "url_path", "=", "url_path", ".", "replace", "(", "\"/\"", ",", "os", ".", "path", ".", "sep", ")", "return", "url_path" ]
Converts a static URL path into a filesystem path. ``url_path`` is the path component of the URL with ``static_url_prefix`` removed. The return value should be filesystem path relative to ``static_path``. This is the inverse of `make_static_url`.
[ "Converts", "a", "static", "URL", "path", "into", "a", "filesystem", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2953-L2964
train
tornadoweb/tornado
tornado/web.py
StaticFileHandler.get_version
def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]: """Generate the version string to be used in static URLs. ``settings`` is the `Application.settings` dictionary and ``path`` is the relative location of the requested asset on the filesystem. The returned value should be a string, or ``None`` if no version could be determined. .. versionchanged:: 3.1 This method was previously recommended for subclasses to override; `get_content_version` is now preferred as it allows the base class to handle caching of the result. """ abs_path = cls.get_absolute_path(settings["static_path"], path) return cls._get_cached_version(abs_path)
python
def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]: """Generate the version string to be used in static URLs. ``settings`` is the `Application.settings` dictionary and ``path`` is the relative location of the requested asset on the filesystem. The returned value should be a string, or ``None`` if no version could be determined. .. versionchanged:: 3.1 This method was previously recommended for subclasses to override; `get_content_version` is now preferred as it allows the base class to handle caching of the result. """ abs_path = cls.get_absolute_path(settings["static_path"], path) return cls._get_cached_version(abs_path)
[ "def", "get_version", "(", "cls", ",", "settings", ":", "Dict", "[", "str", ",", "Any", "]", ",", "path", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "abs_path", "=", "cls", ".", "get_absolute_path", "(", "settings", "[", "\"static_path\"", "]", ",", "path", ")", "return", "cls", ".", "_get_cached_version", "(", "abs_path", ")" ]
Generate the version string to be used in static URLs. ``settings`` is the `Application.settings` dictionary and ``path`` is the relative location of the requested asset on the filesystem. The returned value should be a string, or ``None`` if no version could be determined. .. versionchanged:: 3.1 This method was previously recommended for subclasses to override; `get_content_version` is now preferred as it allows the base class to handle caching of the result.
[ "Generate", "the", "version", "string", "to", "be", "used", "in", "static", "URLs", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L2967-L2981
train
tornadoweb/tornado
tornado/web.py
UIModule.render_string
def render_string(self, path: str, **kwargs: Any) -> bytes: """Renders a template and returns it as a string.""" return self.handler.render_string(path, **kwargs)
python
def render_string(self, path: str, **kwargs: Any) -> bytes: """Renders a template and returns it as a string.""" return self.handler.render_string(path, **kwargs)
[ "def", "render_string", "(", "self", ",", "path", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bytes", ":", "return", "self", ".", "handler", ".", "render_string", "(", "path", ",", "*", "*", "kwargs", ")" ]
Renders a template and returns it as a string.
[ "Renders", "a", "template", "and", "returns", "it", "as", "a", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L3241-L3243
train
tornadoweb/tornado
tornado/escape.py
xhtml_escape
def xhtml_escape(value: Union[str, bytes]) -> str: """Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``. When used in attribute values the escaped strings must be enclosed in quotes. .. versionchanged:: 3.2 Added the single quote to the list of escaped characters. """ return _XHTML_ESCAPE_RE.sub( lambda match: _XHTML_ESCAPE_DICT[match.group(0)], to_basestring(value) )
python
def xhtml_escape(value: Union[str, bytes]) -> str: """Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``. When used in attribute values the escaped strings must be enclosed in quotes. .. versionchanged:: 3.2 Added the single quote to the list of escaped characters. """ return _XHTML_ESCAPE_RE.sub( lambda match: _XHTML_ESCAPE_DICT[match.group(0)], to_basestring(value) )
[ "def", "xhtml_escape", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "str", ":", "return", "_XHTML_ESCAPE_RE", ".", "sub", "(", "lambda", "match", ":", "_XHTML_ESCAPE_DICT", "[", "match", ".", "group", "(", "0", ")", "]", ",", "to_basestring", "(", "value", ")", ")" ]
Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``. When used in attribute values the escaped strings must be enclosed in quotes. .. versionchanged:: 3.2 Added the single quote to the list of escaped characters.
[ "Escapes", "a", "string", "so", "it", "is", "valid", "within", "HTML", "or", "XML", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L43-L56
train
tornadoweb/tornado
tornado/escape.py
xhtml_unescape
def xhtml_unescape(value: Union[str, bytes]) -> str: """Un-escapes an XML-escaped string.""" return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value))
python
def xhtml_unescape(value: Union[str, bytes]) -> str: """Un-escapes an XML-escaped string.""" return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value))
[ "def", "xhtml_unescape", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "str", ":", "return", "re", ".", "sub", "(", "r\"&(#?)(\\w+?);\"", ",", "_convert_entity", ",", "_unicode", "(", "value", ")", ")" ]
Un-escapes an XML-escaped string.
[ "Un", "-", "escapes", "an", "XML", "-", "escaped", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L59-L61
train
tornadoweb/tornado
tornado/escape.py
json_decode
def json_decode(value: Union[str, bytes]) -> Any: """Returns Python objects for the given JSON string. Supports both `str` and `bytes` inputs. """ return json.loads(to_basestring(value))
python
def json_decode(value: Union[str, bytes]) -> Any: """Returns Python objects for the given JSON string. Supports both `str` and `bytes` inputs. """ return json.loads(to_basestring(value))
[ "def", "json_decode", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "Any", ":", "return", "json", ".", "loads", "(", "to_basestring", "(", "value", ")", ")" ]
Returns Python objects for the given JSON string. Supports both `str` and `bytes` inputs.
[ "Returns", "Python", "objects", "for", "the", "given", "JSON", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L78-L83
train
tornadoweb/tornado
tornado/escape.py
url_escape
def url_escape(value: Union[str, bytes], plus: bool = True) -> str: """Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument """ quote = urllib.parse.quote_plus if plus else urllib.parse.quote return quote(utf8(value))
python
def url_escape(value: Union[str, bytes], plus: bool = True) -> str: """Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument """ quote = urllib.parse.quote_plus if plus else urllib.parse.quote return quote(utf8(value))
[ "def", "url_escape", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "plus", ":", "bool", "=", "True", ")", "->", "str", ":", "quote", "=", "urllib", ".", "parse", ".", "quote_plus", "if", "plus", "else", "urllib", ".", "parse", ".", "quote", "return", "quote", "(", "utf8", "(", "value", ")", ")" ]
Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument
[ "Returns", "a", "URL", "-", "encoded", "version", "of", "the", "given", "value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L91-L103
train
tornadoweb/tornado
tornado/escape.py
url_unescape
def url_unescape( # noqa: F811 value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True ) -> Union[str, bytes]: """Decodes the given value from a URL. The argument may be either a byte or unicode string. If encoding is None, the result will be a byte string. Otherwise, the result is a unicode string in the specified encoding. If ``plus`` is true (the default), plus signs will be interpreted as spaces (literal plus signs must be represented as "%2B"). This is appropriate for query strings and form-encoded values but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument """ if encoding is None: if plus: # unquote_to_bytes doesn't have a _plus variant value = to_basestring(value).replace("+", " ") return urllib.parse.unquote_to_bytes(value) else: unquote = urllib.parse.unquote_plus if plus else urllib.parse.unquote return unquote(to_basestring(value), encoding=encoding)
python
def url_unescape( # noqa: F811 value: Union[str, bytes], encoding: Optional[str] = "utf-8", plus: bool = True ) -> Union[str, bytes]: """Decodes the given value from a URL. The argument may be either a byte or unicode string. If encoding is None, the result will be a byte string. Otherwise, the result is a unicode string in the specified encoding. If ``plus`` is true (the default), plus signs will be interpreted as spaces (literal plus signs must be represented as "%2B"). This is appropriate for query strings and form-encoded values but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument """ if encoding is None: if plus: # unquote_to_bytes doesn't have a _plus variant value = to_basestring(value).replace("+", " ") return urllib.parse.unquote_to_bytes(value) else: unquote = urllib.parse.unquote_plus if plus else urllib.parse.unquote return unquote(to_basestring(value), encoding=encoding)
[ "def", "url_unescape", "(", "# noqa: F811", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "encoding", ":", "Optional", "[", "str", "]", "=", "\"utf-8\"", ",", "plus", ":", "bool", "=", "True", ")", "->", "Union", "[", "str", ",", "bytes", "]", ":", "if", "encoding", "is", "None", ":", "if", "plus", ":", "# unquote_to_bytes doesn't have a _plus variant", "value", "=", "to_basestring", "(", "value", ")", ".", "replace", "(", "\"+\"", ",", "\" \"", ")", "return", "urllib", ".", "parse", ".", "unquote_to_bytes", "(", "value", ")", "else", ":", "unquote", "=", "urllib", ".", "parse", ".", "unquote_plus", "if", "plus", "else", "urllib", ".", "parse", ".", "unquote", "return", "unquote", "(", "to_basestring", "(", "value", ")", ",", "encoding", "=", "encoding", ")" ]
Decodes the given value from a URL. The argument may be either a byte or unicode string. If encoding is None, the result will be a byte string. Otherwise, the result is a unicode string in the specified encoding. If ``plus`` is true (the default), plus signs will be interpreted as spaces (literal plus signs must be represented as "%2B"). This is appropriate for query strings and form-encoded values but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argument
[ "Decodes", "the", "given", "value", "from", "a", "URL", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L118-L144
train
tornadoweb/tornado
tornado/escape.py
parse_qs_bytes
def parse_qs_bytes( qs: str, keep_blank_values: bool = False, strict_parsing: bool = False ) -> Dict[str, List[bytes]]: """Parses a query string like urlparse.parse_qs, but returns the values as byte strings. Keys still become type str (interpreted as latin1 in python3!) because it's too painful to keep them as byte strings in python3 and in practice they're nearly always ascii anyway. """ # This is gross, but python3 doesn't give us another way. # Latin1 is the universal donor of character encodings. result = urllib.parse.parse_qs( qs, keep_blank_values, strict_parsing, encoding="latin1", errors="strict" ) encoded = {} for k, v in result.items(): encoded[k] = [i.encode("latin1") for i in v] return encoded
python
def parse_qs_bytes( qs: str, keep_blank_values: bool = False, strict_parsing: bool = False ) -> Dict[str, List[bytes]]: """Parses a query string like urlparse.parse_qs, but returns the values as byte strings. Keys still become type str (interpreted as latin1 in python3!) because it's too painful to keep them as byte strings in python3 and in practice they're nearly always ascii anyway. """ # This is gross, but python3 doesn't give us another way. # Latin1 is the universal donor of character encodings. result = urllib.parse.parse_qs( qs, keep_blank_values, strict_parsing, encoding="latin1", errors="strict" ) encoded = {} for k, v in result.items(): encoded[k] = [i.encode("latin1") for i in v] return encoded
[ "def", "parse_qs_bytes", "(", "qs", ":", "str", ",", "keep_blank_values", ":", "bool", "=", "False", ",", "strict_parsing", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "List", "[", "bytes", "]", "]", ":", "# This is gross, but python3 doesn't give us another way.", "# Latin1 is the universal donor of character encodings.", "result", "=", "urllib", ".", "parse", ".", "parse_qs", "(", "qs", ",", "keep_blank_values", ",", "strict_parsing", ",", "encoding", "=", "\"latin1\"", ",", "errors", "=", "\"strict\"", ")", "encoded", "=", "{", "}", "for", "k", ",", "v", "in", "result", ".", "items", "(", ")", ":", "encoded", "[", "k", "]", "=", "[", "i", ".", "encode", "(", "\"latin1\"", ")", "for", "i", "in", "v", "]", "return", "encoded" ]
Parses a query string like urlparse.parse_qs, but returns the values as byte strings. Keys still become type str (interpreted as latin1 in python3!) because it's too painful to keep them as byte strings in python3 and in practice they're nearly always ascii anyway.
[ "Parses", "a", "query", "string", "like", "urlparse", ".", "parse_qs", "but", "returns", "the", "values", "as", "byte", "strings", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L147-L165
train
tornadoweb/tornado
tornado/escape.py
utf8
def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811 """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value if not isinstance(value, unicode_type): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.encode("utf-8")
python
def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811 """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value if not isinstance(value, unicode_type): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.encode("utf-8")
[ "def", "utf8", "(", "value", ":", "Union", "[", "None", ",", "str", ",", "bytes", "]", ")", "->", "Optional", "[", "bytes", "]", ":", "# noqa: F811", "if", "isinstance", "(", "value", ",", "_UTF8_TYPES", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "unicode_type", ")", ":", "raise", "TypeError", "(", "\"Expected bytes, unicode, or None; got %r\"", "%", "type", "(", "value", ")", ")", "return", "value", ".", "encode", "(", "\"utf-8\"", ")" ]
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
[ "Converts", "a", "string", "argument", "to", "a", "byte", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L186-L196
train
tornadoweb/tornado
tornado/escape.py
to_unicode
def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811 """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(value, bytes): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.decode("utf-8")
python
def to_unicode(value: Union[None, str, bytes]) -> Optional[str]: # noqa: F811 """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(value, bytes): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.decode("utf-8")
[ "def", "to_unicode", "(", "value", ":", "Union", "[", "None", ",", "str", ",", "bytes", "]", ")", "->", "Optional", "[", "str", "]", ":", "# noqa: F811", "if", "isinstance", "(", "value", ",", "_TO_UNICODE_TYPES", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"Expected bytes, unicode, or None; got %r\"", "%", "type", "(", "value", ")", ")", "return", "value", ".", "decode", "(", "\"utf-8\"", ")" ]
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
[ "Converts", "a", "string", "argument", "to", "a", "unicode", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L217-L227
train
tornadoweb/tornado
tornado/escape.py
recursive_unicode
def recursive_unicode(obj: Any) -> Any: """Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries. """ if isinstance(obj, dict): return dict( (recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items() ) elif isinstance(obj, list): return list(recursive_unicode(i) for i in obj) elif isinstance(obj, tuple): return tuple(recursive_unicode(i) for i in obj) elif isinstance(obj, bytes): return to_unicode(obj) else: return obj
python
def recursive_unicode(obj: Any) -> Any: """Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries. """ if isinstance(obj, dict): return dict( (recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items() ) elif isinstance(obj, list): return list(recursive_unicode(i) for i in obj) elif isinstance(obj, tuple): return tuple(recursive_unicode(i) for i in obj) elif isinstance(obj, bytes): return to_unicode(obj) else: return obj
[ "def", "recursive_unicode", "(", "obj", ":", "Any", ")", "->", "Any", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "dict", "(", "(", "recursive_unicode", "(", "k", ")", ",", "recursive_unicode", "(", "v", ")", ")", "for", "(", "k", ",", "v", ")", "in", "obj", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "list", "(", "recursive_unicode", "(", "i", ")", "for", "i", "in", "obj", ")", "elif", "isinstance", "(", "obj", ",", "tuple", ")", ":", "return", "tuple", "(", "recursive_unicode", "(", "i", ")", "for", "i", "in", "obj", ")", "elif", "isinstance", "(", "obj", ",", "bytes", ")", ":", "return", "to_unicode", "(", "obj", ")", "else", ":", "return", "obj" ]
Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries.
[ "Walks", "a", "simple", "data", "structure", "converting", "byte", "strings", "to", "unicode", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L240-L256
train
tornadoweb/tornado
tornado/escape.py
linkify
def linkify( text: Union[str, bytes], shorten: bool = False, extra_params: Union[str, Callable[[str], str]] = "", require_protocol: bool = False, permitted_protocols: List[str] = ["http", "https"], ) -> str: """Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra text to include in the link tag, or a callable taking the link as an argument and returning the extra text e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``, or:: def extra_params_cb(url): if url.startswith("http://example.com"): return 'class="internal"' else: return 'class="external" rel="nofollow"' linkify(text, extra_params=extra_params_cb) * ``require_protocol``: Only linkify urls which include a protocol. If this is False, urls such as www.facebook.com will also be linkified. * ``permitted_protocols``: List (or set) of protocols which should be linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp", "mailto"])``. It is very unsafe to include protocols such as ``javascript``. """ if extra_params and not callable(extra_params): extra_params = " " + extra_params.strip() def make_link(m: typing.Match) -> str: url = m.group(1) proto = m.group(2) if require_protocol and not proto: return url # not protocol, no linkify if proto and proto not in permitted_protocols: return url # bad protocol, no linkify href = m.group(1) if not proto: href = "http://" + href # no proto specified, use http if callable(extra_params): params = " " + extra_params(href).strip() else: params = extra_params # clip long urls. max_len is just an approximation max_len = 30 if shorten and len(url) > max_len: before_clip = url if proto: proto_len = len(proto) + 1 + len(m.group(3) or "") # +1 for : else: proto_len = 0 parts = url[proto_len:].split("/") if len(parts) > 1: # Grab the whole host part plus the first bit of the path # The path is usually not that interesting once shortened # (no more slug, etc), so it really just provides a little # extra indication of shortening. url = ( url[:proto_len] + parts[0] + "/" + parts[1][:8].split("?")[0].split(".")[0] ) if len(url) > max_len * 1.5: # still too long url = url[:max_len] if url != before_clip: amp = url.rfind("&") # avoid splitting html char entities if amp > max_len - 5: url = url[:amp] url += "..." if len(url) >= len(before_clip): url = before_clip else: # full url is visible on mouse-over (for those who don't # have a status bar, such as Safari by default) params += ' title="%s"' % href return u'<a href="%s"%s>%s</a>' % (href, params, url) # First HTML-escape so that our strings are all safe. # The regex is modified to avoid character entites other than &amp; so # that we won't pick up &quot;, etc. text = _unicode(xhtml_escape(text)) return _URL_RE.sub(make_link, text)
python
def linkify( text: Union[str, bytes], shorten: bool = False, extra_params: Union[str, Callable[[str], str]] = "", require_protocol: bool = False, permitted_protocols: List[str] = ["http", "https"], ) -> str: """Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra text to include in the link tag, or a callable taking the link as an argument and returning the extra text e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``, or:: def extra_params_cb(url): if url.startswith("http://example.com"): return 'class="internal"' else: return 'class="external" rel="nofollow"' linkify(text, extra_params=extra_params_cb) * ``require_protocol``: Only linkify urls which include a protocol. If this is False, urls such as www.facebook.com will also be linkified. * ``permitted_protocols``: List (or set) of protocols which should be linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp", "mailto"])``. It is very unsafe to include protocols such as ``javascript``. """ if extra_params and not callable(extra_params): extra_params = " " + extra_params.strip() def make_link(m: typing.Match) -> str: url = m.group(1) proto = m.group(2) if require_protocol and not proto: return url # not protocol, no linkify if proto and proto not in permitted_protocols: return url # bad protocol, no linkify href = m.group(1) if not proto: href = "http://" + href # no proto specified, use http if callable(extra_params): params = " " + extra_params(href).strip() else: params = extra_params # clip long urls. max_len is just an approximation max_len = 30 if shorten and len(url) > max_len: before_clip = url if proto: proto_len = len(proto) + 1 + len(m.group(3) or "") # +1 for : else: proto_len = 0 parts = url[proto_len:].split("/") if len(parts) > 1: # Grab the whole host part plus the first bit of the path # The path is usually not that interesting once shortened # (no more slug, etc), so it really just provides a little # extra indication of shortening. url = ( url[:proto_len] + parts[0] + "/" + parts[1][:8].split("?")[0].split(".")[0] ) if len(url) > max_len * 1.5: # still too long url = url[:max_len] if url != before_clip: amp = url.rfind("&") # avoid splitting html char entities if amp > max_len - 5: url = url[:amp] url += "..." if len(url) >= len(before_clip): url = before_clip else: # full url is visible on mouse-over (for those who don't # have a status bar, such as Safari by default) params += ' title="%s"' % href return u'<a href="%s"%s>%s</a>' % (href, params, url) # First HTML-escape so that our strings are all safe. # The regex is modified to avoid character entites other than &amp; so # that we won't pick up &quot;, etc. text = _unicode(xhtml_escape(text)) return _URL_RE.sub(make_link, text)
[ "def", "linkify", "(", "text", ":", "Union", "[", "str", ",", "bytes", "]", ",", "shorten", ":", "bool", "=", "False", ",", "extra_params", ":", "Union", "[", "str", ",", "Callable", "[", "[", "str", "]", ",", "str", "]", "]", "=", "\"\"", ",", "require_protocol", ":", "bool", "=", "False", ",", "permitted_protocols", ":", "List", "[", "str", "]", "=", "[", "\"http\"", ",", "\"https\"", "]", ",", ")", "->", "str", ":", "if", "extra_params", "and", "not", "callable", "(", "extra_params", ")", ":", "extra_params", "=", "\" \"", "+", "extra_params", ".", "strip", "(", ")", "def", "make_link", "(", "m", ":", "typing", ".", "Match", ")", "->", "str", ":", "url", "=", "m", ".", "group", "(", "1", ")", "proto", "=", "m", ".", "group", "(", "2", ")", "if", "require_protocol", "and", "not", "proto", ":", "return", "url", "# not protocol, no linkify", "if", "proto", "and", "proto", "not", "in", "permitted_protocols", ":", "return", "url", "# bad protocol, no linkify", "href", "=", "m", ".", "group", "(", "1", ")", "if", "not", "proto", ":", "href", "=", "\"http://\"", "+", "href", "# no proto specified, use http", "if", "callable", "(", "extra_params", ")", ":", "params", "=", "\" \"", "+", "extra_params", "(", "href", ")", ".", "strip", "(", ")", "else", ":", "params", "=", "extra_params", "# clip long urls. max_len is just an approximation", "max_len", "=", "30", "if", "shorten", "and", "len", "(", "url", ")", ">", "max_len", ":", "before_clip", "=", "url", "if", "proto", ":", "proto_len", "=", "len", "(", "proto", ")", "+", "1", "+", "len", "(", "m", ".", "group", "(", "3", ")", "or", "\"\"", ")", "# +1 for :", "else", ":", "proto_len", "=", "0", "parts", "=", "url", "[", "proto_len", ":", "]", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "# Grab the whole host part plus the first bit of the path", "# The path is usually not that interesting once shortened", "# (no more slug, etc), so it really just provides a little", "# extra indication of shortening.", "url", "=", "(", "url", "[", ":", "proto_len", "]", "+", "parts", "[", "0", "]", "+", "\"/\"", "+", "parts", "[", "1", "]", "[", ":", "8", "]", ".", "split", "(", "\"?\"", ")", "[", "0", "]", ".", "split", "(", "\".\"", ")", "[", "0", "]", ")", "if", "len", "(", "url", ")", ">", "max_len", "*", "1.5", ":", "# still too long", "url", "=", "url", "[", ":", "max_len", "]", "if", "url", "!=", "before_clip", ":", "amp", "=", "url", ".", "rfind", "(", "\"&\"", ")", "# avoid splitting html char entities", "if", "amp", ">", "max_len", "-", "5", ":", "url", "=", "url", "[", ":", "amp", "]", "url", "+=", "\"...\"", "if", "len", "(", "url", ")", ">=", "len", "(", "before_clip", ")", ":", "url", "=", "before_clip", "else", ":", "# full url is visible on mouse-over (for those who don't", "# have a status bar, such as Safari by default)", "params", "+=", "' title=\"%s\"'", "%", "href", "return", "u'<a href=\"%s\"%s>%s</a>'", "%", "(", "href", ",", "params", ",", "url", ")", "# First HTML-escape so that our strings are all safe.", "# The regex is modified to avoid character entites other than &amp; so", "# that we won't pick up &quot;, etc.", "text", "=", "_unicode", "(", "xhtml_escape", "(", "text", ")", ")", "return", "_URL_RE", ".", "sub", "(", "make_link", ",", "text", ")" ]
Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra text to include in the link tag, or a callable taking the link as an argument and returning the extra text e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``, or:: def extra_params_cb(url): if url.startswith("http://example.com"): return 'class="internal"' else: return 'class="external" rel="nofollow"' linkify(text, extra_params=extra_params_cb) * ``require_protocol``: Only linkify urls which include a protocol. If this is False, urls such as www.facebook.com will also be linkified. * ``permitted_protocols``: List (or set) of protocols which should be linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp", "mailto"])``. It is very unsafe to include protocols such as ``javascript``.
[ "Converts", "plain", "text", "into", "HTML", "with", "links", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L273-L375
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.current
def current(instance: bool = True) -> Optional["IOLoop"]: """Returns the current thread's `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop` and ``instance`` is true, creates one. .. versionchanged:: 4.1 Added ``instance`` argument to control the fallback to `IOLoop.instance()`. .. versionchanged:: 5.0 On Python 3, control of the current `IOLoop` is delegated to `asyncio`, with this and other methods as pass-through accessors. The ``instance`` argument now controls whether an `IOLoop` is created automatically when there is none, instead of whether we fall back to `IOLoop.instance()` (which is now an alias for this method). ``instance=False`` is deprecated, since even if we do not create an `IOLoop`, this method may initialize the asyncio loop. """ try: loop = asyncio.get_event_loop() except (RuntimeError, AssertionError): if not instance: return None raise try: return IOLoop._ioloop_for_asyncio[loop] except KeyError: if instance: from tornado.platform.asyncio import AsyncIOMainLoop current = AsyncIOMainLoop(make_current=True) # type: Optional[IOLoop] else: current = None return current
python
def current(instance: bool = True) -> Optional["IOLoop"]: """Returns the current thread's `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop` and ``instance`` is true, creates one. .. versionchanged:: 4.1 Added ``instance`` argument to control the fallback to `IOLoop.instance()`. .. versionchanged:: 5.0 On Python 3, control of the current `IOLoop` is delegated to `asyncio`, with this and other methods as pass-through accessors. The ``instance`` argument now controls whether an `IOLoop` is created automatically when there is none, instead of whether we fall back to `IOLoop.instance()` (which is now an alias for this method). ``instance=False`` is deprecated, since even if we do not create an `IOLoop`, this method may initialize the asyncio loop. """ try: loop = asyncio.get_event_loop() except (RuntimeError, AssertionError): if not instance: return None raise try: return IOLoop._ioloop_for_asyncio[loop] except KeyError: if instance: from tornado.platform.asyncio import AsyncIOMainLoop current = AsyncIOMainLoop(make_current=True) # type: Optional[IOLoop] else: current = None return current
[ "def", "current", "(", "instance", ":", "bool", "=", "True", ")", "->", "Optional", "[", "\"IOLoop\"", "]", ":", "try", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "except", "(", "RuntimeError", ",", "AssertionError", ")", ":", "if", "not", "instance", ":", "return", "None", "raise", "try", ":", "return", "IOLoop", ".", "_ioloop_for_asyncio", "[", "loop", "]", "except", "KeyError", ":", "if", "instance", ":", "from", "tornado", ".", "platform", ".", "asyncio", "import", "AsyncIOMainLoop", "current", "=", "AsyncIOMainLoop", "(", "make_current", "=", "True", ")", "# type: Optional[IOLoop]", "else", ":", "current", "=", "None", "return", "current" ]
Returns the current thread's `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop` and ``instance`` is true, creates one. .. versionchanged:: 4.1 Added ``instance`` argument to control the fallback to `IOLoop.instance()`. .. versionchanged:: 5.0 On Python 3, control of the current `IOLoop` is delegated to `asyncio`, with this and other methods as pass-through accessors. The ``instance`` argument now controls whether an `IOLoop` is created automatically when there is none, instead of whether we fall back to `IOLoop.instance()` (which is now an alias for this method). ``instance=False`` is deprecated, since even if we do not create an `IOLoop`, this method may initialize the asyncio loop.
[ "Returns", "the", "current", "thread", "s", "IOLoop", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L244-L279
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.clear_current
def clear_current() -> None: """Clears the `IOLoop` for the current thread. Intended primarily for use by test frameworks in between tests. .. versionchanged:: 5.0 This method also clears the current `asyncio` event loop. """ old = IOLoop.current(instance=False) if old is not None: old._clear_current_hook() if asyncio is None: IOLoop._current.instance = None
python
def clear_current() -> None: """Clears the `IOLoop` for the current thread. Intended primarily for use by test frameworks in between tests. .. versionchanged:: 5.0 This method also clears the current `asyncio` event loop. """ old = IOLoop.current(instance=False) if old is not None: old._clear_current_hook() if asyncio is None: IOLoop._current.instance = None
[ "def", "clear_current", "(", ")", "->", "None", ":", "old", "=", "IOLoop", ".", "current", "(", "instance", "=", "False", ")", "if", "old", "is", "not", "None", ":", "old", ".", "_clear_current_hook", "(", ")", "if", "asyncio", "is", "None", ":", "IOLoop", ".", "_current", ".", "instance", "=", "None" ]
Clears the `IOLoop` for the current thread. Intended primarily for use by test frameworks in between tests. .. versionchanged:: 5.0 This method also clears the current `asyncio` event loop.
[ "Clears", "the", "IOLoop", "for", "the", "current", "thread", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L301-L313
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.add_handler
def add_handler( # noqa: F811 self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int ) -> None: """Registers the given handler to receive the given events for ``fd``. The ``fd`` argument may either be an integer file descriptor or a file-like object with a ``fileno()`` and ``close()`` method. The ``events`` argument is a bitwise or of the constants ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``. When an event occurs, ``handler(fd, events)`` will be run. .. versionchanged:: 4.0 Added the ability to pass file-like objects in addition to raw file descriptors. """ raise NotImplementedError()
python
def add_handler( # noqa: F811 self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int ) -> None: """Registers the given handler to receive the given events for ``fd``. The ``fd`` argument may either be an integer file descriptor or a file-like object with a ``fileno()`` and ``close()`` method. The ``events`` argument is a bitwise or of the constants ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``. When an event occurs, ``handler(fd, events)`` will be run. .. versionchanged:: 4.0 Added the ability to pass file-like objects in addition to raw file descriptors. """ raise NotImplementedError()
[ "def", "add_handler", "(", "# noqa: F811", "self", ",", "fd", ":", "Union", "[", "int", ",", "_Selectable", "]", ",", "handler", ":", "Callable", "[", "...", ",", "None", "]", ",", "events", ":", "int", ")", "->", "None", ":", "raise", "NotImplementedError", "(", ")" ]
Registers the given handler to receive the given events for ``fd``. The ``fd`` argument may either be an integer file descriptor or a file-like object with a ``fileno()`` and ``close()`` method. The ``events`` argument is a bitwise or of the constants ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``. When an event occurs, ``handler(fd, events)`` will be run. .. versionchanged:: 4.0 Added the ability to pass file-like objects in addition to raw file descriptors.
[ "Registers", "the", "given", "handler", "to", "receive", "the", "given", "events", "for", "fd", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L382-L399
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop._setup_logging
def _setup_logging(self) -> None: """The IOLoop catches and logs exceptions, so it's important that log output be visible. However, python's default behavior for non-root loggers (prior to python 3.2) is to print an unhelpful "no handlers could be found" message rather than the actual log entry, so we must explicitly configure logging if we've made it this far without anything. This method should be called from start() in subclasses. """ if not any( [ logging.getLogger().handlers, logging.getLogger("tornado").handlers, logging.getLogger("tornado.application").handlers, ] ): logging.basicConfig()
python
def _setup_logging(self) -> None: """The IOLoop catches and logs exceptions, so it's important that log output be visible. However, python's default behavior for non-root loggers (prior to python 3.2) is to print an unhelpful "no handlers could be found" message rather than the actual log entry, so we must explicitly configure logging if we've made it this far without anything. This method should be called from start() in subclasses. """ if not any( [ logging.getLogger().handlers, logging.getLogger("tornado").handlers, logging.getLogger("tornado.application").handlers, ] ): logging.basicConfig()
[ "def", "_setup_logging", "(", "self", ")", "->", "None", ":", "if", "not", "any", "(", "[", "logging", ".", "getLogger", "(", ")", ".", "handlers", ",", "logging", ".", "getLogger", "(", "\"tornado\"", ")", ".", "handlers", ",", "logging", ".", "getLogger", "(", "\"tornado.application\"", ")", ".", "handlers", ",", "]", ")", ":", "logging", ".", "basicConfig", "(", ")" ]
The IOLoop catches and logs exceptions, so it's important that log output be visible. However, python's default behavior for non-root loggers (prior to python 3.2) is to print an unhelpful "no handlers could be found" message rather than the actual log entry, so we must explicitly configure logging if we've made it this far without anything. This method should be called from start() in subclasses.
[ "The", "IOLoop", "catches", "and", "logs", "exceptions", "so", "it", "s", "important", "that", "log", "output", "be", "visible", ".", "However", "python", "s", "default", "behavior", "for", "non", "-", "root", "loggers", "(", "prior", "to", "python", "3", ".", "2", ")", "is", "to", "print", "an", "unhelpful", "no", "handlers", "could", "be", "found", "message", "rather", "than", "the", "actual", "log", "entry", "so", "we", "must", "explicitly", "configure", "logging", "if", "we", "ve", "made", "it", "this", "far", "without", "anything", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L427-L445
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.run_sync
def run_sync(self, func: Callable, timeout: float = None) -> Any: """Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable is resolved (and `run_sync()` will return the awaitable's result). If it raises an exception, the `IOLoop` will stop and the exception will be re-raised to the caller. The keyword-only argument ``timeout`` may be used to set a maximum duration for the function. If the timeout expires, a `tornado.util.TimeoutError` is raised. This method is useful to allow asynchronous calls in a ``main()`` function:: async def main(): # do stuff... if __name__ == '__main__': IOLoop.current().run_sync(main) .. versionchanged:: 4.3 Returning a non-``None``, non-awaitable value is now an error. .. versionchanged:: 5.0 If a timeout occurs, the ``func`` coroutine will be cancelled. """ future_cell = [None] # type: List[Optional[Future]] def run() -> None: try: result = func() if result is not None: from tornado.gen import convert_yielded result = convert_yielded(result) except Exception: fut = Future() # type: Future[Any] future_cell[0] = fut future_set_exc_info(fut, sys.exc_info()) else: if is_future(result): future_cell[0] = result else: fut = Future() future_cell[0] = fut fut.set_result(result) assert future_cell[0] is not None self.add_future(future_cell[0], lambda future: self.stop()) self.add_callback(run) if timeout is not None: def timeout_callback() -> None: # If we can cancel the future, do so and wait on it. If not, # Just stop the loop and return with the task still pending. # (If we neither cancel nor wait for the task, a warning # will be logged). assert future_cell[0] is not None if not future_cell[0].cancel(): self.stop() timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback) self.start() if timeout is not None: self.remove_timeout(timeout_handle) assert future_cell[0] is not None if future_cell[0].cancelled() or not future_cell[0].done(): raise TimeoutError("Operation timed out after %s seconds" % timeout) return future_cell[0].result()
python
def run_sync(self, func: Callable, timeout: float = None) -> Any: """Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable is resolved (and `run_sync()` will return the awaitable's result). If it raises an exception, the `IOLoop` will stop and the exception will be re-raised to the caller. The keyword-only argument ``timeout`` may be used to set a maximum duration for the function. If the timeout expires, a `tornado.util.TimeoutError` is raised. This method is useful to allow asynchronous calls in a ``main()`` function:: async def main(): # do stuff... if __name__ == '__main__': IOLoop.current().run_sync(main) .. versionchanged:: 4.3 Returning a non-``None``, non-awaitable value is now an error. .. versionchanged:: 5.0 If a timeout occurs, the ``func`` coroutine will be cancelled. """ future_cell = [None] # type: List[Optional[Future]] def run() -> None: try: result = func() if result is not None: from tornado.gen import convert_yielded result = convert_yielded(result) except Exception: fut = Future() # type: Future[Any] future_cell[0] = fut future_set_exc_info(fut, sys.exc_info()) else: if is_future(result): future_cell[0] = result else: fut = Future() future_cell[0] = fut fut.set_result(result) assert future_cell[0] is not None self.add_future(future_cell[0], lambda future: self.stop()) self.add_callback(run) if timeout is not None: def timeout_callback() -> None: # If we can cancel the future, do so and wait on it. If not, # Just stop the loop and return with the task still pending. # (If we neither cancel nor wait for the task, a warning # will be logged). assert future_cell[0] is not None if not future_cell[0].cancel(): self.stop() timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback) self.start() if timeout is not None: self.remove_timeout(timeout_handle) assert future_cell[0] is not None if future_cell[0].cancelled() or not future_cell[0].done(): raise TimeoutError("Operation timed out after %s seconds" % timeout) return future_cell[0].result()
[ "def", "run_sync", "(", "self", ",", "func", ":", "Callable", ",", "timeout", ":", "float", "=", "None", ")", "->", "Any", ":", "future_cell", "=", "[", "None", "]", "# type: List[Optional[Future]]", "def", "run", "(", ")", "->", "None", ":", "try", ":", "result", "=", "func", "(", ")", "if", "result", "is", "not", "None", ":", "from", "tornado", ".", "gen", "import", "convert_yielded", "result", "=", "convert_yielded", "(", "result", ")", "except", "Exception", ":", "fut", "=", "Future", "(", ")", "# type: Future[Any]", "future_cell", "[", "0", "]", "=", "fut", "future_set_exc_info", "(", "fut", ",", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "if", "is_future", "(", "result", ")", ":", "future_cell", "[", "0", "]", "=", "result", "else", ":", "fut", "=", "Future", "(", ")", "future_cell", "[", "0", "]", "=", "fut", "fut", ".", "set_result", "(", "result", ")", "assert", "future_cell", "[", "0", "]", "is", "not", "None", "self", ".", "add_future", "(", "future_cell", "[", "0", "]", ",", "lambda", "future", ":", "self", ".", "stop", "(", ")", ")", "self", ".", "add_callback", "(", "run", ")", "if", "timeout", "is", "not", "None", ":", "def", "timeout_callback", "(", ")", "->", "None", ":", "# If we can cancel the future, do so and wait on it. If not,", "# Just stop the loop and return with the task still pending.", "# (If we neither cancel nor wait for the task, a warning", "# will be logged).", "assert", "future_cell", "[", "0", "]", "is", "not", "None", "if", "not", "future_cell", "[", "0", "]", ".", "cancel", "(", ")", ":", "self", ".", "stop", "(", ")", "timeout_handle", "=", "self", ".", "add_timeout", "(", "self", ".", "time", "(", ")", "+", "timeout", ",", "timeout_callback", ")", "self", ".", "start", "(", ")", "if", "timeout", "is", "not", "None", ":", "self", ".", "remove_timeout", "(", "timeout_handle", ")", "assert", "future_cell", "[", "0", "]", "is", "not", "None", "if", "future_cell", "[", "0", "]", ".", "cancelled", "(", ")", "or", "not", "future_cell", "[", "0", "]", ".", "done", "(", ")", ":", "raise", "TimeoutError", "(", "\"Operation timed out after %s seconds\"", "%", "timeout", ")", "return", "future_cell", "[", "0", "]", ".", "result", "(", ")" ]
Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable is resolved (and `run_sync()` will return the awaitable's result). If it raises an exception, the `IOLoop` will stop and the exception will be re-raised to the caller. The keyword-only argument ``timeout`` may be used to set a maximum duration for the function. If the timeout expires, a `tornado.util.TimeoutError` is raised. This method is useful to allow asynchronous calls in a ``main()`` function:: async def main(): # do stuff... if __name__ == '__main__': IOLoop.current().run_sync(main) .. versionchanged:: 4.3 Returning a non-``None``, non-awaitable value is now an error. .. versionchanged:: 5.0 If a timeout occurs, the ``func`` coroutine will be cancelled.
[ "Starts", "the", "IOLoop", "runs", "the", "given", "function", "and", "stops", "the", "loop", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L460-L532
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.add_timeout
def add_timeout( self, deadline: Union[float, datetime.timedelta], callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` at the time ``deadline`` from the I/O loop. Returns an opaque handle that may be passed to `remove_timeout` to cancel. ``deadline`` may be a number denoting a time (on the same scale as `IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. Since Tornado 4.0, `call_later` is a more convenient alternative for the relative case since it does not require a timedelta object. Note that it is not safe to call `add_timeout` from other threads. Instead, you must use `add_callback` to transfer control to the `IOLoop`'s thread, and then call `add_timeout` from there. Subclasses of IOLoop must implement either `add_timeout` or `call_at`; the default implementations of each will call the other. `call_at` is usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must use `add_timeout` instead. .. versionchanged:: 4.0 Now passes through ``*args`` and ``**kwargs`` to the callback. """ if isinstance(deadline, numbers.Real): return self.call_at(deadline, callback, *args, **kwargs) elif isinstance(deadline, datetime.timedelta): return self.call_at( self.time() + deadline.total_seconds(), callback, *args, **kwargs ) else: raise TypeError("Unsupported deadline %r" % deadline)
python
def add_timeout( self, deadline: Union[float, datetime.timedelta], callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` at the time ``deadline`` from the I/O loop. Returns an opaque handle that may be passed to `remove_timeout` to cancel. ``deadline`` may be a number denoting a time (on the same scale as `IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. Since Tornado 4.0, `call_later` is a more convenient alternative for the relative case since it does not require a timedelta object. Note that it is not safe to call `add_timeout` from other threads. Instead, you must use `add_callback` to transfer control to the `IOLoop`'s thread, and then call `add_timeout` from there. Subclasses of IOLoop must implement either `add_timeout` or `call_at`; the default implementations of each will call the other. `call_at` is usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must use `add_timeout` instead. .. versionchanged:: 4.0 Now passes through ``*args`` and ``**kwargs`` to the callback. """ if isinstance(deadline, numbers.Real): return self.call_at(deadline, callback, *args, **kwargs) elif isinstance(deadline, datetime.timedelta): return self.call_at( self.time() + deadline.total_seconds(), callback, *args, **kwargs ) else: raise TypeError("Unsupported deadline %r" % deadline)
[ "def", "add_timeout", "(", "self", ",", "deadline", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", ",", "callback", ":", "Callable", "[", "...", ",", "None", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "object", ":", "if", "isinstance", "(", "deadline", ",", "numbers", ".", "Real", ")", ":", "return", "self", ".", "call_at", "(", "deadline", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "deadline", ",", "datetime", ".", "timedelta", ")", ":", "return", "self", ".", "call_at", "(", "self", ".", "time", "(", ")", "+", "deadline", ".", "total_seconds", "(", ")", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "TypeError", "(", "\"Unsupported deadline %r\"", "%", "deadline", ")" ]
Runs the ``callback`` at the time ``deadline`` from the I/O loop. Returns an opaque handle that may be passed to `remove_timeout` to cancel. ``deadline`` may be a number denoting a time (on the same scale as `IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. Since Tornado 4.0, `call_later` is a more convenient alternative for the relative case since it does not require a timedelta object. Note that it is not safe to call `add_timeout` from other threads. Instead, you must use `add_callback` to transfer control to the `IOLoop`'s thread, and then call `add_timeout` from there. Subclasses of IOLoop must implement either `add_timeout` or `call_at`; the default implementations of each will call the other. `call_at` is usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must use `add_timeout` instead. .. versionchanged:: 4.0 Now passes through ``*args`` and ``**kwargs`` to the callback.
[ "Runs", "the", "callback", "at", "the", "time", "deadline", "from", "the", "I", "/", "O", "loop", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L548-L587
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.call_later
def call_later( self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` after ``delay`` seconds have passed. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0 """ return self.call_at(self.time() + delay, callback, *args, **kwargs)
python
def call_later( self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` after ``delay`` seconds have passed. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0 """ return self.call_at(self.time() + delay, callback, *args, **kwargs)
[ "def", "call_later", "(", "self", ",", "delay", ":", "float", ",", "callback", ":", "Callable", "[", "...", ",", "None", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "object", ":", "return", "self", ".", "call_at", "(", "self", ".", "time", "(", ")", "+", "delay", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Runs the ``callback`` after ``delay`` seconds have passed. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0
[ "Runs", "the", "callback", "after", "delay", "seconds", "have", "passed", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L589-L602
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.call_at
def call_at( self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0 """ return self.add_timeout(when, callback, *args, **kwargs)
python
def call_at( self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> object: """Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0 """ return self.add_timeout(when, callback, *args, **kwargs)
[ "def", "call_at", "(", "self", ",", "when", ":", "float", ",", "callback", ":", "Callable", "[", "...", ",", "None", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "object", ":", "return", "self", ".", "add_timeout", "(", "when", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Runs the ``callback`` at the absolute time designated by ``when``. ``when`` must be a number using the same reference point as `IOLoop.time`. Returns an opaque handle that may be passed to `remove_timeout` to cancel. Note that unlike the `asyncio` method of the same name, the returned object does not have a ``cancel()`` method. See `add_timeout` for comments on thread-safety and subclassing. .. versionadded:: 4.0
[ "Runs", "the", "callback", "at", "the", "absolute", "time", "designated", "by", "when", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L604-L620
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.spawn_callback
def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None: """Calls the given callback on the next IOLoop iteration. As of Tornado 6.0, this method is equivalent to `add_callback`. .. versionadded:: 4.0 """ self.add_callback(callback, *args, **kwargs)
python
def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None: """Calls the given callback on the next IOLoop iteration. As of Tornado 6.0, this method is equivalent to `add_callback`. .. versionadded:: 4.0 """ self.add_callback(callback, *args, **kwargs)
[ "def", "spawn_callback", "(", "self", ",", "callback", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "add_callback", "(", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Calls the given callback on the next IOLoop iteration. As of Tornado 6.0, this method is equivalent to `add_callback`. .. versionadded:: 4.0
[ "Calls", "the", "given", "callback", "on", "the", "next", "IOLoop", "iteration", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L656-L663
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.add_future
def add_future( self, future: "Union[Future[_T], concurrent.futures.Future[_T]]", callback: Callable[["Future[_T]"], None], ) -> None: """Schedules a callback on the ``IOLoop`` when the given `.Future` is finished. The callback is invoked with one argument, the `.Future`. This method only accepts `.Future` objects and not other awaitables (unlike most of Tornado where the two are interchangeable). """ if isinstance(future, Future): # Note that we specifically do not want the inline behavior of # tornado.concurrent.future_add_done_callback. We always want # this callback scheduled on the next IOLoop iteration (which # asyncio.Future always does). # # Wrap the callback in self._run_callback so we control # the error logging (i.e. it goes to tornado.log.app_log # instead of asyncio's log). future.add_done_callback( lambda f: self._run_callback(functools.partial(callback, future)) ) else: assert is_future(future) # For concurrent futures, we use self.add_callback, so # it's fine if future_add_done_callback inlines that call. future_add_done_callback( future, lambda f: self.add_callback(callback, future) )
python
def add_future( self, future: "Union[Future[_T], concurrent.futures.Future[_T]]", callback: Callable[["Future[_T]"], None], ) -> None: """Schedules a callback on the ``IOLoop`` when the given `.Future` is finished. The callback is invoked with one argument, the `.Future`. This method only accepts `.Future` objects and not other awaitables (unlike most of Tornado where the two are interchangeable). """ if isinstance(future, Future): # Note that we specifically do not want the inline behavior of # tornado.concurrent.future_add_done_callback. We always want # this callback scheduled on the next IOLoop iteration (which # asyncio.Future always does). # # Wrap the callback in self._run_callback so we control # the error logging (i.e. it goes to tornado.log.app_log # instead of asyncio's log). future.add_done_callback( lambda f: self._run_callback(functools.partial(callback, future)) ) else: assert is_future(future) # For concurrent futures, we use self.add_callback, so # it's fine if future_add_done_callback inlines that call. future_add_done_callback( future, lambda f: self.add_callback(callback, future) )
[ "def", "add_future", "(", "self", ",", "future", ":", "\"Union[Future[_T], concurrent.futures.Future[_T]]\"", ",", "callback", ":", "Callable", "[", "[", "\"Future[_T]\"", "]", ",", "None", "]", ",", ")", "->", "None", ":", "if", "isinstance", "(", "future", ",", "Future", ")", ":", "# Note that we specifically do not want the inline behavior of", "# tornado.concurrent.future_add_done_callback. We always want", "# this callback scheduled on the next IOLoop iteration (which", "# asyncio.Future always does).", "#", "# Wrap the callback in self._run_callback so we control", "# the error logging (i.e. it goes to tornado.log.app_log", "# instead of asyncio's log).", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "self", ".", "_run_callback", "(", "functools", ".", "partial", "(", "callback", ",", "future", ")", ")", ")", "else", ":", "assert", "is_future", "(", "future", ")", "# For concurrent futures, we use self.add_callback, so", "# it's fine if future_add_done_callback inlines that call.", "future_add_done_callback", "(", "future", ",", "lambda", "f", ":", "self", ".", "add_callback", "(", "callback", ",", "future", ")", ")" ]
Schedules a callback on the ``IOLoop`` when the given `.Future` is finished. The callback is invoked with one argument, the `.Future`. This method only accepts `.Future` objects and not other awaitables (unlike most of Tornado where the two are interchangeable).
[ "Schedules", "a", "callback", "on", "the", "IOLoop", "when", "the", "given", ".", "Future", "is", "finished", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L665-L698
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop.run_in_executor
def run_in_executor( self, executor: Optional[concurrent.futures.Executor], func: Callable[..., _T], *args: Any ) -> Awaitable[_T]: """Runs a function in a ``concurrent.futures.Executor``. If ``executor`` is ``None``, the IO loop's default executor will be used. Use `functools.partial` to pass keyword arguments to ``func``. .. versionadded:: 5.0 """ if executor is None: if not hasattr(self, "_executor"): from tornado.process import cpu_count self._executor = concurrent.futures.ThreadPoolExecutor( max_workers=(cpu_count() * 5) ) # type: concurrent.futures.Executor executor = self._executor c_future = executor.submit(func, *args) # Concurrent Futures are not usable with await. Wrap this in a # Tornado Future instead, using self.add_future for thread-safety. t_future = Future() # type: Future[_T] self.add_future(c_future, lambda f: chain_future(f, t_future)) return t_future
python
def run_in_executor( self, executor: Optional[concurrent.futures.Executor], func: Callable[..., _T], *args: Any ) -> Awaitable[_T]: """Runs a function in a ``concurrent.futures.Executor``. If ``executor`` is ``None``, the IO loop's default executor will be used. Use `functools.partial` to pass keyword arguments to ``func``. .. versionadded:: 5.0 """ if executor is None: if not hasattr(self, "_executor"): from tornado.process import cpu_count self._executor = concurrent.futures.ThreadPoolExecutor( max_workers=(cpu_count() * 5) ) # type: concurrent.futures.Executor executor = self._executor c_future = executor.submit(func, *args) # Concurrent Futures are not usable with await. Wrap this in a # Tornado Future instead, using self.add_future for thread-safety. t_future = Future() # type: Future[_T] self.add_future(c_future, lambda f: chain_future(f, t_future)) return t_future
[ "def", "run_in_executor", "(", "self", ",", "executor", ":", "Optional", "[", "concurrent", ".", "futures", ".", "Executor", "]", ",", "func", ":", "Callable", "[", "...", ",", "_T", "]", ",", "*", "args", ":", "Any", ")", "->", "Awaitable", "[", "_T", "]", ":", "if", "executor", "is", "None", ":", "if", "not", "hasattr", "(", "self", ",", "\"_executor\"", ")", ":", "from", "tornado", ".", "process", "import", "cpu_count", "self", ".", "_executor", "=", "concurrent", ".", "futures", ".", "ThreadPoolExecutor", "(", "max_workers", "=", "(", "cpu_count", "(", ")", "*", "5", ")", ")", "# type: concurrent.futures.Executor", "executor", "=", "self", ".", "_executor", "c_future", "=", "executor", ".", "submit", "(", "func", ",", "*", "args", ")", "# Concurrent Futures are not usable with await. Wrap this in a", "# Tornado Future instead, using self.add_future for thread-safety.", "t_future", "=", "Future", "(", ")", "# type: Future[_T]", "self", ".", "add_future", "(", "c_future", ",", "lambda", "f", ":", "chain_future", "(", "f", ",", "t_future", ")", ")", "return", "t_future" ]
Runs a function in a ``concurrent.futures.Executor``. If ``executor`` is ``None``, the IO loop's default executor will be used. Use `functools.partial` to pass keyword arguments to ``func``. .. versionadded:: 5.0
[ "Runs", "a", "function", "in", "a", "concurrent", ".", "futures", ".", "Executor", ".", "If", "executor", "is", "None", "the", "IO", "loop", "s", "default", "executor", "will", "be", "used", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L700-L726
train
tornadoweb/tornado
tornado/ioloop.py
IOLoop._run_callback
def _run_callback(self, callback: Callable[[], Any]) -> None: """Runs a callback with error handling. .. versionchanged:: 6.0 CancelledErrors are no longer logged. """ try: ret = callback() if ret is not None: from tornado import gen # Functions that return Futures typically swallow all # exceptions and store them in the Future. If a Future # makes it out to the IOLoop, ensure its exception (if any) # gets logged too. try: ret = gen.convert_yielded(ret) except gen.BadYieldError: # It's not unusual for add_callback to be used with # methods returning a non-None and non-yieldable # result, which should just be ignored. pass else: self.add_future(ret, self._discard_future_result) except asyncio.CancelledError: pass except Exception: app_log.error("Exception in callback %r", callback, exc_info=True)
python
def _run_callback(self, callback: Callable[[], Any]) -> None: """Runs a callback with error handling. .. versionchanged:: 6.0 CancelledErrors are no longer logged. """ try: ret = callback() if ret is not None: from tornado import gen # Functions that return Futures typically swallow all # exceptions and store them in the Future. If a Future # makes it out to the IOLoop, ensure its exception (if any) # gets logged too. try: ret = gen.convert_yielded(ret) except gen.BadYieldError: # It's not unusual for add_callback to be used with # methods returning a non-None and non-yieldable # result, which should just be ignored. pass else: self.add_future(ret, self._discard_future_result) except asyncio.CancelledError: pass except Exception: app_log.error("Exception in callback %r", callback, exc_info=True)
[ "def", "_run_callback", "(", "self", ",", "callback", ":", "Callable", "[", "[", "]", ",", "Any", "]", ")", "->", "None", ":", "try", ":", "ret", "=", "callback", "(", ")", "if", "ret", "is", "not", "None", ":", "from", "tornado", "import", "gen", "# Functions that return Futures typically swallow all", "# exceptions and store them in the Future. If a Future", "# makes it out to the IOLoop, ensure its exception (if any)", "# gets logged too.", "try", ":", "ret", "=", "gen", ".", "convert_yielded", "(", "ret", ")", "except", "gen", ".", "BadYieldError", ":", "# It's not unusual for add_callback to be used with", "# methods returning a non-None and non-yieldable", "# result, which should just be ignored.", "pass", "else", ":", "self", ".", "add_future", "(", "ret", ",", "self", ".", "_discard_future_result", ")", "except", "asyncio", ".", "CancelledError", ":", "pass", "except", "Exception", ":", "app_log", ".", "error", "(", "\"Exception in callback %r\"", ",", "callback", ",", "exc_info", "=", "True", ")" ]
Runs a callback with error handling. .. versionchanged:: 6.0 CancelledErrors are no longer logged.
[ "Runs", "a", "callback", "with", "error", "handling", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L735-L763
train
tornadoweb/tornado
tornado/ioloop.py
PeriodicCallback.start
def start(self) -> None: """Starts the timer.""" # Looking up the IOLoop here allows to first instantiate the # PeriodicCallback in another thread, then start it using # IOLoop.add_callback(). self.io_loop = IOLoop.current() self._running = True self._next_timeout = self.io_loop.time() self._schedule_next()
python
def start(self) -> None: """Starts the timer.""" # Looking up the IOLoop here allows to first instantiate the # PeriodicCallback in another thread, then start it using # IOLoop.add_callback(). self.io_loop = IOLoop.current() self._running = True self._next_timeout = self.io_loop.time() self._schedule_next()
[ "def", "start", "(", "self", ")", "->", "None", ":", "# Looking up the IOLoop here allows to first instantiate the", "# PeriodicCallback in another thread, then start it using", "# IOLoop.add_callback().", "self", ".", "io_loop", "=", "IOLoop", ".", "current", "(", ")", "self", ".", "_running", "=", "True", "self", ".", "_next_timeout", "=", "self", ".", "io_loop", ".", "time", "(", ")", "self", ".", "_schedule_next", "(", ")" ]
Starts the timer.
[ "Starts", "the", "timer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L879-L887
train
tornadoweb/tornado
tornado/ioloop.py
PeriodicCallback.stop
def stop(self) -> None: """Stops the timer.""" self._running = False if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = None
python
def stop(self) -> None: """Stops the timer.""" self._running = False if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = None
[ "def", "stop", "(", "self", ")", "->", "None", ":", "self", ".", "_running", "=", "False", "if", "self", ".", "_timeout", "is", "not", "None", ":", "self", ".", "io_loop", ".", "remove_timeout", "(", "self", ".", "_timeout", ")", "self", ".", "_timeout", "=", "None" ]
Stops the timer.
[ "Stops", "the", "timer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/ioloop.py#L889-L894
train
tornadoweb/tornado
tornado/httputil.py
url_concat
def url_concat( url: str, args: Union[ None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...] ], ) -> str: """Concatenate url and arguments regardless of whether url has existing query parameters. ``args`` may be either a dictionary or a list of key-value pairs (the latter allows for multiple values with the same key. >>> url_concat("http://example.com/foo", dict(c="d")) 'http://example.com/foo?c=d' >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ if args is None: return url parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) parsed_query.extend(args.items()) elif isinstance(args, list) or isinstance(args, tuple): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) parsed_query.extend(args) else: err = "'args' parameter should be dict, list or tuple. Not {0}".format( type(args) ) raise TypeError(err) final_query = urlencode(parsed_query) url = urlunparse( ( parsed_url[0], parsed_url[1], parsed_url[2], parsed_url[3], final_query, parsed_url[5], ) ) return url
python
def url_concat( url: str, args: Union[ None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...] ], ) -> str: """Concatenate url and arguments regardless of whether url has existing query parameters. ``args`` may be either a dictionary or a list of key-value pairs (the latter allows for multiple values with the same key. >>> url_concat("http://example.com/foo", dict(c="d")) 'http://example.com/foo?c=d' >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2' """ if args is None: return url parsed_url = urlparse(url) if isinstance(args, dict): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) parsed_query.extend(args.items()) elif isinstance(args, list) or isinstance(args, tuple): parsed_query = parse_qsl(parsed_url.query, keep_blank_values=True) parsed_query.extend(args) else: err = "'args' parameter should be dict, list or tuple. Not {0}".format( type(args) ) raise TypeError(err) final_query = urlencode(parsed_query) url = urlunparse( ( parsed_url[0], parsed_url[1], parsed_url[2], parsed_url[3], final_query, parsed_url[5], ) ) return url
[ "def", "url_concat", "(", "url", ":", "str", ",", "args", ":", "Union", "[", "None", ",", "Dict", "[", "str", ",", "str", "]", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "Tuple", "[", "Tuple", "[", "str", ",", "str", "]", ",", "...", "]", "]", ",", ")", "->", "str", ":", "if", "args", "is", "None", ":", "return", "url", "parsed_url", "=", "urlparse", "(", "url", ")", "if", "isinstance", "(", "args", ",", "dict", ")", ":", "parsed_query", "=", "parse_qsl", "(", "parsed_url", ".", "query", ",", "keep_blank_values", "=", "True", ")", "parsed_query", ".", "extend", "(", "args", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "args", ",", "list", ")", "or", "isinstance", "(", "args", ",", "tuple", ")", ":", "parsed_query", "=", "parse_qsl", "(", "parsed_url", ".", "query", ",", "keep_blank_values", "=", "True", ")", "parsed_query", ".", "extend", "(", "args", ")", "else", ":", "err", "=", "\"'args' parameter should be dict, list or tuple. Not {0}\"", ".", "format", "(", "type", "(", "args", ")", ")", "raise", "TypeError", "(", "err", ")", "final_query", "=", "urlencode", "(", "parsed_query", ")", "url", "=", "urlunparse", "(", "(", "parsed_url", "[", "0", "]", ",", "parsed_url", "[", "1", "]", ",", "parsed_url", "[", "2", "]", ",", "parsed_url", "[", "3", "]", ",", "final_query", ",", "parsed_url", "[", "5", "]", ",", ")", ")", "return", "url" ]
Concatenate url and arguments regardless of whether url has existing query parameters. ``args`` may be either a dictionary or a list of key-value pairs (the latter allows for multiple values with the same key. >>> url_concat("http://example.com/foo", dict(c="d")) 'http://example.com/foo?c=d' >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")]) 'http://example.com/foo?a=b&c=d&c=d2'
[ "Concatenate", "url", "and", "arguments", "regardless", "of", "whether", "url", "has", "existing", "query", "parameters", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L631-L675
train
tornadoweb/tornado
tornado/httputil.py
_parse_request_range
def _parse_request_range( range_header: str ) -> Optional[Tuple[Optional[int], Optional[int]]]: """Parses a Range header. Returns either ``None`` or tuple ``(start, end)``. Note that while the HTTP headers use inclusive byte positions, this method returns indexes suitable for use in slices. >>> start, end = _parse_request_range("bytes=1-2") >>> start, end (1, 3) >>> [0, 1, 2, 3, 4][start:end] [1, 2] >>> _parse_request_range("bytes=6-") (6, None) >>> _parse_request_range("bytes=-6") (-6, None) >>> _parse_request_range("bytes=-0") (None, 0) >>> _parse_request_range("bytes=") (None, None) >>> _parse_request_range("foo=42") >>> _parse_request_range("bytes=1-2,6-10") Note: only supports one range (ex, ``bytes=1-2,6-10`` is not allowed). See [0] for the details of the range header. [0]: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges """ unit, _, value = range_header.partition("=") unit, value = unit.strip(), value.strip() if unit != "bytes": return None start_b, _, end_b = value.partition("-") try: start = _int_or_none(start_b) end = _int_or_none(end_b) except ValueError: return None if end is not None: if start is None: if end != 0: start = -end end = None else: end += 1 return (start, end)
python
def _parse_request_range( range_header: str ) -> Optional[Tuple[Optional[int], Optional[int]]]: """Parses a Range header. Returns either ``None`` or tuple ``(start, end)``. Note that while the HTTP headers use inclusive byte positions, this method returns indexes suitable for use in slices. >>> start, end = _parse_request_range("bytes=1-2") >>> start, end (1, 3) >>> [0, 1, 2, 3, 4][start:end] [1, 2] >>> _parse_request_range("bytes=6-") (6, None) >>> _parse_request_range("bytes=-6") (-6, None) >>> _parse_request_range("bytes=-0") (None, 0) >>> _parse_request_range("bytes=") (None, None) >>> _parse_request_range("foo=42") >>> _parse_request_range("bytes=1-2,6-10") Note: only supports one range (ex, ``bytes=1-2,6-10`` is not allowed). See [0] for the details of the range header. [0]: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges """ unit, _, value = range_header.partition("=") unit, value = unit.strip(), value.strip() if unit != "bytes": return None start_b, _, end_b = value.partition("-") try: start = _int_or_none(start_b) end = _int_or_none(end_b) except ValueError: return None if end is not None: if start is None: if end != 0: start = -end end = None else: end += 1 return (start, end)
[ "def", "_parse_request_range", "(", "range_header", ":", "str", ")", "->", "Optional", "[", "Tuple", "[", "Optional", "[", "int", "]", ",", "Optional", "[", "int", "]", "]", "]", ":", "unit", ",", "_", ",", "value", "=", "range_header", ".", "partition", "(", "\"=\"", ")", "unit", ",", "value", "=", "unit", ".", "strip", "(", ")", ",", "value", ".", "strip", "(", ")", "if", "unit", "!=", "\"bytes\"", ":", "return", "None", "start_b", ",", "_", ",", "end_b", "=", "value", ".", "partition", "(", "\"-\"", ")", "try", ":", "start", "=", "_int_or_none", "(", "start_b", ")", "end", "=", "_int_or_none", "(", "end_b", ")", "except", "ValueError", ":", "return", "None", "if", "end", "is", "not", "None", ":", "if", "start", "is", "None", ":", "if", "end", "!=", "0", ":", "start", "=", "-", "end", "end", "=", "None", "else", ":", "end", "+=", "1", "return", "(", "start", ",", "end", ")" ]
Parses a Range header. Returns either ``None`` or tuple ``(start, end)``. Note that while the HTTP headers use inclusive byte positions, this method returns indexes suitable for use in slices. >>> start, end = _parse_request_range("bytes=1-2") >>> start, end (1, 3) >>> [0, 1, 2, 3, 4][start:end] [1, 2] >>> _parse_request_range("bytes=6-") (6, None) >>> _parse_request_range("bytes=-6") (-6, None) >>> _parse_request_range("bytes=-0") (None, 0) >>> _parse_request_range("bytes=") (None, None) >>> _parse_request_range("foo=42") >>> _parse_request_range("bytes=1-2,6-10") Note: only supports one range (ex, ``bytes=1-2,6-10`` is not allowed). See [0] for the details of the range header. [0]: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges
[ "Parses", "a", "Range", "header", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L692-L740
train
tornadoweb/tornado
tornado/httputil.py
_get_content_range
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: """Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4 """ start = start or 0 end = (end or total) - 1 return "bytes %s-%s/%s" % (start, end, total)
python
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: """Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4 """ start = start or 0 end = (end or total) - 1 return "bytes %s-%s/%s" % (start, end, total)
[ "def", "_get_content_range", "(", "start", ":", "Optional", "[", "int", "]", ",", "end", ":", "Optional", "[", "int", "]", ",", "total", ":", "int", ")", "->", "str", ":", "start", "=", "start", "or", "0", "end", "=", "(", "end", "or", "total", ")", "-", "1", "return", "\"bytes %s-%s/%s\"", "%", "(", "start", ",", "end", ",", "total", ")" ]
Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4
[ "Returns", "a", "suitable", "Content", "-", "Range", "header", ":" ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L743-L755
train
tornadoweb/tornado
tornado/httputil.py
parse_body_arguments
def parse_body_arguments( content_type: str, body: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], headers: HTTPHeaders = None, ) -> None: """Parses a form request body. Supports ``application/x-www-form-urlencoded`` and ``multipart/form-data``. The ``content_type`` parameter should be a string and ``body`` should be a byte string. The ``arguments`` and ``files`` parameters are dictionaries that will be updated with the parsed contents. """ if content_type.startswith("application/x-www-form-urlencoded"): if headers and "Content-Encoding" in headers: gen_log.warning( "Unsupported Content-Encoding: %s", headers["Content-Encoding"] ) return try: uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True) except Exception as e: gen_log.warning("Invalid x-www-form-urlencoded body: %s", e) uri_arguments = {} for name, values in uri_arguments.items(): if values: arguments.setdefault(name, []).extend(values) elif content_type.startswith("multipart/form-data"): if headers and "Content-Encoding" in headers: gen_log.warning( "Unsupported Content-Encoding: %s", headers["Content-Encoding"] ) return try: fields = content_type.split(";") for field in fields: k, sep, v = field.strip().partition("=") if k == "boundary" and v: parse_multipart_form_data(utf8(v), body, arguments, files) break else: raise ValueError("multipart boundary not found") except Exception as e: gen_log.warning("Invalid multipart/form-data: %s", e)
python
def parse_body_arguments( content_type: str, body: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], headers: HTTPHeaders = None, ) -> None: """Parses a form request body. Supports ``application/x-www-form-urlencoded`` and ``multipart/form-data``. The ``content_type`` parameter should be a string and ``body`` should be a byte string. The ``arguments`` and ``files`` parameters are dictionaries that will be updated with the parsed contents. """ if content_type.startswith("application/x-www-form-urlencoded"): if headers and "Content-Encoding" in headers: gen_log.warning( "Unsupported Content-Encoding: %s", headers["Content-Encoding"] ) return try: uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True) except Exception as e: gen_log.warning("Invalid x-www-form-urlencoded body: %s", e) uri_arguments = {} for name, values in uri_arguments.items(): if values: arguments.setdefault(name, []).extend(values) elif content_type.startswith("multipart/form-data"): if headers and "Content-Encoding" in headers: gen_log.warning( "Unsupported Content-Encoding: %s", headers["Content-Encoding"] ) return try: fields = content_type.split(";") for field in fields: k, sep, v = field.strip().partition("=") if k == "boundary" and v: parse_multipart_form_data(utf8(v), body, arguments, files) break else: raise ValueError("multipart boundary not found") except Exception as e: gen_log.warning("Invalid multipart/form-data: %s", e)
[ "def", "parse_body_arguments", "(", "content_type", ":", "str", ",", "body", ":", "bytes", ",", "arguments", ":", "Dict", "[", "str", ",", "List", "[", "bytes", "]", "]", ",", "files", ":", "Dict", "[", "str", ",", "List", "[", "HTTPFile", "]", "]", ",", "headers", ":", "HTTPHeaders", "=", "None", ",", ")", "->", "None", ":", "if", "content_type", ".", "startswith", "(", "\"application/x-www-form-urlencoded\"", ")", ":", "if", "headers", "and", "\"Content-Encoding\"", "in", "headers", ":", "gen_log", ".", "warning", "(", "\"Unsupported Content-Encoding: %s\"", ",", "headers", "[", "\"Content-Encoding\"", "]", ")", "return", "try", ":", "uri_arguments", "=", "parse_qs_bytes", "(", "native_str", "(", "body", ")", ",", "keep_blank_values", "=", "True", ")", "except", "Exception", "as", "e", ":", "gen_log", ".", "warning", "(", "\"Invalid x-www-form-urlencoded body: %s\"", ",", "e", ")", "uri_arguments", "=", "{", "}", "for", "name", ",", "values", "in", "uri_arguments", ".", "items", "(", ")", ":", "if", "values", ":", "arguments", ".", "setdefault", "(", "name", ",", "[", "]", ")", ".", "extend", "(", "values", ")", "elif", "content_type", ".", "startswith", "(", "\"multipart/form-data\"", ")", ":", "if", "headers", "and", "\"Content-Encoding\"", "in", "headers", ":", "gen_log", ".", "warning", "(", "\"Unsupported Content-Encoding: %s\"", ",", "headers", "[", "\"Content-Encoding\"", "]", ")", "return", "try", ":", "fields", "=", "content_type", ".", "split", "(", "\";\"", ")", "for", "field", "in", "fields", ":", "k", ",", "sep", ",", "v", "=", "field", ".", "strip", "(", ")", ".", "partition", "(", "\"=\"", ")", "if", "k", "==", "\"boundary\"", "and", "v", ":", "parse_multipart_form_data", "(", "utf8", "(", "v", ")", ",", "body", ",", "arguments", ",", "files", ")", "break", "else", ":", "raise", "ValueError", "(", "\"multipart boundary not found\"", ")", "except", "Exception", "as", "e", ":", "gen_log", ".", "warning", "(", "\"Invalid multipart/form-data: %s\"", ",", "e", ")" ]
Parses a form request body. Supports ``application/x-www-form-urlencoded`` and ``multipart/form-data``. The ``content_type`` parameter should be a string and ``body`` should be a byte string. The ``arguments`` and ``files`` parameters are dictionaries that will be updated with the parsed contents.
[ "Parses", "a", "form", "request", "body", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L765-L810
train
tornadoweb/tornado
tornado/httputil.py
parse_multipart_form_data
def parse_multipart_form_data( boundary: bytes, data: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], ) -> None: """Parses a ``multipart/form-data`` body. The ``boundary`` and ``data`` parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. .. versionchanged:: 5.1 Now recognizes non-ASCII filenames in RFC 2231/5987 (``filename*=``) format. """ # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at least for google app engine # xmpp). I think we're also supposed to handle backslash-escapes # here but I'll save that until we see a client that uses them # in the wild. if boundary.startswith(b'"') and boundary.endswith(b'"'): boundary = boundary[1:-1] final_boundary_index = data.rfind(b"--" + boundary + b"--") if final_boundary_index == -1: gen_log.warning("Invalid multipart/form-data: no final boundary") return parts = data[:final_boundary_index].split(b"--" + boundary + b"\r\n") for part in parts: if not part: continue eoh = part.find(b"\r\n\r\n") if eoh == -1: gen_log.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh].decode("utf-8")) disp_header = headers.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header) if disposition != "form-data" or not part.endswith(b"\r\n"): gen_log.warning("Invalid multipart/form-data") continue value = part[eoh + 4 : -2] if not disp_params.get("name"): gen_log.warning("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append( HTTPFile( filename=disp_params["filename"], body=value, content_type=ctype ) ) else: arguments.setdefault(name, []).append(value)
python
def parse_multipart_form_data( boundary: bytes, data: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], ) -> None: """Parses a ``multipart/form-data`` body. The ``boundary`` and ``data`` parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. .. versionchanged:: 5.1 Now recognizes non-ASCII filenames in RFC 2231/5987 (``filename*=``) format. """ # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at least for google app engine # xmpp). I think we're also supposed to handle backslash-escapes # here but I'll save that until we see a client that uses them # in the wild. if boundary.startswith(b'"') and boundary.endswith(b'"'): boundary = boundary[1:-1] final_boundary_index = data.rfind(b"--" + boundary + b"--") if final_boundary_index == -1: gen_log.warning("Invalid multipart/form-data: no final boundary") return parts = data[:final_boundary_index].split(b"--" + boundary + b"\r\n") for part in parts: if not part: continue eoh = part.find(b"\r\n\r\n") if eoh == -1: gen_log.warning("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(part[:eoh].decode("utf-8")) disp_header = headers.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header) if disposition != "form-data" or not part.endswith(b"\r\n"): gen_log.warning("Invalid multipart/form-data") continue value = part[eoh + 4 : -2] if not disp_params.get("name"): gen_log.warning("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append( HTTPFile( filename=disp_params["filename"], body=value, content_type=ctype ) ) else: arguments.setdefault(name, []).append(value)
[ "def", "parse_multipart_form_data", "(", "boundary", ":", "bytes", ",", "data", ":", "bytes", ",", "arguments", ":", "Dict", "[", "str", ",", "List", "[", "bytes", "]", "]", ",", "files", ":", "Dict", "[", "str", ",", "List", "[", "HTTPFile", "]", "]", ",", ")", "->", "None", ":", "# The standard allows for the boundary to be quoted in the header,", "# although it's rare (it happens at least for google app engine", "# xmpp). I think we're also supposed to handle backslash-escapes", "# here but I'll save that until we see a client that uses them", "# in the wild.", "if", "boundary", ".", "startswith", "(", "b'\"'", ")", "and", "boundary", ".", "endswith", "(", "b'\"'", ")", ":", "boundary", "=", "boundary", "[", "1", ":", "-", "1", "]", "final_boundary_index", "=", "data", ".", "rfind", "(", "b\"--\"", "+", "boundary", "+", "b\"--\"", ")", "if", "final_boundary_index", "==", "-", "1", ":", "gen_log", ".", "warning", "(", "\"Invalid multipart/form-data: no final boundary\"", ")", "return", "parts", "=", "data", "[", ":", "final_boundary_index", "]", ".", "split", "(", "b\"--\"", "+", "boundary", "+", "b\"\\r\\n\"", ")", "for", "part", "in", "parts", ":", "if", "not", "part", ":", "continue", "eoh", "=", "part", ".", "find", "(", "b\"\\r\\n\\r\\n\"", ")", "if", "eoh", "==", "-", "1", ":", "gen_log", ".", "warning", "(", "\"multipart/form-data missing headers\"", ")", "continue", "headers", "=", "HTTPHeaders", ".", "parse", "(", "part", "[", ":", "eoh", "]", ".", "decode", "(", "\"utf-8\"", ")", ")", "disp_header", "=", "headers", ".", "get", "(", "\"Content-Disposition\"", ",", "\"\"", ")", "disposition", ",", "disp_params", "=", "_parse_header", "(", "disp_header", ")", "if", "disposition", "!=", "\"form-data\"", "or", "not", "part", ".", "endswith", "(", "b\"\\r\\n\"", ")", ":", "gen_log", ".", "warning", "(", "\"Invalid multipart/form-data\"", ")", "continue", "value", "=", "part", "[", "eoh", "+", "4", ":", "-", "2", "]", "if", "not", "disp_params", ".", "get", "(", "\"name\"", ")", ":", "gen_log", ".", "warning", "(", "\"multipart/form-data value missing name\"", ")", "continue", "name", "=", "disp_params", "[", "\"name\"", "]", "if", "disp_params", ".", "get", "(", "\"filename\"", ")", ":", "ctype", "=", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"application/unknown\"", ")", "files", ".", "setdefault", "(", "name", ",", "[", "]", ")", ".", "append", "(", "HTTPFile", "(", "filename", "=", "disp_params", "[", "\"filename\"", "]", ",", "body", "=", "value", ",", "content_type", "=", "ctype", ")", ")", "else", ":", "arguments", ".", "setdefault", "(", "name", ",", "[", "]", ")", ".", "append", "(", "value", ")" ]
Parses a ``multipart/form-data`` body. The ``boundary`` and ``data`` parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. .. versionchanged:: 5.1 Now recognizes non-ASCII filenames in RFC 2231/5987 (``filename*=``) format.
[ "Parses", "a", "multipart", "/", "form", "-", "data", "body", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L813-L868
train
tornadoweb/tornado
tornado/httputil.py
format_timestamp
def format_timestamp( ts: Union[int, float, tuple, time.struct_time, datetime.datetime] ) -> str: """Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >>> format_timestamp(1359312200) 'Sun, 27 Jan 2013 18:43:20 GMT' """ if isinstance(ts, (int, float)): time_num = ts elif isinstance(ts, (tuple, time.struct_time)): time_num = calendar.timegm(ts) elif isinstance(ts, datetime.datetime): time_num = calendar.timegm(ts.utctimetuple()) else: raise TypeError("unknown timestamp type: %r" % ts) return email.utils.formatdate(time_num, usegmt=True)
python
def format_timestamp( ts: Union[int, float, tuple, time.struct_time, datetime.datetime] ) -> str: """Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >>> format_timestamp(1359312200) 'Sun, 27 Jan 2013 18:43:20 GMT' """ if isinstance(ts, (int, float)): time_num = ts elif isinstance(ts, (tuple, time.struct_time)): time_num = calendar.timegm(ts) elif isinstance(ts, datetime.datetime): time_num = calendar.timegm(ts.utctimetuple()) else: raise TypeError("unknown timestamp type: %r" % ts) return email.utils.formatdate(time_num, usegmt=True)
[ "def", "format_timestamp", "(", "ts", ":", "Union", "[", "int", ",", "float", ",", "tuple", ",", "time", ".", "struct_time", ",", "datetime", ".", "datetime", "]", ")", "->", "str", ":", "if", "isinstance", "(", "ts", ",", "(", "int", ",", "float", ")", ")", ":", "time_num", "=", "ts", "elif", "isinstance", "(", "ts", ",", "(", "tuple", ",", "time", ".", "struct_time", ")", ")", ":", "time_num", "=", "calendar", ".", "timegm", "(", "ts", ")", "elif", "isinstance", "(", "ts", ",", "datetime", ".", "datetime", ")", ":", "time_num", "=", "calendar", ".", "timegm", "(", "ts", ".", "utctimetuple", "(", ")", ")", "else", ":", "raise", "TypeError", "(", "\"unknown timestamp type: %r\"", "%", "ts", ")", "return", "email", ".", "utils", ".", "formatdate", "(", "time_num", ",", "usegmt", "=", "True", ")" ]
Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >>> format_timestamp(1359312200) 'Sun, 27 Jan 2013 18:43:20 GMT'
[ "Formats", "a", "timestamp", "in", "the", "format", "used", "by", "HTTP", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L871-L891
train
tornadoweb/tornado
tornado/httputil.py
parse_request_start_line
def parse_request_start_line(line: str) -> RequestStartLine: """Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1') """ try: method, path, version = line.split(" ") except ValueError: # https://tools.ietf.org/html/rfc7230#section-3.1.1 # invalid request-line SHOULD respond with a 400 (Bad Request) raise HTTPInputError("Malformed HTTP request line") if not re.match(r"^HTTP/1\.[0-9]$", version): raise HTTPInputError( "Malformed HTTP version in HTTP Request-Line: %r" % version ) return RequestStartLine(method, path, version)
python
def parse_request_start_line(line: str) -> RequestStartLine: """Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1') """ try: method, path, version = line.split(" ") except ValueError: # https://tools.ietf.org/html/rfc7230#section-3.1.1 # invalid request-line SHOULD respond with a 400 (Bad Request) raise HTTPInputError("Malformed HTTP request line") if not re.match(r"^HTTP/1\.[0-9]$", version): raise HTTPInputError( "Malformed HTTP version in HTTP Request-Line: %r" % version ) return RequestStartLine(method, path, version)
[ "def", "parse_request_start_line", "(", "line", ":", "str", ")", "->", "RequestStartLine", ":", "try", ":", "method", ",", "path", ",", "version", "=", "line", ".", "split", "(", "\" \"", ")", "except", "ValueError", ":", "# https://tools.ietf.org/html/rfc7230#section-3.1.1", "# invalid request-line SHOULD respond with a 400 (Bad Request)", "raise", "HTTPInputError", "(", "\"Malformed HTTP request line\"", ")", "if", "not", "re", ".", "match", "(", "r\"^HTTP/1\\.[0-9]$\"", ",", "version", ")", ":", "raise", "HTTPInputError", "(", "\"Malformed HTTP version in HTTP Request-Line: %r\"", "%", "version", ")", "return", "RequestStartLine", "(", "method", ",", "path", ",", "version", ")" ]
Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
[ "Returns", "a", "(", "method", "path", "version", ")", "tuple", "for", "an", "HTTP", "1", ".", "x", "request", "line", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L899-L917
train
tornadoweb/tornado
tornado/httputil.py
parse_response_start_line
def parse_response_start_line(line: str) -> ResponseStartLine: """Returns a (version, code, reason) tuple for an HTTP 1.x response line. The response is a `collections.namedtuple`. >>> parse_response_start_line("HTTP/1.1 200 OK") ResponseStartLine(version='HTTP/1.1', code=200, reason='OK') """ line = native_str(line) match = re.match("(HTTP/1.[0-9]) ([0-9]+) ([^\r]*)", line) if not match: raise HTTPInputError("Error parsing response start line") return ResponseStartLine(match.group(1), int(match.group(2)), match.group(3))
python
def parse_response_start_line(line: str) -> ResponseStartLine: """Returns a (version, code, reason) tuple for an HTTP 1.x response line. The response is a `collections.namedtuple`. >>> parse_response_start_line("HTTP/1.1 200 OK") ResponseStartLine(version='HTTP/1.1', code=200, reason='OK') """ line = native_str(line) match = re.match("(HTTP/1.[0-9]) ([0-9]+) ([^\r]*)", line) if not match: raise HTTPInputError("Error parsing response start line") return ResponseStartLine(match.group(1), int(match.group(2)), match.group(3))
[ "def", "parse_response_start_line", "(", "line", ":", "str", ")", "->", "ResponseStartLine", ":", "line", "=", "native_str", "(", "line", ")", "match", "=", "re", ".", "match", "(", "\"(HTTP/1.[0-9]) ([0-9]+) ([^\\r]*)\"", ",", "line", ")", "if", "not", "match", ":", "raise", "HTTPInputError", "(", "\"Error parsing response start line\"", ")", "return", "ResponseStartLine", "(", "match", ".", "group", "(", "1", ")", ",", "int", "(", "match", ".", "group", "(", "2", ")", ")", ",", "match", ".", "group", "(", "3", ")", ")" ]
Returns a (version, code, reason) tuple for an HTTP 1.x response line. The response is a `collections.namedtuple`. >>> parse_response_start_line("HTTP/1.1 200 OK") ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
[ "Returns", "a", "(", "version", "code", "reason", ")", "tuple", "for", "an", "HTTP", "1", ".", "x", "response", "line", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L925-L937
train
tornadoweb/tornado
tornado/httputil.py
_parse_header
def _parse_header(line: str) -> Tuple[str, Dict[str, str]]: r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape') True >>> d['foo'] 'b\\a"r' """ parts = _parseparam(";" + line) key = next(parts) # decode_params treats first argument special, but we already stripped key params = [("Dummy", "value")] for p in parts: i = p.find("=") if i >= 0: name = p[:i].strip().lower() value = p[i + 1 :].strip() params.append((name, native_str(value))) decoded_params = email.utils.decode_params(params) decoded_params.pop(0) # get rid of the dummy again pdict = {} for name, decoded_value in decoded_params: value = email.utils.collapse_rfc2231_value(decoded_value) if len(value) >= 2 and value[0] == '"' and value[-1] == '"': value = value[1:-1] pdict[name] = value return key, pdict
python
def _parse_header(line: str) -> Tuple[str, Dict[str, str]]: r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape') True >>> d['foo'] 'b\\a"r' """ parts = _parseparam(";" + line) key = next(parts) # decode_params treats first argument special, but we already stripped key params = [("Dummy", "value")] for p in parts: i = p.find("=") if i >= 0: name = p[:i].strip().lower() value = p[i + 1 :].strip() params.append((name, native_str(value))) decoded_params = email.utils.decode_params(params) decoded_params.pop(0) # get rid of the dummy again pdict = {} for name, decoded_value in decoded_params: value = email.utils.collapse_rfc2231_value(decoded_value) if len(value) >= 2 and value[0] == '"' and value[-1] == '"': value = value[1:-1] pdict[name] = value return key, pdict
[ "def", "_parse_header", "(", "line", ":", "str", ")", "->", "Tuple", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "parts", "=", "_parseparam", "(", "\";\"", "+", "line", ")", "key", "=", "next", "(", "parts", ")", "# decode_params treats first argument special, but we already stripped key", "params", "=", "[", "(", "\"Dummy\"", ",", "\"value\"", ")", "]", "for", "p", "in", "parts", ":", "i", "=", "p", ".", "find", "(", "\"=\"", ")", "if", "i", ">=", "0", ":", "name", "=", "p", "[", ":", "i", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "value", "=", "p", "[", "i", "+", "1", ":", "]", ".", "strip", "(", ")", "params", ".", "append", "(", "(", "name", ",", "native_str", "(", "value", ")", ")", ")", "decoded_params", "=", "email", ".", "utils", ".", "decode_params", "(", "params", ")", "decoded_params", ".", "pop", "(", "0", ")", "# get rid of the dummy again", "pdict", "=", "{", "}", "for", "name", ",", "decoded_value", "in", "decoded_params", ":", "value", "=", "email", ".", "utils", ".", "collapse_rfc2231_value", "(", "decoded_value", ")", "if", "len", "(", "value", ")", ">=", "2", "and", "value", "[", "0", "]", "==", "'\"'", "and", "value", "[", "-", "1", "]", "==", "'\"'", ":", "value", "=", "value", "[", "1", ":", "-", "1", "]", "pdict", "[", "name", "]", "=", "value", "return", "key", ",", "pdict" ]
r"""Parse a Content-type like header. Return the main content-type and a dictionary of options. >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st" >>> ct, d = _parse_header(d) >>> ct 'form-data' >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape') True >>> d['foo'] 'b\\a"r'
[ "r", "Parse", "a", "Content", "-", "type", "like", "header", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L961-L993
train
tornadoweb/tornado
tornado/httputil.py
_encode_header
def _encode_header(key: str, pdict: Dict[str, str]) -> str: """Inverse of _parse_header. >>> _encode_header('permessage-deflate', ... {'client_max_window_bits': 15, 'client_no_context_takeover': None}) 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover' """ if not pdict: return key out = [key] # Sort the parameters just to make it easy to test. for k, v in sorted(pdict.items()): if v is None: out.append(k) else: # TODO: quote if necessary. out.append("%s=%s" % (k, v)) return "; ".join(out)
python
def _encode_header(key: str, pdict: Dict[str, str]) -> str: """Inverse of _parse_header. >>> _encode_header('permessage-deflate', ... {'client_max_window_bits': 15, 'client_no_context_takeover': None}) 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover' """ if not pdict: return key out = [key] # Sort the parameters just to make it easy to test. for k, v in sorted(pdict.items()): if v is None: out.append(k) else: # TODO: quote if necessary. out.append("%s=%s" % (k, v)) return "; ".join(out)
[ "def", "_encode_header", "(", "key", ":", "str", ",", "pdict", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "if", "not", "pdict", ":", "return", "key", "out", "=", "[", "key", "]", "# Sort the parameters just to make it easy to test.", "for", "k", ",", "v", "in", "sorted", "(", "pdict", ".", "items", "(", ")", ")", ":", "if", "v", "is", "None", ":", "out", ".", "append", "(", "k", ")", "else", ":", "# TODO: quote if necessary.", "out", ".", "append", "(", "\"%s=%s\"", "%", "(", "k", ",", "v", ")", ")", "return", "\"; \"", ".", "join", "(", "out", ")" ]
Inverse of _parse_header. >>> _encode_header('permessage-deflate', ... {'client_max_window_bits': 15, 'client_no_context_takeover': None}) 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
[ "Inverse", "of", "_parse_header", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L996-L1013
train
tornadoweb/tornado
tornado/httputil.py
encode_username_password
def encode_username_password( username: Union[str, bytes], password: Union[str, bytes] ) -> bytes: """Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1 """ if isinstance(username, unicode_type): username = unicodedata.normalize("NFC", username) if isinstance(password, unicode_type): password = unicodedata.normalize("NFC", password) return utf8(username) + b":" + utf8(password)
python
def encode_username_password( username: Union[str, bytes], password: Union[str, bytes] ) -> bytes: """Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1 """ if isinstance(username, unicode_type): username = unicodedata.normalize("NFC", username) if isinstance(password, unicode_type): password = unicodedata.normalize("NFC", password) return utf8(username) + b":" + utf8(password)
[ "def", "encode_username_password", "(", "username", ":", "Union", "[", "str", ",", "bytes", "]", ",", "password", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "bytes", ":", "if", "isinstance", "(", "username", ",", "unicode_type", ")", ":", "username", "=", "unicodedata", ".", "normalize", "(", "\"NFC\"", ",", "username", ")", "if", "isinstance", "(", "password", ",", "unicode_type", ")", ":", "password", "=", "unicodedata", ".", "normalize", "(", "\"NFC\"", ",", "password", ")", "return", "utf8", "(", "username", ")", "+", "b\":\"", "+", "utf8", "(", "password", ")" ]
Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1
[ "Encodes", "a", "username", "/", "password", "pair", "in", "the", "format", "used", "by", "HTTP", "auth", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1016-L1029
train
tornadoweb/tornado
tornado/httputil.py
split_host_and_port
def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]: """Returns ``(host, port)`` tuple from ``netloc``. Returned ``port`` will be ``None`` if not present. .. versionadded:: 4.1 """ match = re.match(r"^(.+):(\d+)$", netloc) if match: host = match.group(1) port = int(match.group(2)) # type: Optional[int] else: host = netloc port = None return (host, port)
python
def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]: """Returns ``(host, port)`` tuple from ``netloc``. Returned ``port`` will be ``None`` if not present. .. versionadded:: 4.1 """ match = re.match(r"^(.+):(\d+)$", netloc) if match: host = match.group(1) port = int(match.group(2)) # type: Optional[int] else: host = netloc port = None return (host, port)
[ "def", "split_host_and_port", "(", "netloc", ":", "str", ")", "->", "Tuple", "[", "str", ",", "Optional", "[", "int", "]", "]", ":", "match", "=", "re", ".", "match", "(", "r\"^(.+):(\\d+)$\"", ",", "netloc", ")", "if", "match", ":", "host", "=", "match", ".", "group", "(", "1", ")", "port", "=", "int", "(", "match", ".", "group", "(", "2", ")", ")", "# type: Optional[int]", "else", ":", "host", "=", "netloc", "port", "=", "None", "return", "(", "host", ",", "port", ")" ]
Returns ``(host, port)`` tuple from ``netloc``. Returned ``port`` will be ``None`` if not present. .. versionadded:: 4.1
[ "Returns", "(", "host", "port", ")", "tuple", "from", "netloc", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1039-L1053
train
tornadoweb/tornado
tornado/httputil.py
qs_to_qsl
def qs_to_qsl(qs: Dict[str, List[AnyStr]]) -> Iterable[Tuple[str, AnyStr]]: """Generator converting a result of ``parse_qs`` back to name-value pairs. .. versionadded:: 5.0 """ for k, vs in qs.items(): for v in vs: yield (k, v)
python
def qs_to_qsl(qs: Dict[str, List[AnyStr]]) -> Iterable[Tuple[str, AnyStr]]: """Generator converting a result of ``parse_qs`` back to name-value pairs. .. versionadded:: 5.0 """ for k, vs in qs.items(): for v in vs: yield (k, v)
[ "def", "qs_to_qsl", "(", "qs", ":", "Dict", "[", "str", ",", "List", "[", "AnyStr", "]", "]", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "AnyStr", "]", "]", ":", "for", "k", ",", "vs", "in", "qs", ".", "items", "(", ")", ":", "for", "v", "in", "vs", ":", "yield", "(", "k", ",", "v", ")" ]
Generator converting a result of ``parse_qs`` back to name-value pairs. .. versionadded:: 5.0
[ "Generator", "converting", "a", "result", "of", "parse_qs", "back", "to", "name", "-", "value", "pairs", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1056-L1063
train
tornadoweb/tornado
tornado/httputil.py
_unquote_cookie
def _unquote_cookie(s: str) -> str: """Handle double quotes and escaping in cookie values. This method is copied verbatim from the Python 3.5 standard library (http.cookies._unquote) so we don't have to depend on non-public interfaces. """ # If there aren't any doublequotes, # then there can't be any special characters. See RFC 2109. if s is None or len(s) < 2: return s if s[0] != '"' or s[-1] != '"': return s # We have to assume that we must decode this string. # Down to work. # Remove the "s s = s[1:-1] # Check for special sequences. Examples: # \012 --> \n # \" --> " # i = 0 n = len(s) res = [] while 0 <= i < n: o_match = _OctalPatt.search(s, i) q_match = _QuotePatt.search(s, i) if not o_match and not q_match: # Neither matched res.append(s[i:]) break # else: j = k = -1 if o_match: j = o_match.start(0) if q_match: k = q_match.start(0) if q_match and (not o_match or k < j): # QuotePatt matched res.append(s[i:k]) res.append(s[k + 1]) i = k + 2 else: # OctalPatt matched res.append(s[i:j]) res.append(chr(int(s[j + 1 : j + 4], 8))) i = j + 4 return _nulljoin(res)
python
def _unquote_cookie(s: str) -> str: """Handle double quotes and escaping in cookie values. This method is copied verbatim from the Python 3.5 standard library (http.cookies._unquote) so we don't have to depend on non-public interfaces. """ # If there aren't any doublequotes, # then there can't be any special characters. See RFC 2109. if s is None or len(s) < 2: return s if s[0] != '"' or s[-1] != '"': return s # We have to assume that we must decode this string. # Down to work. # Remove the "s s = s[1:-1] # Check for special sequences. Examples: # \012 --> \n # \" --> " # i = 0 n = len(s) res = [] while 0 <= i < n: o_match = _OctalPatt.search(s, i) q_match = _QuotePatt.search(s, i) if not o_match and not q_match: # Neither matched res.append(s[i:]) break # else: j = k = -1 if o_match: j = o_match.start(0) if q_match: k = q_match.start(0) if q_match and (not o_match or k < j): # QuotePatt matched res.append(s[i:k]) res.append(s[k + 1]) i = k + 2 else: # OctalPatt matched res.append(s[i:j]) res.append(chr(int(s[j + 1 : j + 4], 8))) i = j + 4 return _nulljoin(res)
[ "def", "_unquote_cookie", "(", "s", ":", "str", ")", "->", "str", ":", "# If there aren't any doublequotes,", "# then there can't be any special characters. See RFC 2109.", "if", "s", "is", "None", "or", "len", "(", "s", ")", "<", "2", ":", "return", "s", "if", "s", "[", "0", "]", "!=", "'\"'", "or", "s", "[", "-", "1", "]", "!=", "'\"'", ":", "return", "s", "# We have to assume that we must decode this string.", "# Down to work.", "# Remove the \"s", "s", "=", "s", "[", "1", ":", "-", "1", "]", "# Check for special sequences. Examples:", "# \\012 --> \\n", "# \\\" --> \"", "#", "i", "=", "0", "n", "=", "len", "(", "s", ")", "res", "=", "[", "]", "while", "0", "<=", "i", "<", "n", ":", "o_match", "=", "_OctalPatt", ".", "search", "(", "s", ",", "i", ")", "q_match", "=", "_QuotePatt", ".", "search", "(", "s", ",", "i", ")", "if", "not", "o_match", "and", "not", "q_match", ":", "# Neither matched", "res", ".", "append", "(", "s", "[", "i", ":", "]", ")", "break", "# else:", "j", "=", "k", "=", "-", "1", "if", "o_match", ":", "j", "=", "o_match", ".", "start", "(", "0", ")", "if", "q_match", ":", "k", "=", "q_match", ".", "start", "(", "0", ")", "if", "q_match", "and", "(", "not", "o_match", "or", "k", "<", "j", ")", ":", "# QuotePatt matched", "res", ".", "append", "(", "s", "[", "i", ":", "k", "]", ")", "res", ".", "append", "(", "s", "[", "k", "+", "1", "]", ")", "i", "=", "k", "+", "2", "else", ":", "# OctalPatt matched", "res", ".", "append", "(", "s", "[", "i", ":", "j", "]", ")", "res", ".", "append", "(", "chr", "(", "int", "(", "s", "[", "j", "+", "1", ":", "j", "+", "4", "]", ",", "8", ")", ")", ")", "i", "=", "j", "+", "4", "return", "_nulljoin", "(", "res", ")" ]
Handle double quotes and escaping in cookie values. This method is copied verbatim from the Python 3.5 standard library (http.cookies._unquote) so we don't have to depend on non-public interfaces.
[ "Handle", "double", "quotes", "and", "escaping", "in", "cookie", "values", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1071-L1118
train
tornadoweb/tornado
tornado/httputil.py
parse_cookie
def parse_cookie(cookie: str) -> Dict[str, str]: """Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. .. versionadded:: 4.4.2 """ cookiedict = {} for chunk in cookie.split(str(";")): if str("=") in chunk: key, val = chunk.split(str("="), 1) else: # Assume an empty name per # https://bugzilla.mozilla.org/show_bug.cgi?id=169091 key, val = str(""), chunk key, val = key.strip(), val.strip() if key or val: # unquote using Python's algorithm. cookiedict[key] = _unquote_cookie(val) return cookiedict
python
def parse_cookie(cookie: str) -> Dict[str, str]: """Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. .. versionadded:: 4.4.2 """ cookiedict = {} for chunk in cookie.split(str(";")): if str("=") in chunk: key, val = chunk.split(str("="), 1) else: # Assume an empty name per # https://bugzilla.mozilla.org/show_bug.cgi?id=169091 key, val = str(""), chunk key, val = key.strip(), val.strip() if key or val: # unquote using Python's algorithm. cookiedict[key] = _unquote_cookie(val) return cookiedict
[ "def", "parse_cookie", "(", "cookie", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "cookiedict", "=", "{", "}", "for", "chunk", "in", "cookie", ".", "split", "(", "str", "(", "\";\"", ")", ")", ":", "if", "str", "(", "\"=\"", ")", "in", "chunk", ":", "key", ",", "val", "=", "chunk", ".", "split", "(", "str", "(", "\"=\"", ")", ",", "1", ")", "else", ":", "# Assume an empty name per", "# https://bugzilla.mozilla.org/show_bug.cgi?id=169091", "key", ",", "val", "=", "str", "(", "\"\"", ")", ",", "chunk", "key", ",", "val", "=", "key", ".", "strip", "(", ")", ",", "val", ".", "strip", "(", ")", "if", "key", "or", "val", ":", "# unquote using Python's algorithm.", "cookiedict", "[", "key", "]", "=", "_unquote_cookie", "(", "val", ")", "return", "cookiedict" ]
Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. .. versionadded:: 4.4.2
[ "Parse", "a", "Cookie", "HTTP", "header", "into", "a", "dict", "of", "name", "/", "value", "pairs", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L1121-L1144
train
tornadoweb/tornado
tornado/httputil.py
HTTPHeaders.add
def add(self, name: str, value: str) -> None: """Adds a new value for the given key.""" norm_name = _normalized_headers[name] self._last_key = norm_name if norm_name in self: self._dict[norm_name] = ( native_str(self[norm_name]) + "," + native_str(value) ) self._as_list[norm_name].append(value) else: self[norm_name] = value
python
def add(self, name: str, value: str) -> None: """Adds a new value for the given key.""" norm_name = _normalized_headers[name] self._last_key = norm_name if norm_name in self: self._dict[norm_name] = ( native_str(self[norm_name]) + "," + native_str(value) ) self._as_list[norm_name].append(value) else: self[norm_name] = value
[ "def", "add", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "norm_name", "=", "_normalized_headers", "[", "name", "]", "self", ".", "_last_key", "=", "norm_name", "if", "norm_name", "in", "self", ":", "self", ".", "_dict", "[", "norm_name", "]", "=", "(", "native_str", "(", "self", "[", "norm_name", "]", ")", "+", "\",\"", "+", "native_str", "(", "value", ")", ")", "self", ".", "_as_list", "[", "norm_name", "]", ".", "append", "(", "value", ")", "else", ":", "self", "[", "norm_name", "]", "=", "value" ]
Adds a new value for the given key.
[ "Adds", "a", "new", "value", "for", "the", "given", "key", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L162-L172
train
tornadoweb/tornado
tornado/httputil.py
HTTPHeaders.get_list
def get_list(self, name: str) -> List[str]: """Returns all values for the given header as a list.""" norm_name = _normalized_headers[name] return self._as_list.get(norm_name, [])
python
def get_list(self, name: str) -> List[str]: """Returns all values for the given header as a list.""" norm_name = _normalized_headers[name] return self._as_list.get(norm_name, [])
[ "def", "get_list", "(", "self", ",", "name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "norm_name", "=", "_normalized_headers", "[", "name", "]", "return", "self", ".", "_as_list", ".", "get", "(", "norm_name", ",", "[", "]", ")" ]
Returns all values for the given header as a list.
[ "Returns", "all", "values", "for", "the", "given", "header", "as", "a", "list", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L174-L177
train
tornadoweb/tornado
tornado/httputil.py
HTTPHeaders.get_all
def get_all(self) -> Iterable[Tuple[str, str]]: """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, values in self._as_list.items(): for value in values: yield (name, value)
python
def get_all(self) -> Iterable[Tuple[str, str]]: """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, values in self._as_list.items(): for value in values: yield (name, value)
[ "def", "get_all", "(", "self", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "for", "name", ",", "values", "in", "self", ".", "_as_list", ".", "items", "(", ")", ":", "for", "value", "in", "values", ":", "yield", "(", "name", ",", "value", ")" ]
Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name.
[ "Returns", "an", "iterable", "of", "all", "(", "name", "value", ")", "pairs", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L179-L187
train
tornadoweb/tornado
tornado/httputil.py
HTTPHeaders.parse_line
def parse_line(self, line: str) -> None: """Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html' """ if line[0].isspace(): # continuation of a multi-line header if self._last_key is None: raise HTTPInputError("first header line cannot start with whitespace") new_part = " " + line.lstrip() self._as_list[self._last_key][-1] += new_part self._dict[self._last_key] += new_part else: try: name, value = line.split(":", 1) except ValueError: raise HTTPInputError("no colon in header line") self.add(name, value.strip())
python
def parse_line(self, line: str) -> None: """Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html' """ if line[0].isspace(): # continuation of a multi-line header if self._last_key is None: raise HTTPInputError("first header line cannot start with whitespace") new_part = " " + line.lstrip() self._as_list[self._last_key][-1] += new_part self._dict[self._last_key] += new_part else: try: name, value = line.split(":", 1) except ValueError: raise HTTPInputError("no colon in header line") self.add(name, value.strip())
[ "def", "parse_line", "(", "self", ",", "line", ":", "str", ")", "->", "None", ":", "if", "line", "[", "0", "]", ".", "isspace", "(", ")", ":", "# continuation of a multi-line header", "if", "self", ".", "_last_key", "is", "None", ":", "raise", "HTTPInputError", "(", "\"first header line cannot start with whitespace\"", ")", "new_part", "=", "\" \"", "+", "line", ".", "lstrip", "(", ")", "self", ".", "_as_list", "[", "self", ".", "_last_key", "]", "[", "-", "1", "]", "+=", "new_part", "self", ".", "_dict", "[", "self", ".", "_last_key", "]", "+=", "new_part", "else", ":", "try", ":", "name", ",", "value", "=", "line", ".", "split", "(", "\":\"", ",", "1", ")", "except", "ValueError", ":", "raise", "HTTPInputError", "(", "\"no colon in header line\"", ")", "self", ".", "add", "(", "name", ",", "value", ".", "strip", "(", ")", ")" ]
Updates the dictionary with a single header line. >>> h = HTTPHeaders() >>> h.parse_line("Content-Type: text/html") >>> h.get('content-type') 'text/html'
[ "Updates", "the", "dictionary", "with", "a", "single", "header", "line", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L189-L209
train
tornadoweb/tornado
tornado/httputil.py
HTTPHeaders.parse
def parse(cls, headers: str) -> "HTTPHeaders": """Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.items()) [('Content-Length', '42'), ('Content-Type', 'text/html')] .. versionchanged:: 5.1 Raises `HTTPInputError` on malformed headers instead of a mix of `KeyError`, and `ValueError`. """ h = cls() for line in _CRLF_RE.split(headers): if line: h.parse_line(line) return h
python
def parse(cls, headers: str) -> "HTTPHeaders": """Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.items()) [('Content-Length', '42'), ('Content-Type', 'text/html')] .. versionchanged:: 5.1 Raises `HTTPInputError` on malformed headers instead of a mix of `KeyError`, and `ValueError`. """ h = cls() for line in _CRLF_RE.split(headers): if line: h.parse_line(line) return h
[ "def", "parse", "(", "cls", ",", "headers", ":", "str", ")", "->", "\"HTTPHeaders\"", ":", "h", "=", "cls", "(", ")", "for", "line", "in", "_CRLF_RE", ".", "split", "(", "headers", ")", ":", "if", "line", ":", "h", ".", "parse_line", "(", "line", ")", "return", "h" ]
Returns a dictionary from HTTP header text. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n") >>> sorted(h.items()) [('Content-Length', '42'), ('Content-Type', 'text/html')] .. versionchanged:: 5.1 Raises `HTTPInputError` on malformed headers instead of a mix of `KeyError`, and `ValueError`.
[ "Returns", "a", "dictionary", "from", "HTTP", "header", "text", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L212-L229
train
tornadoweb/tornado
tornado/httputil.py
HTTPServerRequest.cookies
def cookies(self) -> Dict[str, http.cookies.Morsel]: """A dictionary of ``http.cookies.Morsel`` objects.""" if not hasattr(self, "_cookies"): self._cookies = http.cookies.SimpleCookie() if "Cookie" in self.headers: try: parsed = parse_cookie(self.headers["Cookie"]) except Exception: pass else: for k, v in parsed.items(): try: self._cookies[k] = v except Exception: # SimpleCookie imposes some restrictions on keys; # parse_cookie does not. Discard any cookies # with disallowed keys. pass return self._cookies
python
def cookies(self) -> Dict[str, http.cookies.Morsel]: """A dictionary of ``http.cookies.Morsel`` objects.""" if not hasattr(self, "_cookies"): self._cookies = http.cookies.SimpleCookie() if "Cookie" in self.headers: try: parsed = parse_cookie(self.headers["Cookie"]) except Exception: pass else: for k, v in parsed.items(): try: self._cookies[k] = v except Exception: # SimpleCookie imposes some restrictions on keys; # parse_cookie does not. Discard any cookies # with disallowed keys. pass return self._cookies
[ "def", "cookies", "(", "self", ")", "->", "Dict", "[", "str", ",", "http", ".", "cookies", ".", "Morsel", "]", ":", "if", "not", "hasattr", "(", "self", ",", "\"_cookies\"", ")", ":", "self", ".", "_cookies", "=", "http", ".", "cookies", ".", "SimpleCookie", "(", ")", "if", "\"Cookie\"", "in", "self", ".", "headers", ":", "try", ":", "parsed", "=", "parse_cookie", "(", "self", ".", "headers", "[", "\"Cookie\"", "]", ")", "except", "Exception", ":", "pass", "else", ":", "for", "k", ",", "v", "in", "parsed", ".", "items", "(", ")", ":", "try", ":", "self", ".", "_cookies", "[", "k", "]", "=", "v", "except", "Exception", ":", "# SimpleCookie imposes some restrictions on keys;", "# parse_cookie does not. Discard any cookies", "# with disallowed keys.", "pass", "return", "self", ".", "_cookies" ]
A dictionary of ``http.cookies.Morsel`` objects.
[ "A", "dictionary", "of", "http", ".", "cookies", ".", "Morsel", "objects", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L410-L428
train
tornadoweb/tornado
tornado/httputil.py
HTTPServerRequest.request_time
def request_time(self) -> float: """Returns the amount of time it took for this request to execute.""" if self._finish_time is None: return time.time() - self._start_time else: return self._finish_time - self._start_time
python
def request_time(self) -> float: """Returns the amount of time it took for this request to execute.""" if self._finish_time is None: return time.time() - self._start_time else: return self._finish_time - self._start_time
[ "def", "request_time", "(", "self", ")", "->", "float", ":", "if", "self", ".", "_finish_time", "is", "None", ":", "return", "time", ".", "time", "(", ")", "-", "self", ".", "_start_time", "else", ":", "return", "self", ".", "_finish_time", "-", "self", ".", "_start_time" ]
Returns the amount of time it took for this request to execute.
[ "Returns", "the", "amount", "of", "time", "it", "took", "for", "this", "request", "to", "execute", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L434-L439
train
tornadoweb/tornado
tornado/httputil.py
HTTPServerRequest.get_ssl_certificate
def get_ssl_certificate( self, binary_form: bool = False ) -> Union[None, Dict, bytes]: """Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer's `ssl.SSLContext.verify_mode` field must be set, e.g.:: ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain("foo.crt", "foo.key") ssl_ctx.load_verify_locations("cacerts.pem") ssl_ctx.verify_mode = ssl.CERT_REQUIRED server = HTTPServer(app, ssl_options=ssl_ctx) By default, the return value is a dictionary (or None, if no client certificate is present). If ``binary_form`` is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects """ try: if self.connection is None: return None # TODO: add a method to HTTPConnection for this so it can work with HTTP/2 return self.connection.stream.socket.getpeercert( # type: ignore binary_form=binary_form ) except SSLError: return None
python
def get_ssl_certificate( self, binary_form: bool = False ) -> Union[None, Dict, bytes]: """Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer's `ssl.SSLContext.verify_mode` field must be set, e.g.:: ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain("foo.crt", "foo.key") ssl_ctx.load_verify_locations("cacerts.pem") ssl_ctx.verify_mode = ssl.CERT_REQUIRED server = HTTPServer(app, ssl_options=ssl_ctx) By default, the return value is a dictionary (or None, if no client certificate is present). If ``binary_form`` is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects """ try: if self.connection is None: return None # TODO: add a method to HTTPConnection for this so it can work with HTTP/2 return self.connection.stream.socket.getpeercert( # type: ignore binary_form=binary_form ) except SSLError: return None
[ "def", "get_ssl_certificate", "(", "self", ",", "binary_form", ":", "bool", "=", "False", ")", "->", "Union", "[", "None", ",", "Dict", ",", "bytes", "]", ":", "try", ":", "if", "self", ".", "connection", "is", "None", ":", "return", "None", "# TODO: add a method to HTTPConnection for this so it can work with HTTP/2", "return", "self", ".", "connection", ".", "stream", ".", "socket", ".", "getpeercert", "(", "# type: ignore", "binary_form", "=", "binary_form", ")", "except", "SSLError", ":", "return", "None" ]
Returns the client's SSL certificate, if any. To use client certificates, the HTTPServer's `ssl.SSLContext.verify_mode` field must be set, e.g.:: ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain("foo.crt", "foo.key") ssl_ctx.load_verify_locations("cacerts.pem") ssl_ctx.verify_mode = ssl.CERT_REQUIRED server = HTTPServer(app, ssl_options=ssl_ctx) By default, the return value is a dictionary (or None, if no client certificate is present). If ``binary_form`` is true, a DER-encoded form of the certificate is returned instead. See SSLSocket.getpeercert() in the standard library for more details. http://docs.python.org/library/ssl.html#sslsocket-objects
[ "Returns", "the", "client", "s", "SSL", "certificate", "if", "any", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L441-L470
train
tornadoweb/tornado
tornado/netutil.py
bind_sockets
def bind_sockets( port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = _DEFAULT_BACKLOG, flags: int = None, reuse_port: bool = False, ) -> List[socket.socket]: """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket in the list. If your platform doesn't support this option ValueError will be raised. """ if reuse_port and not hasattr(socket, "SO_REUSEPORT"): raise ValueError("the platform doesn't support SO_REUSEPORT") sockets = [] if address == "": address = None if not socket.has_ipv6 and family == socket.AF_UNSPEC: # Python can be compiled with --disable-ipv6, which causes # operations on AF_INET6 sockets to fail, but does not # automatically exclude those results from getaddrinfo # results. # http://bugs.python.org/issue16208 family = socket.AF_INET if flags is None: flags = socket.AI_PASSIVE bound_port = None unique_addresses = set() # type: set for res in sorted( socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags), key=lambda x: x[0], ): if res in unique_addresses: continue unique_addresses.add(res) af, socktype, proto, canonname, sockaddr = res if ( sys.platform == "darwin" and address == "localhost" and af == socket.AF_INET6 and sockaddr[3] != 0 ): # Mac OS X includes a link-local address fe80::1%lo0 in the # getaddrinfo results for 'localhost'. However, the firewall # doesn't understand that this is a local address and will # prompt for access (often repeatedly, due to an apparent # bug in its ability to remember granting access to an # application). Skip these addresses. continue try: sock = socket.socket(af, socktype, proto) except socket.error as e: if errno_from_exception(e) == errno.EAFNOSUPPORT: continue raise set_close_exec(sock.fileno()) if os.name != "nt": try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error as e: if errno_from_exception(e) != errno.ENOPROTOOPT: # Hurd doesn't support SO_REUSEADDR. raise if reuse_port: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if af == socket.AF_INET6: # On linux, ipv6 sockets accept ipv4 too by default, # but this makes it impossible to bind to both # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, # separate sockets *must* be used to listen for both ipv4 # and ipv6. For consistency, always disable ipv4 on our # ipv6 sockets and use a separate ipv4 socket when needed. # # Python 2.x on windows doesn't have IPPROTO_IPV6. if hasattr(socket, "IPPROTO_IPV6"): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) # automatic port allocation with port=None # should bind on the same port on IPv4 and IPv6 host, requested_port = sockaddr[:2] if requested_port == 0 and bound_port is not None: sockaddr = tuple([host, bound_port] + list(sockaddr[2:])) sock.setblocking(False) sock.bind(sockaddr) bound_port = sock.getsockname()[1] sock.listen(backlog) sockets.append(sock) return sockets
python
def bind_sockets( port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = _DEFAULT_BACKLOG, flags: int = None, reuse_port: bool = False, ) -> List[socket.socket]: """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket in the list. If your platform doesn't support this option ValueError will be raised. """ if reuse_port and not hasattr(socket, "SO_REUSEPORT"): raise ValueError("the platform doesn't support SO_REUSEPORT") sockets = [] if address == "": address = None if not socket.has_ipv6 and family == socket.AF_UNSPEC: # Python can be compiled with --disable-ipv6, which causes # operations on AF_INET6 sockets to fail, but does not # automatically exclude those results from getaddrinfo # results. # http://bugs.python.org/issue16208 family = socket.AF_INET if flags is None: flags = socket.AI_PASSIVE bound_port = None unique_addresses = set() # type: set for res in sorted( socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags), key=lambda x: x[0], ): if res in unique_addresses: continue unique_addresses.add(res) af, socktype, proto, canonname, sockaddr = res if ( sys.platform == "darwin" and address == "localhost" and af == socket.AF_INET6 and sockaddr[3] != 0 ): # Mac OS X includes a link-local address fe80::1%lo0 in the # getaddrinfo results for 'localhost'. However, the firewall # doesn't understand that this is a local address and will # prompt for access (often repeatedly, due to an apparent # bug in its ability to remember granting access to an # application). Skip these addresses. continue try: sock = socket.socket(af, socktype, proto) except socket.error as e: if errno_from_exception(e) == errno.EAFNOSUPPORT: continue raise set_close_exec(sock.fileno()) if os.name != "nt": try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error as e: if errno_from_exception(e) != errno.ENOPROTOOPT: # Hurd doesn't support SO_REUSEADDR. raise if reuse_port: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if af == socket.AF_INET6: # On linux, ipv6 sockets accept ipv4 too by default, # but this makes it impossible to bind to both # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, # separate sockets *must* be used to listen for both ipv4 # and ipv6. For consistency, always disable ipv4 on our # ipv6 sockets and use a separate ipv4 socket when needed. # # Python 2.x on windows doesn't have IPPROTO_IPV6. if hasattr(socket, "IPPROTO_IPV6"): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) # automatic port allocation with port=None # should bind on the same port on IPv4 and IPv6 host, requested_port = sockaddr[:2] if requested_port == 0 and bound_port is not None: sockaddr = tuple([host, bound_port] + list(sockaddr[2:])) sock.setblocking(False) sock.bind(sockaddr) bound_port = sock.getsockname()[1] sock.listen(backlog) sockets.append(sock) return sockets
[ "def", "bind_sockets", "(", "port", ":", "int", ",", "address", ":", "str", "=", "None", ",", "family", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "backlog", ":", "int", "=", "_DEFAULT_BACKLOG", ",", "flags", ":", "int", "=", "None", ",", "reuse_port", ":", "bool", "=", "False", ",", ")", "->", "List", "[", "socket", ".", "socket", "]", ":", "if", "reuse_port", "and", "not", "hasattr", "(", "socket", ",", "\"SO_REUSEPORT\"", ")", ":", "raise", "ValueError", "(", "\"the platform doesn't support SO_REUSEPORT\"", ")", "sockets", "=", "[", "]", "if", "address", "==", "\"\"", ":", "address", "=", "None", "if", "not", "socket", ".", "has_ipv6", "and", "family", "==", "socket", ".", "AF_UNSPEC", ":", "# Python can be compiled with --disable-ipv6, which causes", "# operations on AF_INET6 sockets to fail, but does not", "# automatically exclude those results from getaddrinfo", "# results.", "# http://bugs.python.org/issue16208", "family", "=", "socket", ".", "AF_INET", "if", "flags", "is", "None", ":", "flags", "=", "socket", ".", "AI_PASSIVE", "bound_port", "=", "None", "unique_addresses", "=", "set", "(", ")", "# type: set", "for", "res", "in", "sorted", "(", "socket", ".", "getaddrinfo", "(", "address", ",", "port", ",", "family", ",", "socket", ".", "SOCK_STREAM", ",", "0", ",", "flags", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ",", ")", ":", "if", "res", "in", "unique_addresses", ":", "continue", "unique_addresses", ".", "add", "(", "res", ")", "af", ",", "socktype", ",", "proto", ",", "canonname", ",", "sockaddr", "=", "res", "if", "(", "sys", ".", "platform", "==", "\"darwin\"", "and", "address", "==", "\"localhost\"", "and", "af", "==", "socket", ".", "AF_INET6", "and", "sockaddr", "[", "3", "]", "!=", "0", ")", ":", "# Mac OS X includes a link-local address fe80::1%lo0 in the", "# getaddrinfo results for 'localhost'. However, the firewall", "# doesn't understand that this is a local address and will", "# prompt for access (often repeatedly, due to an apparent", "# bug in its ability to remember granting access to an", "# application). Skip these addresses.", "continue", "try", ":", "sock", "=", "socket", ".", "socket", "(", "af", ",", "socktype", ",", "proto", ")", "except", "socket", ".", "error", "as", "e", ":", "if", "errno_from_exception", "(", "e", ")", "==", "errno", ".", "EAFNOSUPPORT", ":", "continue", "raise", "set_close_exec", "(", "sock", ".", "fileno", "(", ")", ")", "if", "os", ".", "name", "!=", "\"nt\"", ":", "try", ":", "sock", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "except", "socket", ".", "error", "as", "e", ":", "if", "errno_from_exception", "(", "e", ")", "!=", "errno", ".", "ENOPROTOOPT", ":", "# Hurd doesn't support SO_REUSEADDR.", "raise", "if", "reuse_port", ":", "sock", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEPORT", ",", "1", ")", "if", "af", "==", "socket", ".", "AF_INET6", ":", "# On linux, ipv6 sockets accept ipv4 too by default,", "# but this makes it impossible to bind to both", "# 0.0.0.0 in ipv4 and :: in ipv6. On other systems,", "# separate sockets *must* be used to listen for both ipv4", "# and ipv6. For consistency, always disable ipv4 on our", "# ipv6 sockets and use a separate ipv4 socket when needed.", "#", "# Python 2.x on windows doesn't have IPPROTO_IPV6.", "if", "hasattr", "(", "socket", ",", "\"IPPROTO_IPV6\"", ")", ":", "sock", ".", "setsockopt", "(", "socket", ".", "IPPROTO_IPV6", ",", "socket", ".", "IPV6_V6ONLY", ",", "1", ")", "# automatic port allocation with port=None", "# should bind on the same port on IPv4 and IPv6", "host", ",", "requested_port", "=", "sockaddr", "[", ":", "2", "]", "if", "requested_port", "==", "0", "and", "bound_port", "is", "not", "None", ":", "sockaddr", "=", "tuple", "(", "[", "host", ",", "bound_port", "]", "+", "list", "(", "sockaddr", "[", "2", ":", "]", ")", ")", "sock", ".", "setblocking", "(", "False", ")", "sock", ".", "bind", "(", "sockaddr", ")", "bound_port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]", "sock", ".", "listen", "(", "backlog", ")", "sockets", ".", "append", "(", "sock", ")", "return", "sockets" ]
Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket in the list. If your platform doesn't support this option ValueError will be raised.
[ "Creates", "listening", "sockets", "bound", "to", "the", "given", "port", "and", "address", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L68-L178
train
tornadoweb/tornado
tornado/netutil.py
add_accept_handler
def add_accept_handler( sock: socket.socket, callback: Callable[[socket.socket, Any], None] ) -> Callable[[], None]: """Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. A callable is returned which, when called, will remove the `.IOLoop` event handler and stop processing further incoming connections. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.0 A callable is returned (``None`` was returned before). """ io_loop = IOLoop.current() removed = [False] def accept_handler(fd: socket.socket, events: int) -> None: # More connections may come in while we're handling callbacks; # to prevent starvation of other tasks we must limit the number # of connections we accept at a time. Ideally we would accept # up to the number of connections that were waiting when we # entered this method, but this information is not available # (and rearranging this method to call accept() as many times # as possible before running any callbacks would have adverse # effects on load balancing in multiprocess configurations). # Instead, we use the (default) listen backlog as a rough # heuristic for the number of connections we can reasonably # accept at once. for i in range(_DEFAULT_BACKLOG): if removed[0]: # The socket was probably closed return try: connection, address = sock.accept() except socket.error as e: # _ERRNO_WOULDBLOCK indicate we have accepted every # connection that is available. if errno_from_exception(e) in _ERRNO_WOULDBLOCK: return # ECONNABORTED indicates that there was a connection # but it was closed while still in the accept queue. # (observed on FreeBSD). if errno_from_exception(e) == errno.ECONNABORTED: continue raise set_close_exec(connection.fileno()) callback(connection, address) def remove_handler() -> None: io_loop.remove_handler(sock) removed[0] = True io_loop.add_handler(sock, accept_handler, IOLoop.READ) return remove_handler
python
def add_accept_handler( sock: socket.socket, callback: Callable[[socket.socket, Any], None] ) -> Callable[[], None]: """Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. A callable is returned which, when called, will remove the `.IOLoop` event handler and stop processing further incoming connections. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.0 A callable is returned (``None`` was returned before). """ io_loop = IOLoop.current() removed = [False] def accept_handler(fd: socket.socket, events: int) -> None: # More connections may come in while we're handling callbacks; # to prevent starvation of other tasks we must limit the number # of connections we accept at a time. Ideally we would accept # up to the number of connections that were waiting when we # entered this method, but this information is not available # (and rearranging this method to call accept() as many times # as possible before running any callbacks would have adverse # effects on load balancing in multiprocess configurations). # Instead, we use the (default) listen backlog as a rough # heuristic for the number of connections we can reasonably # accept at once. for i in range(_DEFAULT_BACKLOG): if removed[0]: # The socket was probably closed return try: connection, address = sock.accept() except socket.error as e: # _ERRNO_WOULDBLOCK indicate we have accepted every # connection that is available. if errno_from_exception(e) in _ERRNO_WOULDBLOCK: return # ECONNABORTED indicates that there was a connection # but it was closed while still in the accept queue. # (observed on FreeBSD). if errno_from_exception(e) == errno.ECONNABORTED: continue raise set_close_exec(connection.fileno()) callback(connection, address) def remove_handler() -> None: io_loop.remove_handler(sock) removed[0] = True io_loop.add_handler(sock, accept_handler, IOLoop.READ) return remove_handler
[ "def", "add_accept_handler", "(", "sock", ":", "socket", ".", "socket", ",", "callback", ":", "Callable", "[", "[", "socket", ".", "socket", ",", "Any", "]", ",", "None", "]", ")", "->", "Callable", "[", "[", "]", ",", "None", "]", ":", "io_loop", "=", "IOLoop", ".", "current", "(", ")", "removed", "=", "[", "False", "]", "def", "accept_handler", "(", "fd", ":", "socket", ".", "socket", ",", "events", ":", "int", ")", "->", "None", ":", "# More connections may come in while we're handling callbacks;", "# to prevent starvation of other tasks we must limit the number", "# of connections we accept at a time. Ideally we would accept", "# up to the number of connections that were waiting when we", "# entered this method, but this information is not available", "# (and rearranging this method to call accept() as many times", "# as possible before running any callbacks would have adverse", "# effects on load balancing in multiprocess configurations).", "# Instead, we use the (default) listen backlog as a rough", "# heuristic for the number of connections we can reasonably", "# accept at once.", "for", "i", "in", "range", "(", "_DEFAULT_BACKLOG", ")", ":", "if", "removed", "[", "0", "]", ":", "# The socket was probably closed", "return", "try", ":", "connection", ",", "address", "=", "sock", ".", "accept", "(", ")", "except", "socket", ".", "error", "as", "e", ":", "# _ERRNO_WOULDBLOCK indicate we have accepted every", "# connection that is available.", "if", "errno_from_exception", "(", "e", ")", "in", "_ERRNO_WOULDBLOCK", ":", "return", "# ECONNABORTED indicates that there was a connection", "# but it was closed while still in the accept queue.", "# (observed on FreeBSD).", "if", "errno_from_exception", "(", "e", ")", "==", "errno", ".", "ECONNABORTED", ":", "continue", "raise", "set_close_exec", "(", "connection", ".", "fileno", "(", ")", ")", "callback", "(", "connection", ",", "address", ")", "def", "remove_handler", "(", ")", "->", "None", ":", "io_loop", ".", "remove_handler", "(", "sock", ")", "removed", "[", "0", "]", "=", "True", "io_loop", ".", "add_handler", "(", "sock", ",", "accept_handler", ",", "IOLoop", ".", "READ", ")", "return", "remove_handler" ]
Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. A callable is returned which, when called, will remove the `.IOLoop` event handler and stop processing further incoming connections. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. .. versionchanged:: 5.0 A callable is returned (``None`` was returned before).
[ "Adds", "an", ".", "IOLoop", "event", "handler", "to", "accept", "new", "connections", "on", "sock", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L220-L280
train
tornadoweb/tornado
tornado/netutil.py
is_valid_ip
def is_valid_ip(ip: str) -> bool: """Returns ``True`` if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ if not ip or "\x00" in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo( ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST ) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True
python
def is_valid_ip(ip: str) -> bool: """Returns ``True`` if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ if not ip or "\x00" in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo( ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST ) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True
[ "def", "is_valid_ip", "(", "ip", ":", "str", ")", "->", "bool", ":", "if", "not", "ip", "or", "\"\\x00\"", "in", "ip", ":", "# getaddrinfo resolves empty strings to localhost, and truncates", "# on zero bytes.", "return", "False", "try", ":", "res", "=", "socket", ".", "getaddrinfo", "(", "ip", ",", "0", ",", "socket", ".", "AF_UNSPEC", ",", "socket", ".", "SOCK_STREAM", ",", "0", ",", "socket", ".", "AI_NUMERICHOST", ")", "return", "bool", "(", "res", ")", "except", "socket", ".", "gaierror", "as", "e", ":", "if", "e", ".", "args", "[", "0", "]", "==", "socket", ".", "EAI_NONAME", ":", "return", "False", "raise", "return", "True" ]
Returns ``True`` if the given string is a well-formed IP address. Supports IPv4 and IPv6.
[ "Returns", "True", "if", "the", "given", "string", "is", "a", "well", "-", "formed", "IP", "address", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L283-L301
train
tornadoweb/tornado
tornado/netutil.py
ssl_options_to_context
def ssl_options_to_context( ssl_options: Union[Dict[str, Any], ssl.SSLContext] ) -> ssl.SSLContext: """Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN. """ if isinstance(ssl_options, ssl.SSLContext): return ssl_options assert isinstance(ssl_options, dict) assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options # Can't use create_default_context since this interface doesn't # tell us client vs server. context = ssl.SSLContext(ssl_options.get("ssl_version", ssl.PROTOCOL_SSLv23)) if "certfile" in ssl_options: context.load_cert_chain( ssl_options["certfile"], ssl_options.get("keyfile", None) ) if "cert_reqs" in ssl_options: context.verify_mode = ssl_options["cert_reqs"] if "ca_certs" in ssl_options: context.load_verify_locations(ssl_options["ca_certs"]) if "ciphers" in ssl_options: context.set_ciphers(ssl_options["ciphers"]) if hasattr(ssl, "OP_NO_COMPRESSION"): # Disable TLS compression to avoid CRIME and related attacks. # This constant depends on openssl version 1.0. # TODO: Do we need to do this ourselves or can we trust # the defaults? context.options |= ssl.OP_NO_COMPRESSION return context
python
def ssl_options_to_context( ssl_options: Union[Dict[str, Any], ssl.SSLContext] ) -> ssl.SSLContext: """Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN. """ if isinstance(ssl_options, ssl.SSLContext): return ssl_options assert isinstance(ssl_options, dict) assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options # Can't use create_default_context since this interface doesn't # tell us client vs server. context = ssl.SSLContext(ssl_options.get("ssl_version", ssl.PROTOCOL_SSLv23)) if "certfile" in ssl_options: context.load_cert_chain( ssl_options["certfile"], ssl_options.get("keyfile", None) ) if "cert_reqs" in ssl_options: context.verify_mode = ssl_options["cert_reqs"] if "ca_certs" in ssl_options: context.load_verify_locations(ssl_options["ca_certs"]) if "ciphers" in ssl_options: context.set_ciphers(ssl_options["ciphers"]) if hasattr(ssl, "OP_NO_COMPRESSION"): # Disable TLS compression to avoid CRIME and related attacks. # This constant depends on openssl version 1.0. # TODO: Do we need to do this ourselves or can we trust # the defaults? context.options |= ssl.OP_NO_COMPRESSION return context
[ "def", "ssl_options_to_context", "(", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "ssl", ".", "SSLContext", "]", ")", "->", "ssl", ".", "SSLContext", ":", "if", "isinstance", "(", "ssl_options", ",", "ssl", ".", "SSLContext", ")", ":", "return", "ssl_options", "assert", "isinstance", "(", "ssl_options", ",", "dict", ")", "assert", "all", "(", "k", "in", "_SSL_CONTEXT_KEYWORDS", "for", "k", "in", "ssl_options", ")", ",", "ssl_options", "# Can't use create_default_context since this interface doesn't", "# tell us client vs server.", "context", "=", "ssl", ".", "SSLContext", "(", "ssl_options", ".", "get", "(", "\"ssl_version\"", ",", "ssl", ".", "PROTOCOL_SSLv23", ")", ")", "if", "\"certfile\"", "in", "ssl_options", ":", "context", ".", "load_cert_chain", "(", "ssl_options", "[", "\"certfile\"", "]", ",", "ssl_options", ".", "get", "(", "\"keyfile\"", ",", "None", ")", ")", "if", "\"cert_reqs\"", "in", "ssl_options", ":", "context", ".", "verify_mode", "=", "ssl_options", "[", "\"cert_reqs\"", "]", "if", "\"ca_certs\"", "in", "ssl_options", ":", "context", ".", "load_verify_locations", "(", "ssl_options", "[", "\"ca_certs\"", "]", ")", "if", "\"ciphers\"", "in", "ssl_options", ":", "context", ".", "set_ciphers", "(", "ssl_options", "[", "\"ciphers\"", "]", ")", "if", "hasattr", "(", "ssl", ",", "\"OP_NO_COMPRESSION\"", ")", ":", "# Disable TLS compression to avoid CRIME and related attacks.", "# This constant depends on openssl version 1.0.", "# TODO: Do we need to do this ourselves or can we trust", "# the defaults?", "context", ".", "options", "|=", "ssl", ".", "OP_NO_COMPRESSION", "return", "context" ]
Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 2.7.9+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN.
[ "Try", "to", "convert", "an", "ssl_options", "dictionary", "to", "an", "~ssl", ".", "SSLContext", "object", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L552-L588
train
tornadoweb/tornado
tornado/netutil.py
ssl_wrap_socket
def ssl_wrap_socket( socket: socket.socket, ssl_options: Union[Dict[str, Any], ssl.SSLContext], server_hostname: str = None, **kwargs: Any ) -> ssl.SSLSocket: """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if ssl.HAS_SNI: # In python 3.4, wrap_socket only accepts the server_hostname # argument if HAS_SNI is true. # TODO: add a unittest (python added server-side SNI support in 3.4) # In the meantime it can be manually tested with # python3 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs)
python
def ssl_wrap_socket( socket: socket.socket, ssl_options: Union[Dict[str, Any], ssl.SSLContext], server_hostname: str = None, **kwargs: Any ) -> ssl.SSLSocket: """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if ssl.HAS_SNI: # In python 3.4, wrap_socket only accepts the server_hostname # argument if HAS_SNI is true. # TODO: add a unittest (python added server-side SNI support in 3.4) # In the meantime it can be manually tested with # python3 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs)
[ "def", "ssl_wrap_socket", "(", "socket", ":", "socket", ".", "socket", ",", "ssl_options", ":", "Union", "[", "Dict", "[", "str", ",", "Any", "]", ",", "ssl", ".", "SSLContext", "]", ",", "server_hostname", ":", "str", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "ssl", ".", "SSLSocket", ":", "context", "=", "ssl_options_to_context", "(", "ssl_options", ")", "if", "ssl", ".", "HAS_SNI", ":", "# In python 3.4, wrap_socket only accepts the server_hostname", "# argument if HAS_SNI is true.", "# TODO: add a unittest (python added server-side SNI support in 3.4)", "# In the meantime it can be manually tested with", "# python3 -m tornado.httpclient https://sni.velox.ch", "return", "context", ".", "wrap_socket", "(", "socket", ",", "server_hostname", "=", "server_hostname", ",", "*", "*", "kwargs", ")", "else", ":", "return", "context", ".", "wrap_socket", "(", "socket", ",", "*", "*", "kwargs", ")" ]
Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate).
[ "Returns", "an", "ssl", ".", "SSLSocket", "wrapping", "the", "given", "socket", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/netutil.py#L591-L614
train
tornadoweb/tornado
tornado/concurrent.py
run_on_executor
def run_on_executor(*args: Any, **kwargs: Any) -> Callable: """Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass This decorator should not be confused with the similarly-named `.IOLoop.run_in_executor`. In general, using ``run_in_executor`` when *calling* a blocking method is recommended instead of using this decorator when *defining* a method. If compatibility with older versions of Tornado is required, consider defining an executor and using ``executor.submit()`` at the call site. .. versionchanged:: 4.2 Added keyword arguments to use alternative attributes. .. versionchanged:: 5.0 Always uses the current IOLoop instead of ``self.io_loop``. .. versionchanged:: 5.1 Returns a `.Future` compatible with ``await`` instead of a `concurrent.futures.Future`. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. The decorator itself is discouraged in new code but will not be removed in 6.0. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ # Fully type-checking decorators is tricky, and this one is # discouraged anyway so it doesn't have all the generic magic. def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]: executor = kwargs.get("executor", "executor") @functools.wraps(fn) def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future: async_future = Future() # type: Future conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs) chain_future(conc_future, async_future) return async_future return wrapper if args and kwargs: raise ValueError("cannot combine positional and keyword args") if len(args) == 1: return run_on_executor_decorator(args[0]) elif len(args) != 0: raise ValueError("expected 1 argument, got %d", len(args)) return run_on_executor_decorator
python
def run_on_executor(*args: Any, **kwargs: Any) -> Callable: """Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass This decorator should not be confused with the similarly-named `.IOLoop.run_in_executor`. In general, using ``run_in_executor`` when *calling* a blocking method is recommended instead of using this decorator when *defining* a method. If compatibility with older versions of Tornado is required, consider defining an executor and using ``executor.submit()`` at the call site. .. versionchanged:: 4.2 Added keyword arguments to use alternative attributes. .. versionchanged:: 5.0 Always uses the current IOLoop instead of ``self.io_loop``. .. versionchanged:: 5.1 Returns a `.Future` compatible with ``await`` instead of a `concurrent.futures.Future`. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. The decorator itself is discouraged in new code but will not be removed in 6.0. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ # Fully type-checking decorators is tricky, and this one is # discouraged anyway so it doesn't have all the generic magic. def run_on_executor_decorator(fn: Callable) -> Callable[..., Future]: executor = kwargs.get("executor", "executor") @functools.wraps(fn) def wrapper(self: Any, *args: Any, **kwargs: Any) -> Future: async_future = Future() # type: Future conc_future = getattr(self, executor).submit(fn, self, *args, **kwargs) chain_future(conc_future, async_future) return async_future return wrapper if args and kwargs: raise ValueError("cannot combine positional and keyword args") if len(args) == 1: return run_on_executor_decorator(args[0]) elif len(args) != 0: raise ValueError("expected 1 argument, got %d", len(args)) return run_on_executor_decorator
[ "def", "run_on_executor", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Callable", ":", "# Fully type-checking decorators is tricky, and this one is", "# discouraged anyway so it doesn't have all the generic magic.", "def", "run_on_executor_decorator", "(", "fn", ":", "Callable", ")", "->", "Callable", "[", "...", ",", "Future", "]", ":", "executor", "=", "kwargs", ".", "get", "(", "\"executor\"", ",", "\"executor\"", ")", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "self", ":", "Any", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Future", ":", "async_future", "=", "Future", "(", ")", "# type: Future", "conc_future", "=", "getattr", "(", "self", ",", "executor", ")", ".", "submit", "(", "fn", ",", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "chain_future", "(", "conc_future", ",", "async_future", ")", "return", "async_future", "return", "wrapper", "if", "args", "and", "kwargs", ":", "raise", "ValueError", "(", "\"cannot combine positional and keyword args\"", ")", "if", "len", "(", "args", ")", "==", "1", ":", "return", "run_on_executor_decorator", "(", "args", "[", "0", "]", ")", "elif", "len", "(", "args", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"expected 1 argument, got %d\"", ",", "len", "(", "args", ")", ")", "return", "run_on_executor_decorator" ]
Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass This decorator should not be confused with the similarly-named `.IOLoop.run_in_executor`. In general, using ``run_in_executor`` when *calling* a blocking method is recommended instead of using this decorator when *defining* a method. If compatibility with older versions of Tornado is required, consider defining an executor and using ``executor.submit()`` at the call site. .. versionchanged:: 4.2 Added keyword arguments to use alternative attributes. .. versionchanged:: 5.0 Always uses the current IOLoop instead of ``self.io_loop``. .. versionchanged:: 5.1 Returns a `.Future` compatible with ``await`` instead of a `concurrent.futures.Future`. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. The decorator itself is discouraged in new code but will not be removed in 6.0. .. versionchanged:: 6.0 The ``callback`` argument was removed.
[ "Decorator", "to", "run", "a", "synchronous", "method", "asynchronously", "on", "an", "executor", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L74-L135
train
tornadoweb/tornado
tornado/concurrent.py
chain_future
def chain_future(a: "Future[_T]", b: "Future[_T]") -> None: """Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes. .. versionchanged:: 5.0 Now accepts both Tornado/asyncio `Future` objects and `concurrent.futures.Future`. """ def copy(future: "Future[_T]") -> None: assert future is a if b.done(): return if hasattr(a, "exc_info") and a.exc_info() is not None: # type: ignore future_set_exc_info(b, a.exc_info()) # type: ignore elif a.exception() is not None: b.set_exception(a.exception()) else: b.set_result(a.result()) if isinstance(a, Future): future_add_done_callback(a, copy) else: # concurrent.futures.Future from tornado.ioloop import IOLoop IOLoop.current().add_future(a, copy)
python
def chain_future(a: "Future[_T]", b: "Future[_T]") -> None: """Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes. .. versionchanged:: 5.0 Now accepts both Tornado/asyncio `Future` objects and `concurrent.futures.Future`. """ def copy(future: "Future[_T]") -> None: assert future is a if b.done(): return if hasattr(a, "exc_info") and a.exc_info() is not None: # type: ignore future_set_exc_info(b, a.exc_info()) # type: ignore elif a.exception() is not None: b.set_exception(a.exception()) else: b.set_result(a.result()) if isinstance(a, Future): future_add_done_callback(a, copy) else: # concurrent.futures.Future from tornado.ioloop import IOLoop IOLoop.current().add_future(a, copy)
[ "def", "chain_future", "(", "a", ":", "\"Future[_T]\"", ",", "b", ":", "\"Future[_T]\"", ")", "->", "None", ":", "def", "copy", "(", "future", ":", "\"Future[_T]\"", ")", "->", "None", ":", "assert", "future", "is", "a", "if", "b", ".", "done", "(", ")", ":", "return", "if", "hasattr", "(", "a", ",", "\"exc_info\"", ")", "and", "a", ".", "exc_info", "(", ")", "is", "not", "None", ":", "# type: ignore", "future_set_exc_info", "(", "b", ",", "a", ".", "exc_info", "(", ")", ")", "# type: ignore", "elif", "a", ".", "exception", "(", ")", "is", "not", "None", ":", "b", ".", "set_exception", "(", "a", ".", "exception", "(", ")", ")", "else", ":", "b", ".", "set_result", "(", "a", ".", "result", "(", ")", ")", "if", "isinstance", "(", "a", ",", "Future", ")", ":", "future_add_done_callback", "(", "a", ",", "copy", ")", "else", ":", "# concurrent.futures.Future", "from", "tornado", ".", "ioloop", "import", "IOLoop", "IOLoop", ".", "current", "(", ")", ".", "add_future", "(", "a", ",", "copy", ")" ]
Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes. .. versionchanged:: 5.0 Now accepts both Tornado/asyncio `Future` objects and `concurrent.futures.Future`.
[ "Chain", "two", "futures", "together", "so", "that", "when", "one", "completes", "so", "does", "the", "other", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L141-L171
train
tornadoweb/tornado
tornado/concurrent.py
future_set_exception_unless_cancelled
def future_set_exception_unless_cancelled( future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException ) -> None: """Set the given ``exc`` as the `Future`'s exception. If the Future is already canceled, logs the exception instead. If this logging is not desired, the caller should explicitly check the state of the Future and call ``Future.set_exception`` instead of this wrapper. Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on a cancelled `asyncio.Future`. .. versionadded:: 6.0 """ if not future.cancelled(): future.set_exception(exc) else: app_log.error("Exception after Future was cancelled", exc_info=exc)
python
def future_set_exception_unless_cancelled( future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException ) -> None: """Set the given ``exc`` as the `Future`'s exception. If the Future is already canceled, logs the exception instead. If this logging is not desired, the caller should explicitly check the state of the Future and call ``Future.set_exception`` instead of this wrapper. Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on a cancelled `asyncio.Future`. .. versionadded:: 6.0 """ if not future.cancelled(): future.set_exception(exc) else: app_log.error("Exception after Future was cancelled", exc_info=exc)
[ "def", "future_set_exception_unless_cancelled", "(", "future", ":", "\"Union[futures.Future[_T], Future[_T]]\"", ",", "exc", ":", "BaseException", ")", "->", "None", ":", "if", "not", "future", ".", "cancelled", "(", ")", ":", "future", ".", "set_exception", "(", "exc", ")", "else", ":", "app_log", ".", "error", "(", "\"Exception after Future was cancelled\"", ",", "exc_info", "=", "exc", ")" ]
Set the given ``exc`` as the `Future`'s exception. If the Future is already canceled, logs the exception instead. If this logging is not desired, the caller should explicitly check the state of the Future and call ``Future.set_exception`` instead of this wrapper. Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on a cancelled `asyncio.Future`. .. versionadded:: 6.0
[ "Set", "the", "given", "exc", "as", "the", "Future", "s", "exception", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L188-L207
train
tornadoweb/tornado
tornado/concurrent.py
future_set_exc_info
def future_set_exc_info( future: "Union[futures.Future[_T], Future[_T]]", exc_info: Tuple[ Optional[type], Optional[BaseException], Optional[types.TracebackType] ], ) -> None: """Set the given ``exc_info`` as the `Future`'s exception. Understands both `asyncio.Future` and the extensions in older versions of Tornado to enable better tracebacks on Python 2. .. versionadded:: 5.0 .. versionchanged:: 6.0 If the future is already cancelled, this function is a no-op. (previously ``asyncio.InvalidStateError`` would be raised) """ if exc_info[1] is None: raise Exception("future_set_exc_info called with no exception") future_set_exception_unless_cancelled(future, exc_info[1])
python
def future_set_exc_info( future: "Union[futures.Future[_T], Future[_T]]", exc_info: Tuple[ Optional[type], Optional[BaseException], Optional[types.TracebackType] ], ) -> None: """Set the given ``exc_info`` as the `Future`'s exception. Understands both `asyncio.Future` and the extensions in older versions of Tornado to enable better tracebacks on Python 2. .. versionadded:: 5.0 .. versionchanged:: 6.0 If the future is already cancelled, this function is a no-op. (previously ``asyncio.InvalidStateError`` would be raised) """ if exc_info[1] is None: raise Exception("future_set_exc_info called with no exception") future_set_exception_unless_cancelled(future, exc_info[1])
[ "def", "future_set_exc_info", "(", "future", ":", "\"Union[futures.Future[_T], Future[_T]]\"", ",", "exc_info", ":", "Tuple", "[", "Optional", "[", "type", "]", ",", "Optional", "[", "BaseException", "]", ",", "Optional", "[", "types", ".", "TracebackType", "]", "]", ",", ")", "->", "None", ":", "if", "exc_info", "[", "1", "]", "is", "None", ":", "raise", "Exception", "(", "\"future_set_exc_info called with no exception\"", ")", "future_set_exception_unless_cancelled", "(", "future", ",", "exc_info", "[", "1", "]", ")" ]
Set the given ``exc_info`` as the `Future`'s exception. Understands both `asyncio.Future` and the extensions in older versions of Tornado to enable better tracebacks on Python 2. .. versionadded:: 5.0 .. versionchanged:: 6.0 If the future is already cancelled, this function is a no-op. (previously ``asyncio.InvalidStateError`` would be raised)
[ "Set", "the", "given", "exc_info", "as", "the", "Future", "s", "exception", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L210-L231
train
tornadoweb/tornado
tornado/concurrent.py
future_add_done_callback
def future_add_done_callback( # noqa: F811 future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None] ) -> None: """Arrange to call ``callback`` when ``future`` is complete. ``callback`` is invoked with one argument, the ``future``. If ``future`` is already done, ``callback`` is invoked immediately. This may differ from the behavior of ``Future.add_done_callback``, which makes no such guarantee. .. versionadded:: 5.0 """ if future.done(): callback(future) else: future.add_done_callback(callback)
python
def future_add_done_callback( # noqa: F811 future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None] ) -> None: """Arrange to call ``callback`` when ``future`` is complete. ``callback`` is invoked with one argument, the ``future``. If ``future`` is already done, ``callback`` is invoked immediately. This may differ from the behavior of ``Future.add_done_callback``, which makes no such guarantee. .. versionadded:: 5.0 """ if future.done(): callback(future) else: future.add_done_callback(callback)
[ "def", "future_add_done_callback", "(", "# noqa: F811", "future", ":", "\"Union[futures.Future[_T], Future[_T]]\"", ",", "callback", ":", "Callable", "[", "...", ",", "None", "]", ")", "->", "None", ":", "if", "future", ".", "done", "(", ")", ":", "callback", "(", "future", ")", "else", ":", "future", ".", "add_done_callback", "(", "callback", ")" ]
Arrange to call ``callback`` when ``future`` is complete. ``callback`` is invoked with one argument, the ``future``. If ``future`` is already done, ``callback`` is invoked immediately. This may differ from the behavior of ``Future.add_done_callback``, which makes no such guarantee. .. versionadded:: 5.0
[ "Arrange", "to", "call", "callback", "when", "future", "is", "complete", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/concurrent.py#L248-L264
train
tornadoweb/tornado
tornado/template.py
filter_whitespace
def filter_whitespace(mode: str, text: str) -> str: """Transform whitespace in ``text`` according to ``mode``. Available modes are: * ``all``: Return all whitespace unmodified. * ``single``: Collapse consecutive whitespace with a single whitespace character, preserving newlines. * ``oneline``: Collapse all runs of whitespace into a single space character, removing all newlines in the process. .. versionadded:: 4.3 """ if mode == "all": return text elif mode == "single": text = re.sub(r"([\t ]+)", " ", text) text = re.sub(r"(\s*\n\s*)", "\n", text) return text elif mode == "oneline": return re.sub(r"(\s+)", " ", text) else: raise Exception("invalid whitespace mode %s" % mode)
python
def filter_whitespace(mode: str, text: str) -> str: """Transform whitespace in ``text`` according to ``mode``. Available modes are: * ``all``: Return all whitespace unmodified. * ``single``: Collapse consecutive whitespace with a single whitespace character, preserving newlines. * ``oneline``: Collapse all runs of whitespace into a single space character, removing all newlines in the process. .. versionadded:: 4.3 """ if mode == "all": return text elif mode == "single": text = re.sub(r"([\t ]+)", " ", text) text = re.sub(r"(\s*\n\s*)", "\n", text) return text elif mode == "oneline": return re.sub(r"(\s+)", " ", text) else: raise Exception("invalid whitespace mode %s" % mode)
[ "def", "filter_whitespace", "(", "mode", ":", "str", ",", "text", ":", "str", ")", "->", "str", ":", "if", "mode", "==", "\"all\"", ":", "return", "text", "elif", "mode", "==", "\"single\"", ":", "text", "=", "re", ".", "sub", "(", "r\"([\\t ]+)\"", ",", "\" \"", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r\"(\\s*\\n\\s*)\"", ",", "\"\\n\"", ",", "text", ")", "return", "text", "elif", "mode", "==", "\"oneline\"", ":", "return", "re", ".", "sub", "(", "r\"(\\s+)\"", ",", "\" \"", ",", "text", ")", "else", ":", "raise", "Exception", "(", "\"invalid whitespace mode %s\"", "%", "mode", ")" ]
Transform whitespace in ``text`` according to ``mode``. Available modes are: * ``all``: Return all whitespace unmodified. * ``single``: Collapse consecutive whitespace with a single whitespace character, preserving newlines. * ``oneline``: Collapse all runs of whitespace into a single space character, removing all newlines in the process. .. versionadded:: 4.3
[ "Transform", "whitespace", "in", "text", "according", "to", "mode", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L226-L248
train
tornadoweb/tornado
tornado/template.py
Template.generate
def generate(self, **kwargs: Any) -> bytes: """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_tt_utf8": escape.utf8, # for internal use "_tt_string_types": (unicode_type, bytes), # __name__ and __loader__ allow the traceback mechanism to find # the generated source code. "__name__": self.name.replace(".", "_"), "__loader__": ObjectDict(get_source=lambda name: self.code), } namespace.update(self.namespace) namespace.update(kwargs) exec_in(self.compiled, namespace) execute = typing.cast(Callable[[], bytes], namespace["_tt_execute"]) # Clear the traceback module's cache of source data now that # we've generated a new template (mainly for this module's # unittests, where different tests reuse the same name). linecache.clearcache() return execute()
python
def generate(self, **kwargs: Any) -> bytes: """Generate this template with the given arguments.""" namespace = { "escape": escape.xhtml_escape, "xhtml_escape": escape.xhtml_escape, "url_escape": escape.url_escape, "json_encode": escape.json_encode, "squeeze": escape.squeeze, "linkify": escape.linkify, "datetime": datetime, "_tt_utf8": escape.utf8, # for internal use "_tt_string_types": (unicode_type, bytes), # __name__ and __loader__ allow the traceback mechanism to find # the generated source code. "__name__": self.name.replace(".", "_"), "__loader__": ObjectDict(get_source=lambda name: self.code), } namespace.update(self.namespace) namespace.update(kwargs) exec_in(self.compiled, namespace) execute = typing.cast(Callable[[], bytes], namespace["_tt_execute"]) # Clear the traceback module's cache of source data now that # we've generated a new template (mainly for this module's # unittests, where different tests reuse the same name). linecache.clearcache() return execute()
[ "def", "generate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bytes", ":", "namespace", "=", "{", "\"escape\"", ":", "escape", ".", "xhtml_escape", ",", "\"xhtml_escape\"", ":", "escape", ".", "xhtml_escape", ",", "\"url_escape\"", ":", "escape", ".", "url_escape", ",", "\"json_encode\"", ":", "escape", ".", "json_encode", ",", "\"squeeze\"", ":", "escape", ".", "squeeze", ",", "\"linkify\"", ":", "escape", ".", "linkify", ",", "\"datetime\"", ":", "datetime", ",", "\"_tt_utf8\"", ":", "escape", ".", "utf8", ",", "# for internal use", "\"_tt_string_types\"", ":", "(", "unicode_type", ",", "bytes", ")", ",", "# __name__ and __loader__ allow the traceback mechanism to find", "# the generated source code.", "\"__name__\"", ":", "self", ".", "name", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", ",", "\"__loader__\"", ":", "ObjectDict", "(", "get_source", "=", "lambda", "name", ":", "self", ".", "code", ")", ",", "}", "namespace", ".", "update", "(", "self", ".", "namespace", ")", "namespace", ".", "update", "(", "kwargs", ")", "exec_in", "(", "self", ".", "compiled", ",", "namespace", ")", "execute", "=", "typing", ".", "cast", "(", "Callable", "[", "[", "]", ",", "bytes", "]", ",", "namespace", "[", "\"_tt_execute\"", "]", ")", "# Clear the traceback module's cache of source data now that", "# we've generated a new template (mainly for this module's", "# unittests, where different tests reuse the same name).", "linecache", ".", "clearcache", "(", ")", "return", "execute", "(", ")" ]
Generate this template with the given arguments.
[ "Generate", "this", "template", "with", "the", "given", "arguments", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L336-L361
train
tornadoweb/tornado
tornado/template.py
BaseLoader.load
def load(self, name: str, parent_path: str = None) -> Template: """Loads a template.""" name = self.resolve_path(name, parent_path=parent_path) with self.lock: if name not in self.templates: self.templates[name] = self._create_template(name) return self.templates[name]
python
def load(self, name: str, parent_path: str = None) -> Template: """Loads a template.""" name = self.resolve_path(name, parent_path=parent_path) with self.lock: if name not in self.templates: self.templates[name] = self._create_template(name) return self.templates[name]
[ "def", "load", "(", "self", ",", "name", ":", "str", ",", "parent_path", ":", "str", "=", "None", ")", "->", "Template", ":", "name", "=", "self", ".", "resolve_path", "(", "name", ",", "parent_path", "=", "parent_path", ")", "with", "self", ".", "lock", ":", "if", "name", "not", "in", "self", ".", "templates", ":", "self", ".", "templates", "[", "name", "]", "=", "self", ".", "_create_template", "(", "name", ")", "return", "self", ".", "templates", "[", "name", "]" ]
Loads a template.
[ "Loads", "a", "template", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/template.py#L440-L446
train
tornadoweb/tornado
tornado/gen.py
coroutine
def coroutine( func: Callable[..., "Generator[Any, Any, _T]"] ) -> Callable[..., "Future[_T]"]: """Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may also "return" by raising the special exception `Return(value) <Return>`. Functions with this decorator return a `.Future`. .. warning:: When exceptions occur inside a coroutine, the exception information will be stored in the `.Future` object. You must examine the result of the `.Future` object, or the exception may go unnoticed by your code. This means yielding the function if called from another coroutine, using something like `.IOLoop.run_sync` for top-level calls, or passing the `.Future` to `.IOLoop.add_future`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ @functools.wraps(func) def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Future[_T] # This function is type-annotated with a comment to work around # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in future = _create_future() try: result = func(*args, **kwargs) except (Return, StopIteration) as e: result = _value_from_stopiteration(e) except Exception: future_set_exc_info(future, sys.exc_info()) try: return future finally: # Avoid circular references future = None # type: ignore else: if isinstance(result, Generator): # Inline the first iteration of Runner.run. This lets us # avoid the cost of creating a Runner when the coroutine # never actually yields, which in turn allows us to # use "optional" coroutines in critical path code without # performance penalty for the synchronous case. try: yielded = next(result) except (StopIteration, Return) as e: future_set_result_unless_cancelled( future, _value_from_stopiteration(e) ) except Exception: future_set_exc_info(future, sys.exc_info()) else: # Provide strong references to Runner objects as long # as their result future objects also have strong # references (typically from the parent coroutine's # Runner). This keeps the coroutine's Runner alive. # We do this by exploiting the public API # add_done_callback() instead of putting a private # attribute on the Future. # (Github issues #1769, #2229). runner = Runner(result, future, yielded) future.add_done_callback(lambda _: runner) yielded = None try: return future finally: # Subtle memory optimization: if next() raised an exception, # the future's exc_info contains a traceback which # includes this stack frame. This creates a cycle, # which will be collected at the next full GC but has # been shown to greatly increase memory usage of # benchmarks (relative to the refcount-based scheme # used in the absence of cycles). We can avoid the # cycle by clearing the local variable after we return it. future = None # type: ignore future_set_result_unless_cancelled(future, result) return future wrapper.__wrapped__ = func # type: ignore wrapper.__tornado_coroutine__ = True # type: ignore return wrapper
python
def coroutine( func: Callable[..., "Generator[Any, Any, _T]"] ) -> Callable[..., "Future[_T]"]: """Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may also "return" by raising the special exception `Return(value) <Return>`. Functions with this decorator return a `.Future`. .. warning:: When exceptions occur inside a coroutine, the exception information will be stored in the `.Future` object. You must examine the result of the `.Future` object, or the exception may go unnoticed by your code. This means yielding the function if called from another coroutine, using something like `.IOLoop.run_sync` for top-level calls, or passing the `.Future` to `.IOLoop.add_future`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ @functools.wraps(func) def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Future[_T] # This function is type-annotated with a comment to work around # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in future = _create_future() try: result = func(*args, **kwargs) except (Return, StopIteration) as e: result = _value_from_stopiteration(e) except Exception: future_set_exc_info(future, sys.exc_info()) try: return future finally: # Avoid circular references future = None # type: ignore else: if isinstance(result, Generator): # Inline the first iteration of Runner.run. This lets us # avoid the cost of creating a Runner when the coroutine # never actually yields, which in turn allows us to # use "optional" coroutines in critical path code without # performance penalty for the synchronous case. try: yielded = next(result) except (StopIteration, Return) as e: future_set_result_unless_cancelled( future, _value_from_stopiteration(e) ) except Exception: future_set_exc_info(future, sys.exc_info()) else: # Provide strong references to Runner objects as long # as their result future objects also have strong # references (typically from the parent coroutine's # Runner). This keeps the coroutine's Runner alive. # We do this by exploiting the public API # add_done_callback() instead of putting a private # attribute on the Future. # (Github issues #1769, #2229). runner = Runner(result, future, yielded) future.add_done_callback(lambda _: runner) yielded = None try: return future finally: # Subtle memory optimization: if next() raised an exception, # the future's exc_info contains a traceback which # includes this stack frame. This creates a cycle, # which will be collected at the next full GC but has # been shown to greatly increase memory usage of # benchmarks (relative to the refcount-based scheme # used in the absence of cycles). We can avoid the # cycle by clearing the local variable after we return it. future = None # type: ignore future_set_result_unless_cancelled(future, result) return future wrapper.__wrapped__ = func # type: ignore wrapper.__tornado_coroutine__ = True # type: ignore return wrapper
[ "def", "coroutine", "(", "func", ":", "Callable", "[", "...", ",", "\"Generator[Any, Any, _T]\"", "]", ")", "->", "Callable", "[", "...", ",", "\"Future[_T]\"", "]", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (*Any, **Any) -> Future[_T]", "# This function is type-annotated with a comment to work around", "# https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in", "future", "=", "_create_future", "(", ")", "try", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "Return", ",", "StopIteration", ")", "as", "e", ":", "result", "=", "_value_from_stopiteration", "(", "e", ")", "except", "Exception", ":", "future_set_exc_info", "(", "future", ",", "sys", ".", "exc_info", "(", ")", ")", "try", ":", "return", "future", "finally", ":", "# Avoid circular references", "future", "=", "None", "# type: ignore", "else", ":", "if", "isinstance", "(", "result", ",", "Generator", ")", ":", "# Inline the first iteration of Runner.run. This lets us", "# avoid the cost of creating a Runner when the coroutine", "# never actually yields, which in turn allows us to", "# use \"optional\" coroutines in critical path code without", "# performance penalty for the synchronous case.", "try", ":", "yielded", "=", "next", "(", "result", ")", "except", "(", "StopIteration", ",", "Return", ")", "as", "e", ":", "future_set_result_unless_cancelled", "(", "future", ",", "_value_from_stopiteration", "(", "e", ")", ")", "except", "Exception", ":", "future_set_exc_info", "(", "future", ",", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "# Provide strong references to Runner objects as long", "# as their result future objects also have strong", "# references (typically from the parent coroutine's", "# Runner). This keeps the coroutine's Runner alive.", "# We do this by exploiting the public API", "# add_done_callback() instead of putting a private", "# attribute on the Future.", "# (Github issues #1769, #2229).", "runner", "=", "Runner", "(", "result", ",", "future", ",", "yielded", ")", "future", ".", "add_done_callback", "(", "lambda", "_", ":", "runner", ")", "yielded", "=", "None", "try", ":", "return", "future", "finally", ":", "# Subtle memory optimization: if next() raised an exception,", "# the future's exc_info contains a traceback which", "# includes this stack frame. This creates a cycle,", "# which will be collected at the next full GC but has", "# been shown to greatly increase memory usage of", "# benchmarks (relative to the refcount-based scheme", "# used in the absence of cycles). We can avoid the", "# cycle by clearing the local variable after we return it.", "future", "=", "None", "# type: ignore", "future_set_result_unless_cancelled", "(", "future", ",", "result", ")", "return", "future", "wrapper", ".", "__wrapped__", "=", "func", "# type: ignore", "wrapper", ".", "__tornado_coroutine__", "=", "True", "# type: ignore", "return", "wrapper" ]
Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may also "return" by raising the special exception `Return(value) <Return>`. Functions with this decorator return a `.Future`. .. warning:: When exceptions occur inside a coroutine, the exception information will be stored in the `.Future` object. You must examine the result of the `.Future` object, or the exception may go unnoticed by your code. This means yielding the function if called from another coroutine, using something like `.IOLoop.run_sync` for top-level calls, or passing the `.Future` to `.IOLoop.add_future`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead.
[ "Decorator", "for", "asynchronous", "generators", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L156-L245
train
tornadoweb/tornado
tornado/gen.py
multi
def multi( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys. That is, ``results = yield multi(list_of_futures)`` is equivalent to:: results = [] for future in list_of_futures: results.append(yield future) If any children raise exceptions, ``multi()`` will raise the first one. All others will be logged, unless they are of types contained in the ``quiet_exceptions`` argument. In a ``yield``-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary in ``await``-based coroutines, or to pass the ``quiet_exceptions`` argument. This function is available under the names ``multi()`` and ``Multi()`` for historical reasons. Cancelling a `.Future` returned by ``multi()`` does not cancel its children. `asyncio.gather` is similar to ``multi()``, but it does cancel its children. .. versionchanged:: 4.2 If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. versionchanged:: 4.3 Replaced the class ``Multi`` and the function ``multi_future`` with a unified function ``multi``. Added support for yieldables other than ``YieldPoint`` and `.Future`. """ return multi_future(children, quiet_exceptions=quiet_exceptions)
python
def multi( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys. That is, ``results = yield multi(list_of_futures)`` is equivalent to:: results = [] for future in list_of_futures: results.append(yield future) If any children raise exceptions, ``multi()`` will raise the first one. All others will be logged, unless they are of types contained in the ``quiet_exceptions`` argument. In a ``yield``-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary in ``await``-based coroutines, or to pass the ``quiet_exceptions`` argument. This function is available under the names ``multi()`` and ``Multi()`` for historical reasons. Cancelling a `.Future` returned by ``multi()`` does not cancel its children. `asyncio.gather` is similar to ``multi()``, but it does cancel its children. .. versionchanged:: 4.2 If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. versionchanged:: 4.3 Replaced the class ``Multi`` and the function ``multi_future`` with a unified function ``multi``. Added support for yieldables other than ``YieldPoint`` and `.Future`. """ return multi_future(children, quiet_exceptions=quiet_exceptions)
[ "def", "multi", "(", "children", ":", "Union", "[", "List", "[", "_Yieldable", "]", ",", "Dict", "[", "Any", ",", "_Yieldable", "]", "]", ",", "quiet_exceptions", ":", "\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"", "=", "(", ")", ",", ")", "->", "\"Union[Future[List], Future[Dict]]\"", ":", "return", "multi_future", "(", "children", ",", "quiet_exceptions", "=", "quiet_exceptions", ")" ]
Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys. That is, ``results = yield multi(list_of_futures)`` is equivalent to:: results = [] for future in list_of_futures: results.append(yield future) If any children raise exceptions, ``multi()`` will raise the first one. All others will be logged, unless they are of types contained in the ``quiet_exceptions`` argument. In a ``yield``-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary in ``await``-based coroutines, or to pass the ``quiet_exceptions`` argument. This function is available under the names ``multi()`` and ``Multi()`` for historical reasons. Cancelling a `.Future` returned by ``multi()`` does not cancel its children. `asyncio.gather` is similar to ``multi()``, but it does cancel its children. .. versionchanged:: 4.2 If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. versionchanged:: 4.3 Replaced the class ``Multi`` and the function ``multi_future`` with a unified function ``multi``. Added support for yieldables other than ``YieldPoint`` and `.Future`.
[ "Runs", "multiple", "asynchronous", "operations", "in", "parallel", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L409-L457
train
tornadoweb/tornado
tornado/gen.py
multi_future
def multi_future( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Wait for multiple asynchronous futures in parallel. Since Tornado 6.0, this function is exactly the same as `multi`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. deprecated:: 4.3 Use `multi` instead. """ if isinstance(children, dict): keys = list(children.keys()) # type: Optional[List] children_seq = children.values() # type: Iterable else: keys = None children_seq = children children_futs = list(map(convert_yielded, children_seq)) assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs) unfinished_children = set(children_futs) future = _create_future() if not children_futs: future_set_result_unless_cancelled(future, {} if keys is not None else []) def callback(fut: Future) -> None: unfinished_children.remove(fut) if not unfinished_children: result_list = [] for f in children_futs: try: result_list.append(f.result()) except Exception as e: if future.done(): if not isinstance(e, quiet_exceptions): app_log.error( "Multiple exceptions in yield list", exc_info=True ) else: future_set_exc_info(future, sys.exc_info()) if not future.done(): if keys is not None: future_set_result_unless_cancelled( future, dict(zip(keys, result_list)) ) else: future_set_result_unless_cancelled(future, result_list) listening = set() # type: Set[Future] for f in children_futs: if f not in listening: listening.add(f) future_add_done_callback(f, callback) return future
python
def multi_future( children: Union[List[_Yieldable], Dict[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Wait for multiple asynchronous futures in parallel. Since Tornado 6.0, this function is exactly the same as `multi`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. deprecated:: 4.3 Use `multi` instead. """ if isinstance(children, dict): keys = list(children.keys()) # type: Optional[List] children_seq = children.values() # type: Iterable else: keys = None children_seq = children children_futs = list(map(convert_yielded, children_seq)) assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs) unfinished_children = set(children_futs) future = _create_future() if not children_futs: future_set_result_unless_cancelled(future, {} if keys is not None else []) def callback(fut: Future) -> None: unfinished_children.remove(fut) if not unfinished_children: result_list = [] for f in children_futs: try: result_list.append(f.result()) except Exception as e: if future.done(): if not isinstance(e, quiet_exceptions): app_log.error( "Multiple exceptions in yield list", exc_info=True ) else: future_set_exc_info(future, sys.exc_info()) if not future.done(): if keys is not None: future_set_result_unless_cancelled( future, dict(zip(keys, result_list)) ) else: future_set_result_unless_cancelled(future, result_list) listening = set() # type: Set[Future] for f in children_futs: if f not in listening: listening.add(f) future_add_done_callback(f, callback) return future
[ "def", "multi_future", "(", "children", ":", "Union", "[", "List", "[", "_Yieldable", "]", ",", "Dict", "[", "Any", ",", "_Yieldable", "]", "]", ",", "quiet_exceptions", ":", "\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"", "=", "(", ")", ",", ")", "->", "\"Union[Future[List], Future[Dict]]\"", ":", "if", "isinstance", "(", "children", ",", "dict", ")", ":", "keys", "=", "list", "(", "children", ".", "keys", "(", ")", ")", "# type: Optional[List]", "children_seq", "=", "children", ".", "values", "(", ")", "# type: Iterable", "else", ":", "keys", "=", "None", "children_seq", "=", "children", "children_futs", "=", "list", "(", "map", "(", "convert_yielded", ",", "children_seq", ")", ")", "assert", "all", "(", "is_future", "(", "i", ")", "or", "isinstance", "(", "i", ",", "_NullFuture", ")", "for", "i", "in", "children_futs", ")", "unfinished_children", "=", "set", "(", "children_futs", ")", "future", "=", "_create_future", "(", ")", "if", "not", "children_futs", ":", "future_set_result_unless_cancelled", "(", "future", ",", "{", "}", "if", "keys", "is", "not", "None", "else", "[", "]", ")", "def", "callback", "(", "fut", ":", "Future", ")", "->", "None", ":", "unfinished_children", ".", "remove", "(", "fut", ")", "if", "not", "unfinished_children", ":", "result_list", "=", "[", "]", "for", "f", "in", "children_futs", ":", "try", ":", "result_list", ".", "append", "(", "f", ".", "result", "(", ")", ")", "except", "Exception", "as", "e", ":", "if", "future", ".", "done", "(", ")", ":", "if", "not", "isinstance", "(", "e", ",", "quiet_exceptions", ")", ":", "app_log", ".", "error", "(", "\"Multiple exceptions in yield list\"", ",", "exc_info", "=", "True", ")", "else", ":", "future_set_exc_info", "(", "future", ",", "sys", ".", "exc_info", "(", ")", ")", "if", "not", "future", ".", "done", "(", ")", ":", "if", "keys", "is", "not", "None", ":", "future_set_result_unless_cancelled", "(", "future", ",", "dict", "(", "zip", "(", "keys", ",", "result_list", ")", ")", ")", "else", ":", "future_set_result_unless_cancelled", "(", "future", ",", "result_list", ")", "listening", "=", "set", "(", ")", "# type: Set[Future]", "for", "f", "in", "children_futs", ":", "if", "f", "not", "in", "listening", ":", "listening", ".", "add", "(", "f", ")", "future_add_done_callback", "(", "f", ",", "callback", ")", "return", "future" ]
Wait for multiple asynchronous futures in parallel. Since Tornado 6.0, this function is exactly the same as `multi`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. deprecated:: 4.3 Use `multi` instead.
[ "Wait", "for", "multiple", "asynchronous", "futures", "in", "parallel", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L463-L523
train
tornadoweb/tornado
tornado/gen.py
maybe_future
def maybe_future(x: Any) -> Future: """Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This function only handles ``Futures``, not other yieldable objects. Instead of `maybe_future`, check for the non-future result types you expect (often just ``None``), and ``yield`` anything unknown. """ if is_future(x): return x else: fut = _create_future() fut.set_result(x) return fut
python
def maybe_future(x: Any) -> Future: """Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This function only handles ``Futures``, not other yieldable objects. Instead of `maybe_future`, check for the non-future result types you expect (often just ``None``), and ``yield`` anything unknown. """ if is_future(x): return x else: fut = _create_future() fut.set_result(x) return fut
[ "def", "maybe_future", "(", "x", ":", "Any", ")", "->", "Future", ":", "if", "is_future", "(", "x", ")", ":", "return", "x", "else", ":", "fut", "=", "_create_future", "(", ")", "fut", ".", "set_result", "(", "x", ")", "return", "fut" ]
Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This function only handles ``Futures``, not other yieldable objects. Instead of `maybe_future`, check for the non-future result types you expect (often just ``None``), and ``yield`` anything unknown.
[ "Converts", "x", "into", "a", ".", "Future", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L526-L544
train
tornadoweb/tornado
tornado/gen.py
with_timeout
def with_timeout( timeout: Union[float, datetime.timedelta], future: _Yieldable, quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> Future: """Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not 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`) If the wrapped `.Future` fails after it has timed out, the exception will be logged unless it is of a type contained in ``quiet_exceptions`` (which may be an exception type or a sequence of types). The wrapped `.Future` is not canceled when the timeout expires, permitting it to be reused. `asyncio.wait_for` is similar to this function but it does cancel the wrapped `.Future` on timeout. .. versionadded:: 4.0 .. versionchanged:: 4.1 Added the ``quiet_exceptions`` argument and the logging of unhandled exceptions. .. versionchanged:: 4.4 Added support for yieldable objects other than `.Future`. """ # It's tempting to optimize this by cancelling the input future on timeout # instead of creating a new one, but A) we can't know if we are the only # one waiting on the input future, so cancelling it might disrupt other # callers and B) concurrent futures can only be cancelled while they are # in the queue, so cancellation cannot reliably bound our waiting time. future_converted = convert_yielded(future) result = _create_future() chain_future(future_converted, result) io_loop = IOLoop.current() def error_callback(future: Future) -> None: try: future.result() except Exception as e: if not isinstance(e, quiet_exceptions): app_log.error( "Exception in Future %r after timeout", future, exc_info=True ) def timeout_callback() -> None: if not result.done(): result.set_exception(TimeoutError("Timeout")) # In case the wrapped future goes on to fail, log it. future_add_done_callback(future_converted, error_callback) timeout_handle = io_loop.add_timeout(timeout, timeout_callback) if isinstance(future_converted, Future): # We know this future will resolve on the IOLoop, so we don't # need the extra thread-safety of IOLoop.add_future (and we also # don't care about StackContext here. future_add_done_callback( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) else: # concurrent.futures.Futures may resolve on any thread, so we # need to route them back to the IOLoop. io_loop.add_future( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) return result
python
def with_timeout( timeout: Union[float, datetime.timedelta], future: _Yieldable, quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> Future: """Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not 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`) If the wrapped `.Future` fails after it has timed out, the exception will be logged unless it is of a type contained in ``quiet_exceptions`` (which may be an exception type or a sequence of types). The wrapped `.Future` is not canceled when the timeout expires, permitting it to be reused. `asyncio.wait_for` is similar to this function but it does cancel the wrapped `.Future` on timeout. .. versionadded:: 4.0 .. versionchanged:: 4.1 Added the ``quiet_exceptions`` argument and the logging of unhandled exceptions. .. versionchanged:: 4.4 Added support for yieldable objects other than `.Future`. """ # It's tempting to optimize this by cancelling the input future on timeout # instead of creating a new one, but A) we can't know if we are the only # one waiting on the input future, so cancelling it might disrupt other # callers and B) concurrent futures can only be cancelled while they are # in the queue, so cancellation cannot reliably bound our waiting time. future_converted = convert_yielded(future) result = _create_future() chain_future(future_converted, result) io_loop = IOLoop.current() def error_callback(future: Future) -> None: try: future.result() except Exception as e: if not isinstance(e, quiet_exceptions): app_log.error( "Exception in Future %r after timeout", future, exc_info=True ) def timeout_callback() -> None: if not result.done(): result.set_exception(TimeoutError("Timeout")) # In case the wrapped future goes on to fail, log it. future_add_done_callback(future_converted, error_callback) timeout_handle = io_loop.add_timeout(timeout, timeout_callback) if isinstance(future_converted, Future): # We know this future will resolve on the IOLoop, so we don't # need the extra thread-safety of IOLoop.add_future (and we also # don't care about StackContext here. future_add_done_callback( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) else: # concurrent.futures.Futures may resolve on any thread, so we # need to route them back to the IOLoop. io_loop.add_future( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) return result
[ "def", "with_timeout", "(", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", ",", "future", ":", "_Yieldable", ",", "quiet_exceptions", ":", "\"Union[Type[Exception], Tuple[Type[Exception], ...]]\"", "=", "(", ")", ",", ")", "->", "Future", ":", "# It's tempting to optimize this by cancelling the input future on timeout", "# instead of creating a new one, but A) we can't know if we are the only", "# one waiting on the input future, so cancelling it might disrupt other", "# callers and B) concurrent futures can only be cancelled while they are", "# in the queue, so cancellation cannot reliably bound our waiting time.", "future_converted", "=", "convert_yielded", "(", "future", ")", "result", "=", "_create_future", "(", ")", "chain_future", "(", "future_converted", ",", "result", ")", "io_loop", "=", "IOLoop", ".", "current", "(", ")", "def", "error_callback", "(", "future", ":", "Future", ")", "->", "None", ":", "try", ":", "future", ".", "result", "(", ")", "except", "Exception", "as", "e", ":", "if", "not", "isinstance", "(", "e", ",", "quiet_exceptions", ")", ":", "app_log", ".", "error", "(", "\"Exception in Future %r after timeout\"", ",", "future", ",", "exc_info", "=", "True", ")", "def", "timeout_callback", "(", ")", "->", "None", ":", "if", "not", "result", ".", "done", "(", ")", ":", "result", ".", "set_exception", "(", "TimeoutError", "(", "\"Timeout\"", ")", ")", "# In case the wrapped future goes on to fail, log it.", "future_add_done_callback", "(", "future_converted", ",", "error_callback", ")", "timeout_handle", "=", "io_loop", ".", "add_timeout", "(", "timeout", ",", "timeout_callback", ")", "if", "isinstance", "(", "future_converted", ",", "Future", ")", ":", "# We know this future will resolve on the IOLoop, so we don't", "# need the extra thread-safety of IOLoop.add_future (and we also", "# don't care about StackContext here.", "future_add_done_callback", "(", "future_converted", ",", "lambda", "future", ":", "io_loop", ".", "remove_timeout", "(", "timeout_handle", ")", ")", "else", ":", "# concurrent.futures.Futures may resolve on any thread, so we", "# need to route them back to the IOLoop.", "io_loop", ".", "add_future", "(", "future_converted", ",", "lambda", "future", ":", "io_loop", ".", "remove_timeout", "(", "timeout_handle", ")", ")", "return", "result" ]
Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) If the wrapped `.Future` fails after it has timed out, the exception will be logged unless it is of a type contained in ``quiet_exceptions`` (which may be an exception type or a sequence of types). The wrapped `.Future` is not canceled when the timeout expires, permitting it to be reused. `asyncio.wait_for` is similar to this function but it does cancel the wrapped `.Future` on timeout. .. versionadded:: 4.0 .. versionchanged:: 4.1 Added the ``quiet_exceptions`` argument and the logging of unhandled exceptions. .. versionchanged:: 4.4 Added support for yieldable objects other than `.Future`.
[ "Wraps", "a", ".", "Future", "(", "or", "other", "yieldable", "object", ")", "in", "a", "timeout", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L547-L616
train
tornadoweb/tornado
tornado/gen.py
sleep
def sleep(duration: float) -> "Future[None]": """Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does nothing; you must wait on the `.Future` it returns (usually by yielding it). .. versionadded:: 4.1 """ f = _create_future() IOLoop.current().call_later( duration, lambda: future_set_result_unless_cancelled(f, None) ) return f
python
def sleep(duration: float) -> "Future[None]": """Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does nothing; you must wait on the `.Future` it returns (usually by yielding it). .. versionadded:: 4.1 """ f = _create_future() IOLoop.current().call_later( duration, lambda: future_set_result_unless_cancelled(f, None) ) return f
[ "def", "sleep", "(", "duration", ":", "float", ")", "->", "\"Future[None]\"", ":", "f", "=", "_create_future", "(", ")", "IOLoop", ".", "current", "(", ")", ".", "call_later", "(", "duration", ",", "lambda", ":", "future_set_result_unless_cancelled", "(", "f", ",", "None", ")", ")", "return", "f" ]
Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does nothing; you must wait on the `.Future` it returns (usually by yielding it). .. versionadded:: 4.1
[ "Return", "a", ".", "Future", "that", "resolves", "after", "the", "given", "number", "of", "seconds", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L619-L637
train
tornadoweb/tornado
tornado/gen.py
convert_yielded
def convert_yielded(yielded: _Yieldable) -> Future: """Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. This has the side effect of starting any coroutines that did not start themselves, similar to `asyncio.ensure_future`. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.register(asyncio.Future) def _(asyncio_future): return tornado.platform.asyncio.to_tornado_future(asyncio_future) .. versionadded:: 4.1 """ if yielded is None or yielded is moment: return moment elif yielded is _null_future: return _null_future elif isinstance(yielded, (list, dict)): return multi(yielded) # type: ignore elif is_future(yielded): return typing.cast(Future, yielded) elif isawaitable(yielded): return _wrap_awaitable(yielded) # type: ignore else: raise BadYieldError("yielded unknown object %r" % (yielded,))
python
def convert_yielded(yielded: _Yieldable) -> Future: """Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. This has the side effect of starting any coroutines that did not start themselves, similar to `asyncio.ensure_future`. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.register(asyncio.Future) def _(asyncio_future): return tornado.platform.asyncio.to_tornado_future(asyncio_future) .. versionadded:: 4.1 """ if yielded is None or yielded is moment: return moment elif yielded is _null_future: return _null_future elif isinstance(yielded, (list, dict)): return multi(yielded) # type: ignore elif is_future(yielded): return typing.cast(Future, yielded) elif isawaitable(yielded): return _wrap_awaitable(yielded) # type: ignore else: raise BadYieldError("yielded unknown object %r" % (yielded,))
[ "def", "convert_yielded", "(", "yielded", ":", "_Yieldable", ")", "->", "Future", ":", "if", "yielded", "is", "None", "or", "yielded", "is", "moment", ":", "return", "moment", "elif", "yielded", "is", "_null_future", ":", "return", "_null_future", "elif", "isinstance", "(", "yielded", ",", "(", "list", ",", "dict", ")", ")", ":", "return", "multi", "(", "yielded", ")", "# type: ignore", "elif", "is_future", "(", "yielded", ")", ":", "return", "typing", ".", "cast", "(", "Future", ",", "yielded", ")", "elif", "isawaitable", "(", "yielded", ")", ":", "return", "_wrap_awaitable", "(", "yielded", ")", "# type: ignore", "else", ":", "raise", "BadYieldError", "(", "\"yielded unknown object %r\"", "%", "(", "yielded", ",", ")", ")" ]
Convert a yielded object into a `.Future`. The default implementation accepts lists, dictionaries, and Futures. This has the side effect of starting any coroutines that did not start themselves, similar to `asyncio.ensure_future`. If the `~functools.singledispatch` library is available, this function may be extended to support additional types. For example:: @convert_yielded.register(asyncio.Future) def _(asyncio_future): return tornado.platform.asyncio.to_tornado_future(asyncio_future) .. versionadded:: 4.1
[ "Convert", "a", "yielded", "object", "into", "a", ".", "Future", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L808-L836
train
tornadoweb/tornado
tornado/gen.py
WaitIterator.next
def next(self) -> Future: """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = Future() if self._finished: self._return_result(self._finished.popleft()) return self._running_future
python
def next(self) -> Future: """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = Future() if self._finished: self._return_result(self._finished.popleft()) return self._running_future
[ "def", "next", "(", "self", ")", "->", "Future", ":", "self", ".", "_running_future", "=", "Future", "(", ")", "if", "self", ".", "_finished", ":", "self", ".", "_return_result", "(", "self", ".", "_finished", ".", "popleft", "(", ")", ")", "return", "self", ".", "_running_future" ]
Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs.
[ "Returns", "a", ".", "Future", "that", "will", "yield", "the", "next", "available", "result", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L369-L380
train
tornadoweb/tornado
tornado/gen.py
Runner.run
def run(self) -> None: """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: future = self.future if future is None: raise Exception("No pending future") if not future.done(): return self.future = None try: exc_info = None try: value = future.result() except Exception: exc_info = sys.exc_info() future = None if exc_info is not None: try: yielded = self.gen.throw(*exc_info) # type: ignore finally: # Break up a reference to itself # for faster GC on CPython. exc_info = None else: yielded = self.gen.send(value) except (StopIteration, Return) as e: self.finished = True self.future = _null_future future_set_result_unless_cancelled( self.result_future, _value_from_stopiteration(e) ) self.result_future = None # type: ignore return except Exception: self.finished = True self.future = _null_future future_set_exc_info(self.result_future, sys.exc_info()) self.result_future = None # type: ignore return if not self.handle_yield(yielded): return yielded = None finally: self.running = False
python
def run(self) -> None: """Starts or resumes the generator, running until it reaches a yield point that is not ready. """ if self.running or self.finished: return try: self.running = True while True: future = self.future if future is None: raise Exception("No pending future") if not future.done(): return self.future = None try: exc_info = None try: value = future.result() except Exception: exc_info = sys.exc_info() future = None if exc_info is not None: try: yielded = self.gen.throw(*exc_info) # type: ignore finally: # Break up a reference to itself # for faster GC on CPython. exc_info = None else: yielded = self.gen.send(value) except (StopIteration, Return) as e: self.finished = True self.future = _null_future future_set_result_unless_cancelled( self.result_future, _value_from_stopiteration(e) ) self.result_future = None # type: ignore return except Exception: self.finished = True self.future = _null_future future_set_exc_info(self.result_future, sys.exc_info()) self.result_future = None # type: ignore return if not self.handle_yield(yielded): return yielded = None finally: self.running = False
[ "def", "run", "(", "self", ")", "->", "None", ":", "if", "self", ".", "running", "or", "self", ".", "finished", ":", "return", "try", ":", "self", ".", "running", "=", "True", "while", "True", ":", "future", "=", "self", ".", "future", "if", "future", "is", "None", ":", "raise", "Exception", "(", "\"No pending future\"", ")", "if", "not", "future", ".", "done", "(", ")", ":", "return", "self", ".", "future", "=", "None", "try", ":", "exc_info", "=", "None", "try", ":", "value", "=", "future", ".", "result", "(", ")", "except", "Exception", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "future", "=", "None", "if", "exc_info", "is", "not", "None", ":", "try", ":", "yielded", "=", "self", ".", "gen", ".", "throw", "(", "*", "exc_info", ")", "# type: ignore", "finally", ":", "# Break up a reference to itself", "# for faster GC on CPython.", "exc_info", "=", "None", "else", ":", "yielded", "=", "self", ".", "gen", ".", "send", "(", "value", ")", "except", "(", "StopIteration", ",", "Return", ")", "as", "e", ":", "self", ".", "finished", "=", "True", "self", ".", "future", "=", "_null_future", "future_set_result_unless_cancelled", "(", "self", ".", "result_future", ",", "_value_from_stopiteration", "(", "e", ")", ")", "self", ".", "result_future", "=", "None", "# type: ignore", "return", "except", "Exception", ":", "self", ".", "finished", "=", "True", "self", ".", "future", "=", "_null_future", "future_set_exc_info", "(", "self", ".", "result_future", ",", "sys", ".", "exc_info", "(", ")", ")", "self", ".", "result_future", "=", "None", "# type: ignore", "return", "if", "not", "self", ".", "handle_yield", "(", "yielded", ")", ":", "return", "yielded", "=", "None", "finally", ":", "self", ".", "running", "=", "False" ]
Starts or resumes the generator, running until it reaches a yield point that is not ready.
[ "Starts", "or", "resumes", "the", "generator", "running", "until", "it", "reaches", "a", "yield", "point", "that", "is", "not", "ready", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/gen.py#L710-L762
train
tornadoweb/tornado
tornado/iostream.py
_StreamBuffer.append
def append(self, data: Union[bytes, bytearray, memoryview]) -> None: """ Append the given piece of data (should be a buffer-compatible object). """ size = len(data) if size > self._large_buf_threshold: if not isinstance(data, memoryview): data = memoryview(data) self._buffers.append((True, data)) elif size > 0: if self._buffers: is_memview, b = self._buffers[-1] new_buf = is_memview or len(b) >= self._large_buf_threshold else: new_buf = True if new_buf: self._buffers.append((False, bytearray(data))) else: b += data # type: ignore self._size += size
python
def append(self, data: Union[bytes, bytearray, memoryview]) -> None: """ Append the given piece of data (should be a buffer-compatible object). """ size = len(data) if size > self._large_buf_threshold: if not isinstance(data, memoryview): data = memoryview(data) self._buffers.append((True, data)) elif size > 0: if self._buffers: is_memview, b = self._buffers[-1] new_buf = is_memview or len(b) >= self._large_buf_threshold else: new_buf = True if new_buf: self._buffers.append((False, bytearray(data))) else: b += data # type: ignore self._size += size
[ "def", "append", "(", "self", ",", "data", ":", "Union", "[", "bytes", ",", "bytearray", ",", "memoryview", "]", ")", "->", "None", ":", "size", "=", "len", "(", "data", ")", "if", "size", ">", "self", ".", "_large_buf_threshold", ":", "if", "not", "isinstance", "(", "data", ",", "memoryview", ")", ":", "data", "=", "memoryview", "(", "data", ")", "self", ".", "_buffers", ".", "append", "(", "(", "True", ",", "data", ")", ")", "elif", "size", ">", "0", ":", "if", "self", ".", "_buffers", ":", "is_memview", ",", "b", "=", "self", ".", "_buffers", "[", "-", "1", "]", "new_buf", "=", "is_memview", "or", "len", "(", "b", ")", ">=", "self", ".", "_large_buf_threshold", "else", ":", "new_buf", "=", "True", "if", "new_buf", ":", "self", ".", "_buffers", ".", "append", "(", "(", "False", ",", "bytearray", "(", "data", ")", ")", ")", "else", ":", "b", "+=", "data", "# type: ignore", "self", ".", "_size", "+=", "size" ]
Append the given piece of data (should be a buffer-compatible object).
[ "Append", "the", "given", "piece", "of", "data", "(", "should", "be", "a", "buffer", "-", "compatible", "object", ")", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L159-L179
train