id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
26,700
tornadoweb/tornado
tornado/web.py
stream_request_body
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
python
def stream_request_body(cls: Type[RequestHandler]) -> Type[RequestHandler]: """Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage. """ # noqa: E501 if not issubclass(cls, RequestHandler): raise TypeError("expected subclass of RequestHandler, got %r", cls) cls._stream_request_body = True return cls
[ "def", "stream_request_body", "(", "cls", ":", "Type", "[", "RequestHandler", "]", ")", "->", "Type", "[", "RequestHandler", "]", ":", "# noqa: E501", "if", "not", "issubclass", "(", "cls", ",", "RequestHandler", ")", ":", "raise", "TypeError", "(", "\"expected subclass of RequestHandler, got %r\"", ",", "cls", ")", "cls", ".", "_stream_request_body", "=", "True", "return", "cls" ]
Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of after the entire body has been read. * The subclass must define a method ``data_received(self, data):``, which will be called zero or more times as data is available. Note that if the request has an empty body, ``data_received`` may not be called. * ``prepare`` and ``data_received`` may return Futures (such as via ``@gen.coroutine``, in which case the next method will not be called until those futures have completed. * The regular HTTP method (``post``, ``put``, etc) will be called after the entire body has been read. See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/master/demos/file_upload/>`_ for example usage.
[ "Apply", "to", "RequestHandler", "subclasses", "to", "enable", "streaming", "body", "support", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1824-L1848
26,701
tornadoweb/tornado
tornado/web.py
removeslash
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if self.request.path.endswith("/"): if self.request.method in ("GET", "HEAD"): uri = self.request.path.rstrip("/") if uri: # don't try to redirect '/' to '' if self.request.query: uri += "?" + self.request.query self.redirect(uri, permanent=True) return None else: raise HTTPError(404) return method(self, *args, **kwargs) return wrapper
python
def removeslash( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if self.request.path.endswith("/"): if self.request.method in ("GET", "HEAD"): uri = self.request.path.rstrip("/") if uri: # don't try to redirect '/' to '' if self.request.query: uri += "?" + self.request.query self.redirect(uri, permanent=True) return None else: raise HTTPError(404) return method(self, *args, **kwargs) return wrapper
[ "def", "removeslash", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "# type: ignore", "self", ":", "RequestHandler", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Optional", "[", "Awaitable", "[", "None", "]", "]", ":", "if", "self", ".", "request", ".", "path", ".", "endswith", "(", "\"/\"", ")", ":", "if", "self", ".", "request", ".", "method", "in", "(", "\"GET\"", ",", "\"HEAD\"", ")", ":", "uri", "=", "self", ".", "request", ".", "path", ".", "rstrip", "(", "\"/\"", ")", "if", "uri", ":", "# don't try to redirect '/' to ''", "if", "self", ".", "request", ".", "query", ":", "uri", "+=", "\"?\"", "+", "self", ".", "request", ".", "query", "self", ".", "redirect", "(", "uri", ",", "permanent", "=", "True", ")", "return", "None", "else", ":", "raise", "HTTPError", "(", "404", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator.
[ "Use", "this", "decorator", "to", "remove", "trailing", "slashes", "from", "the", "request", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1857-L1883
26,702
tornadoweb/tornado
tornado/web.py
authenticated
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urllib.parse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: assert self.request.uri is not None next_url = self.request.uri url += "?" + urlencode(dict(next=next_url)) self.redirect(url) return None raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
python
def authenticated( method: Callable[..., Optional[Awaitable[None]]] ) -> Callable[..., Optional[Awaitable[None]]]: """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in. """ @functools.wraps(method) def wrapper( # type: ignore self: RequestHandler, *args, **kwargs ) -> Optional[Awaitable[None]]: if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urllib.parse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: assert self.request.uri is not None next_url = self.request.uri url += "?" + urlencode(dict(next=next_url)) self.redirect(url) return None raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
[ "def", "authenticated", "(", "method", ":", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ")", "->", "Callable", "[", "...", ",", "Optional", "[", "Awaitable", "[", "None", "]", "]", "]", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "# type: ignore", "self", ":", "RequestHandler", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Optional", "[", "Awaitable", "[", "None", "]", "]", ":", "if", "not", "self", ".", "current_user", ":", "if", "self", ".", "request", ".", "method", "in", "(", "\"GET\"", ",", "\"HEAD\"", ")", ":", "url", "=", "self", ".", "get_login_url", "(", ")", "if", "\"?\"", "not", "in", "url", ":", "if", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", ".", "scheme", ":", "# if login url is absolute, make next absolute too", "next_url", "=", "self", ".", "request", ".", "full_url", "(", ")", "else", ":", "assert", "self", ".", "request", ".", "uri", "is", "not", "None", "next_url", "=", "self", ".", "request", ".", "uri", "url", "+=", "\"?\"", "+", "urlencode", "(", "dict", "(", "next", "=", "next_url", ")", ")", "self", ".", "redirect", "(", "url", ")", "return", "None", "raise", "HTTPError", "(", "403", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in.
[ "Decorate", "methods", "with", "this", "to", "require", "that", "the", "user", "be", "logged", "in", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L3142-L3176
26,703
tornadoweb/tornado
tornado/web.py
RequestHandler.on_connection_close
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection. """ if _has_stream_request_body(self.__class__): if not self.request._body_future.done(): self.request._body_future.set_exception(iostream.StreamClosedError()) self.request._body_future.exception()
python
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection. """ if _has_stream_request_body(self.__class__): if not self.request._body_future.done(): self.request._body_future.set_exception(iostream.StreamClosedError()) self.request._body_future.exception()
[ "def", "on_connection_close", "(", "self", ")", "->", "None", ":", "if", "_has_stream_request_body", "(", "self", ".", "__class__", ")", ":", "if", "not", "self", ".", "request", ".", "_body_future", ".", "done", "(", ")", ":", "self", ".", "request", ".", "_body_future", ".", "set_exception", "(", "iostream", ".", "StreamClosedError", "(", ")", ")", "self", ".", "request", ".", "_body_future", ".", "exception", "(", ")" ]
Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override `on_finish` instead. Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
[ "Called", "in", "async", "handlers", "if", "the", "client", "closed", "the", "connection", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L300-L317
26,704
tornadoweb/tornado
tornado/web.py
RequestHandler.clear
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timestamp(time.time()), } ) self.set_default_headers() self._write_buffer = [] # type: List[bytes] self._status_code = 200 self._reason = httputil.responses[200]
python
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timestamp(time.time()), } ) self.set_default_headers() self._write_buffer = [] # type: List[bytes] self._status_code = 200 self._reason = httputil.responses[200]
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_headers", "=", "httputil", ".", "HTTPHeaders", "(", "{", "\"Server\"", ":", "\"TornadoServer/%s\"", "%", "tornado", ".", "version", ",", "\"Content-Type\"", ":", "\"text/html; charset=UTF-8\"", ",", "\"Date\"", ":", "httputil", ".", "format_timestamp", "(", "time", ".", "time", "(", ")", ")", ",", "}", ")", "self", ".", "set_default_headers", "(", ")", "self", ".", "_write_buffer", "=", "[", "]", "# type: List[bytes]", "self", ".", "_status_code", "=", "200", "self", ".", "_reason", "=", "httputil", ".", "responses", "[", "200", "]" ]
Resets all headers and content for this response.
[ "Resets", "all", "headers", "and", "content", "for", "this", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L319-L331
26,705
tornadoweb/tornado
tornado/web.py
RequestHandler.set_status
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`. """ self._status_code = status_code if reason is not None: self._reason = escape.native_str(reason) else: self._reason = httputil.responses.get(status_code, "Unknown")
python
def set_status(self, status_code: int, reason: str = None) -> None: """Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`. """ self._status_code = status_code if reason is not None: self._reason = escape.native_str(reason) else: self._reason = httputil.responses.get(status_code, "Unknown")
[ "def", "set_status", "(", "self", ",", "status_code", ":", "int", ",", "reason", ":", "str", "=", "None", ")", "->", "None", ":", "self", ".", "_status_code", "=", "status_code", "if", "reason", "is", "not", "None", ":", "self", ".", "_reason", "=", "escape", ".", "native_str", "(", "reason", ")", "else", ":", "self", ".", "_reason", "=", "httputil", ".", "responses", ".", "get", "(", "status_code", ",", "\"Unknown\"", ")" ]
Sets the status code for our response. :arg int status_code: Response status code. :arg str reason: Human-readable reason phrase describing the status code. If ``None``, it will be filled in from `http.client.responses` or "Unknown". .. versionchanged:: 5.0 No longer validates that the response code is in `http.client.responses`.
[ "Sets", "the", "status", "code", "for", "our", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L343-L360
26,706
tornadoweb/tornado
tornado/web.py
RequestHandler.set_header
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[name] = self._convert_header_value(value)
python
def set_header(self, name: str, value: _HeaderTypes) -> None: """Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header). """ self._headers[name] = self._convert_header_value(value)
[ "def", "set_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", "[", "name", "]", "=", "self", ".", "_convert_header_value", "(", "value", ")" ]
Sets the given response header name and value. All header values are converted to strings (`datetime` objects are formatted according to the HTTP specification for the ``Date`` header).
[ "Sets", "the", "given", "response", "header", "name", "and", "value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L366-L374
26,707
tornadoweb/tornado
tornado/web.py
RequestHandler.add_header
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
python
def add_header(self, name: str, value: _HeaderTypes) -> None: """Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header. """ self._headers.add(name, self._convert_header_value(value))
[ "def", "add_header", "(", "self", ",", "name", ":", "str", ",", "value", ":", "_HeaderTypes", ")", "->", "None", ":", "self", ".", "_headers", ".", "add", "(", "name", ",", "self", ".", "_convert_header_value", "(", "value", ")", ")" ]
Adds the given response header and value. Unlike `set_header`, `add_header` may be called multiple times to return multiple values for the same header.
[ "Adds", "the", "given", "response", "header", "and", "value", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L376-L382
26,708
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_header
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
python
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
[ "def", "clear_header", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "name", "in", "self", ".", "_headers", ":", "del", "self", ".", "_headers", "[", "name", "]" ]
Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`.
[ "Clears", "an", "outgoing", "header", "undoing", "a", "previous", "set_header", "call", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L384-L391
26,709
tornadoweb/tornado
tornado/web.py
RequestHandler.get_arguments
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # Make sure `get_arguments` isn't accidentally being called with a # positional argument that's assumed to be a default (like in # `get_argument`.) assert isinstance(strip, bool) return self._get_arguments(name, self.request.arguments, strip)
python
def get_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments. """ # Make sure `get_arguments` isn't accidentally being called with a # positional argument that's assumed to be a default (like in # `get_argument`.) assert isinstance(strip, bool) return self._get_arguments(name, self.request.arguments, strip)
[ "def", "get_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "# Make sure `get_arguments` isn't accidentally being called with a", "# positional argument that's assumed to be a default (like in", "# `get_argument`.)", "assert", "isinstance", "(", "strip", ",", "bool", ")", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "arguments", ",", "strip", ")" ]
Returns a list of the arguments with the given name. If the argument is not present, returns an empty list. This method searches both the query and body arguments.
[ "Returns", "a", "list", "of", "the", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L457-L470
26,710
tornadoweb/tornado
tornado/web.py
RequestHandler.get_body_argument
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.body_arguments, strip)
python
def get_body_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.body_arguments, strip)
[ "def", "get_body_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_get_argument", "(", "name", ",", "default", ",", "self", ".", "request", ".", "body_arguments", ",", "strip", ")" ]
Returns the value of the argument with the given name from the request body. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "body", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L472-L489
26,711
tornadoweb/tornado
tornado/web.py
RequestHandler.get_body_arguments
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, strip)
python
def get_body_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.body_arguments, strip)
[ "def", "get_body_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "body_arguments", ",", "strip", ")" ]
Returns a list of the body arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
[ "Returns", "a", "list", "of", "the", "body", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L491-L498
26,712
tornadoweb/tornado
tornado/web.py
RequestHandler.get_query_argument
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.query_arguments, strip)
python
def get_query_argument( self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2 """ return self._get_argument(name, default, self.request.query_arguments, strip)
[ "def", "get_query_argument", "(", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_get_argument", "(", "name", ",", "default", ",", "self", ".", "request", ".", "query_arguments", ",", "strip", ")" ]
Returns the value of the argument with the given name from the request query string. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. .. versionadded:: 3.2
[ "Returns", "the", "value", "of", "the", "argument", "with", "the", "given", "name", "from", "the", "request", "query", "string", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L500-L517
26,713
tornadoweb/tornado
tornado/web.py
RequestHandler.get_query_arguments
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_arguments, strip)
python
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]: """Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2 """ return self._get_arguments(name, self.request.query_arguments, strip)
[ "def", "get_query_arguments", "(", "self", ",", "name", ":", "str", ",", "strip", ":", "bool", "=", "True", ")", "->", "List", "[", "str", "]", ":", "return", "self", ".", "_get_arguments", "(", "name", ",", "self", ".", "request", ".", "query_arguments", ",", "strip", ")" ]
Returns a list of the query arguments with the given name. If the argument is not present, returns an empty list. .. versionadded:: 3.2
[ "Returns", "a", "list", "of", "the", "query", "arguments", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L519-L526
26,714
tornadoweb/tornado
tornado/web.py
RequestHandler.decode_argument
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex). """ try: return _unicode(value) except UnicodeDecodeError: raise HTTPError( 400, "Invalid unicode in %s: %r" % (name or "url", value[:40]) )
python
def decode_argument(self, value: bytes, name: str = None) -> str: """Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex). """ try: return _unicode(value) except UnicodeDecodeError: raise HTTPError( 400, "Invalid unicode in %s: %r" % (name or "url", value[:40]) )
[ "def", "decode_argument", "(", "self", ",", "value", ":", "bytes", ",", "name", ":", "str", "=", "None", ")", "->", "str", ":", "try", ":", "return", "_unicode", "(", "value", ")", "except", "UnicodeDecodeError", ":", "raise", "HTTPError", "(", "400", ",", "\"Invalid unicode in %s: %r\"", "%", "(", "name", "or", "\"url\"", ",", "value", "[", ":", "40", "]", ")", ")" ]
Decodes an argument from the request. The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses. This method is used as a filter for both `get_argument()` and for values extracted from the url and passed to `get()`/`post()`/etc. The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
[ "Decodes", "an", "argument", "from", "the", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L557-L575
26,715
tornadoweb/tornado
tornado/web.py
RequestHandler.get_cookie
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler. """ if self.request.cookies is not None and name in self.request.cookies: return self.request.cookies[name].value return default
python
def get_cookie(self, name: str, default: str = None) -> Optional[str]: """Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler. """ if self.request.cookies is not None and name in self.request.cookies: return self.request.cookies[name].value return default
[ "def", "get_cookie", "(", "self", ",", "name", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "request", ".", "cookies", "is", "not", "None", "and", "name", "in", "self", ".", "request", ".", "cookies", ":", "return", "self", ".", "request", ".", "cookies", "[", "name", "]", ".", "value", "return", "default" ]
Returns the value of the request cookie with the given name. If the named cookie is not present, returns ``default``. This method only returns cookies that were present in the request. It does not see the outgoing cookies set by `set_cookie` in this handler.
[ "Returns", "the", "value", "of", "the", "request", "cookie", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L583-L594
26,716
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_cookie
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request. """ expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain)
python
def clear_cookie(self, name: str, path: str = "/", domain: str = None) -> None: """Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request. """ expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain)
[ "def", "clear_cookie", "(", "self", ",", "name", ":", "str", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "expires", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "365", ")", "self", ".", "set_cookie", "(", "name", ",", "value", "=", "\"\"", ",", "path", "=", "path", ",", "expires", "=", "expires", ",", "domain", "=", "domain", ")" ]
Deletes the cookie with the given name. Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie). Similar to `set_cookie`, the effect of this method will not be seen until the following request.
[ "Deletes", "the", "cookie", "with", "the", "given", "name", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L651-L663
26,717
tornadoweb/tornado
tornado/web.py
RequestHandler.clear_all_cookies
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters. """ for name in self.request.cookies: self.clear_cookie(name, path=path, domain=domain)
python
def clear_all_cookies(self, path: str = "/", domain: str = None) -> None: """Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters. """ for name in self.request.cookies: self.clear_cookie(name, path=path, domain=domain)
[ "def", "clear_all_cookies", "(", "self", ",", "path", ":", "str", "=", "\"/\"", ",", "domain", ":", "str", "=", "None", ")", "->", "None", ":", "for", "name", "in", "self", ".", "request", ".", "cookies", ":", "self", ".", "clear_cookie", "(", "name", ",", "path", "=", "path", ",", "domain", "=", "domain", ")" ]
Deletes all the cookies the user sent with this request. See `clear_cookie` for more information on the path and domain parameters. Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2 Added the ``path`` and ``domain`` parameters.
[ "Deletes", "all", "the", "cookies", "the", "user", "sent", "with", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L665-L679
26,718
tornadoweb/tornado
tornado/web.py
RequestHandler.set_secure_cookie
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.set_cookie( name, self.create_signed_value(name, value, version=version), expires_days=expires_days, **kwargs )
python
def set_secure_cookie( self, name: str, value: Union[str, bytes], expires_days: int = 30, version: int = None, **kwargs: Any ) -> None: """Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.set_cookie( name, self.create_signed_value(name, value, version=version), expires_days=expires_days, **kwargs )
[ "def", "set_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "expires_days", ":", "int", "=", "30", ",", "version", ":", "int", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "set_cookie", "(", "name", ",", "self", ".", "create_signed_value", "(", "name", ",", "value", ",", "version", "=", "version", ")", ",", "expires_days", "=", "expires_days", ",", "*", "*", "kwargs", ")" ]
Signs and timestamps a cookie so it cannot be forged. You must specify the ``cookie_secret`` setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use `get_secure_cookie()`. Note that the ``expires_days`` parameter sets the lifetime of the cookie in the browser, but is independent of the ``max_age_days`` parameter to `get_secure_cookie`. Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies) Similar to `set_cookie`, the effect of this method will not be seen until the following request. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default.
[ "Signs", "and", "timestamps", "a", "cookie", "so", "it", "cannot", "be", "forged", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L681-L717
26,719
tornadoweb/tornado
tornado/web.py
RequestHandler.create_signed_value
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.require_setting("cookie_secret", "secure cookies") secret = self.application.settings["cookie_secret"] key_version = None if isinstance(secret, dict): if self.application.settings.get("key_version") is None: raise Exception("key_version setting must be used for secret_key dicts") key_version = self.application.settings["key_version"] return create_signed_value( secret, name, value, version=version, key_version=key_version )
python
def create_signed_value( self, name: str, value: Union[str, bytes], version: int = None ) -> bytes: """Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default. """ self.require_setting("cookie_secret", "secure cookies") secret = self.application.settings["cookie_secret"] key_version = None if isinstance(secret, dict): if self.application.settings.get("key_version") is None: raise Exception("key_version setting must be used for secret_key dicts") key_version = self.application.settings["key_version"] return create_signed_value( secret, name, value, version=version, key_version=key_version )
[ "def", "create_signed_value", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "version", ":", "int", "=", "None", ")", "->", "bytes", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", ",", "\"secure cookies\"", ")", "secret", "=", "self", ".", "application", ".", "settings", "[", "\"cookie_secret\"", "]", "key_version", "=", "None", "if", "isinstance", "(", "secret", ",", "dict", ")", ":", "if", "self", ".", "application", ".", "settings", ".", "get", "(", "\"key_version\"", ")", "is", "None", ":", "raise", "Exception", "(", "\"key_version setting must be used for secret_key dicts\"", ")", "key_version", "=", "self", ".", "application", ".", "settings", "[", "\"key_version\"", "]", "return", "create_signed_value", "(", "secret", ",", "name", ",", "value", ",", "version", "=", "version", ",", "key_version", "=", "key_version", ")" ]
Signs and timestamps a string so it cannot be forged. Normally used via set_secure_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_secure_cookie. .. versionchanged:: 3.2.1 Added the ``version`` argument. Introduced cookie version 2 and made it the default.
[ "Signs", "and", "timestamps", "a", "string", "so", "it", "cannot", "be", "forged", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L719-L743
26,720
tornadoweb/tornado
tornado/web.py
RequestHandler.get_secure_cookie
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) return decode_signed_value( self.application.settings["cookie_secret"], name, value, max_age_days=max_age_days, min_version=min_version, )
python
def get_secure_cookie( self, name: str, value: str = None, max_age_days: int = 31, min_version: int = None, ) -> Optional[bytes]: """Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) return decode_signed_value( self.application.settings["cookie_secret"], name, value, max_age_days=max_age_days, min_version=min_version, )
[ "def", "get_secure_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ",", "max_age_days", ":", "int", "=", "31", ",", "min_version", ":", "int", "=", "None", ",", ")", "->", "Optional", "[", "bytes", "]", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", ",", "\"secure cookies\"", ")", "if", "value", "is", "None", ":", "value", "=", "self", ".", "get_cookie", "(", "name", ")", "return", "decode_signed_value", "(", "self", ".", "application", ".", "settings", "[", "\"cookie_secret\"", "]", ",", "name", ",", "value", ",", "max_age_days", "=", "max_age_days", ",", "min_version", "=", "min_version", ",", ")" ]
Returns the given signed cookie if it validates, or None. The decoded cookie value is returned as a byte string (unlike `get_cookie`). Similar to `get_cookie`, this method only returns cookies that were present in the request. It does not see outgoing cookies set by `set_secure_cookie` in this handler. .. versionchanged:: 3.2.1 Added the ``min_version`` argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.
[ "Returns", "the", "given", "signed", "cookie", "if", "it", "validates", "or", "None", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L745-L775
26,721
tornadoweb/tornado
tornado/web.py
RequestHandler.get_secure_cookie_key_version
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) if value is None: return None return get_signature_key_version(value)
python
def get_secure_cookie_key_version( self, name: str, value: str = None ) -> Optional[int]: """Returns the signing key version of the secure cookie. The version is returned as int. """ self.require_setting("cookie_secret", "secure cookies") if value is None: value = self.get_cookie(name) if value is None: return None return get_signature_key_version(value)
[ "def", "get_secure_cookie_key_version", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", "=", "None", ")", "->", "Optional", "[", "int", "]", ":", "self", ".", "require_setting", "(", "\"cookie_secret\"", ",", "\"secure cookies\"", ")", "if", "value", "is", "None", ":", "value", "=", "self", ".", "get_cookie", "(", "name", ")", "if", "value", "is", "None", ":", "return", "None", "return", "get_signature_key_version", "(", "value", ")" ]
Returns the signing key version of the secure cookie. The version is returned as int.
[ "Returns", "the", "signing", "key", "version", "of", "the", "secure", "cookie", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L777-L789
26,722
tornadoweb/tornado
tornado/web.py
RequestHandler.write
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009 """ if self._finished: raise RuntimeError("Cannot write() after finish()") if not isinstance(chunk, (bytes, unicode_type, dict)): message = "write() only accepts bytes, unicode, and dict objects" if isinstance(chunk, list): message += ( ". Lists not accepted for security reasons; see " + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 ) raise TypeError(message) if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
python
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009 """ if self._finished: raise RuntimeError("Cannot write() after finish()") if not isinstance(chunk, (bytes, unicode_type, dict)): message = "write() only accepts bytes, unicode, and dict objects" if isinstance(chunk, list): message += ( ". Lists not accepted for security reasons; see " + "http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write" # noqa: E501 ) raise TypeError(message) if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
[ "def", "write", "(", "self", ",", "chunk", ":", "Union", "[", "str", ",", "bytes", ",", "dict", "]", ")", "->", "None", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot write() after finish()\"", ")", "if", "not", "isinstance", "(", "chunk", ",", "(", "bytes", ",", "unicode_type", ",", "dict", ")", ")", ":", "message", "=", "\"write() only accepts bytes, unicode, and dict objects\"", "if", "isinstance", "(", "chunk", ",", "list", ")", ":", "message", "+=", "(", "\". Lists not accepted for security reasons; see \"", "+", "\"http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write\"", "# noqa: E501", ")", "raise", "TypeError", "(", "message", ")", "if", "isinstance", "(", "chunk", ",", "dict", ")", ":", "chunk", "=", "escape", ".", "json_encode", "(", "chunk", ")", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/json; charset=UTF-8\"", ")", "chunk", "=", "utf8", "(", "chunk", ")", "self", ".", "_write_buffer", ".", "append", "(", "chunk", ")" ]
Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call ``set_header`` *after* calling ``write()``). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and https://github.com/facebook/tornado/issues/1009
[ "Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L809-L839
26,723
tornadoweb/tornado
tornado/web.py
RequestHandler.render
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) # Insert the additional JS and CSS added by the modules on the page js_embed = [] js_files = [] css_embed = [] css_files = [] html_heads = [] html_bodies = [] for module in getattr(self, "_active_modules", {}).values(): embed_part = module.embedded_javascript() if embed_part: js_embed.append(utf8(embed_part)) file_part = module.javascript_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): js_files.append(_unicode(file_part)) else: js_files.extend(file_part) embed_part = module.embedded_css() if embed_part: css_embed.append(utf8(embed_part)) file_part = module.css_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): css_files.append(_unicode(file_part)) else: css_files.extend(file_part) head_part = module.html_head() if head_part: html_heads.append(utf8(head_part)) body_part = module.html_body() if body_part: html_bodies.append(utf8(body_part)) if js_files: # Maintain order of JavaScript files given by modules js = self.render_linked_js(js_files) sloc = html.rindex(b"</body>") html = html[:sloc] + utf8(js) + b"\n" + html[sloc:] if js_embed: js_bytes = self.render_embed_js(js_embed) sloc = html.rindex(b"</body>") html = html[:sloc] + js_bytes + b"\n" + html[sloc:] if css_files: css = self.render_linked_css(css_files) hloc = html.index(b"</head>") html = html[:hloc] + utf8(css) + b"\n" + html[hloc:] if css_embed: css_bytes = self.render_embed_css(css_embed) hloc = html.index(b"</head>") html = html[:hloc] + css_bytes + b"\n" + html[hloc:] if html_heads: hloc = html.index(b"</head>") html = html[:hloc] + b"".join(html_heads) + b"\n" + html[hloc:] if html_bodies: hloc = html.index(b"</body>") html = html[:hloc] + b"".join(html_bodies) + b"\n" + html[hloc:] return self.finish(html)
python
def render(self, template_name: str, **kwargs: Any) -> "Future[None]": """Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``. """ if self._finished: raise RuntimeError("Cannot render() after finish()") html = self.render_string(template_name, **kwargs) # Insert the additional JS and CSS added by the modules on the page js_embed = [] js_files = [] css_embed = [] css_files = [] html_heads = [] html_bodies = [] for module in getattr(self, "_active_modules", {}).values(): embed_part = module.embedded_javascript() if embed_part: js_embed.append(utf8(embed_part)) file_part = module.javascript_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): js_files.append(_unicode(file_part)) else: js_files.extend(file_part) embed_part = module.embedded_css() if embed_part: css_embed.append(utf8(embed_part)) file_part = module.css_files() if file_part: if isinstance(file_part, (unicode_type, bytes)): css_files.append(_unicode(file_part)) else: css_files.extend(file_part) head_part = module.html_head() if head_part: html_heads.append(utf8(head_part)) body_part = module.html_body() if body_part: html_bodies.append(utf8(body_part)) if js_files: # Maintain order of JavaScript files given by modules js = self.render_linked_js(js_files) sloc = html.rindex(b"</body>") html = html[:sloc] + utf8(js) + b"\n" + html[sloc:] if js_embed: js_bytes = self.render_embed_js(js_embed) sloc = html.rindex(b"</body>") html = html[:sloc] + js_bytes + b"\n" + html[sloc:] if css_files: css = self.render_linked_css(css_files) hloc = html.index(b"</head>") html = html[:hloc] + utf8(css) + b"\n" + html[hloc:] if css_embed: css_bytes = self.render_embed_css(css_embed) hloc = html.index(b"</head>") html = html[:hloc] + css_bytes + b"\n" + html[hloc:] if html_heads: hloc = html.index(b"</head>") html = html[:hloc] + b"".join(html_heads) + b"\n" + html[hloc:] if html_bodies: hloc = html.index(b"</body>") html = html[:hloc] + b"".join(html_bodies) + b"\n" + html[hloc:] return self.finish(html)
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "\"Future[None]\"", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot render() after finish()\"", ")", "html", "=", "self", ".", "render_string", "(", "template_name", ",", "*", "*", "kwargs", ")", "# Insert the additional JS and CSS added by the modules on the page", "js_embed", "=", "[", "]", "js_files", "=", "[", "]", "css_embed", "=", "[", "]", "css_files", "=", "[", "]", "html_heads", "=", "[", "]", "html_bodies", "=", "[", "]", "for", "module", "in", "getattr", "(", "self", ",", "\"_active_modules\"", ",", "{", "}", ")", ".", "values", "(", ")", ":", "embed_part", "=", "module", ".", "embedded_javascript", "(", ")", "if", "embed_part", ":", "js_embed", ".", "append", "(", "utf8", "(", "embed_part", ")", ")", "file_part", "=", "module", ".", "javascript_files", "(", ")", "if", "file_part", ":", "if", "isinstance", "(", "file_part", ",", "(", "unicode_type", ",", "bytes", ")", ")", ":", "js_files", ".", "append", "(", "_unicode", "(", "file_part", ")", ")", "else", ":", "js_files", ".", "extend", "(", "file_part", ")", "embed_part", "=", "module", ".", "embedded_css", "(", ")", "if", "embed_part", ":", "css_embed", ".", "append", "(", "utf8", "(", "embed_part", ")", ")", "file_part", "=", "module", ".", "css_files", "(", ")", "if", "file_part", ":", "if", "isinstance", "(", "file_part", ",", "(", "unicode_type", ",", "bytes", ")", ")", ":", "css_files", ".", "append", "(", "_unicode", "(", "file_part", ")", ")", "else", ":", "css_files", ".", "extend", "(", "file_part", ")", "head_part", "=", "module", ".", "html_head", "(", ")", "if", "head_part", ":", "html_heads", ".", "append", "(", "utf8", "(", "head_part", ")", ")", "body_part", "=", "module", ".", "html_body", "(", ")", "if", "body_part", ":", "html_bodies", ".", "append", "(", "utf8", "(", "body_part", ")", ")", "if", "js_files", ":", "# Maintain order of JavaScript files given by modules", "js", "=", "self", ".", "render_linked_js", "(", "js_files", ")", "sloc", "=", "html", ".", "rindex", "(", "b\"</body>\"", ")", "html", "=", "html", "[", ":", "sloc", "]", "+", "utf8", "(", "js", ")", "+", "b\"\\n\"", "+", "html", "[", "sloc", ":", "]", "if", "js_embed", ":", "js_bytes", "=", "self", ".", "render_embed_js", "(", "js_embed", ")", "sloc", "=", "html", ".", "rindex", "(", "b\"</body>\"", ")", "html", "=", "html", "[", ":", "sloc", "]", "+", "js_bytes", "+", "b\"\\n\"", "+", "html", "[", "sloc", ":", "]", "if", "css_files", ":", "css", "=", "self", ".", "render_linked_css", "(", "css_files", ")", "hloc", "=", "html", ".", "index", "(", "b\"</head>\"", ")", "html", "=", "html", "[", ":", "hloc", "]", "+", "utf8", "(", "css", ")", "+", "b\"\\n\"", "+", "html", "[", "hloc", ":", "]", "if", "css_embed", ":", "css_bytes", "=", "self", ".", "render_embed_css", "(", "css_embed", ")", "hloc", "=", "html", ".", "index", "(", "b\"</head>\"", ")", "html", "=", "html", "[", ":", "hloc", "]", "+", "css_bytes", "+", "b\"\\n\"", "+", "html", "[", "hloc", ":", "]", "if", "html_heads", ":", "hloc", "=", "html", ".", "index", "(", "b\"</head>\"", ")", "html", "=", "html", "[", ":", "hloc", "]", "+", "b\"\"", ".", "join", "(", "html_heads", ")", "+", "b\"\\n\"", "+", "html", "[", "hloc", ":", "]", "if", "html_bodies", ":", "hloc", "=", "html", ".", "index", "(", "b\"</body>\"", ")", "html", "=", "html", "[", ":", "hloc", "]", "+", "b\"\"", ".", "join", "(", "html_bodies", ")", "+", "b\"\\n\"", "+", "html", "[", "hloc", ":", "]", "return", "self", ".", "finish", "(", "html", ")" ]
Renders the template with the given arguments as the response. ``render()`` calls ``finish()``, so no other output methods can be called after it. Returns a `.Future` with the same semantics as the one returned by `finish`. Awaiting this `.Future` is optional. .. versionchanged:: 5.1 Now returns a `.Future` instead of ``None``.
[ "Renders", "the", "template", "with", "the", "given", "arguments", "as", "the", "response", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L841-L914
26,724
tornadoweb/tornado
tornado/web.py
RequestHandler.render_linked_js
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] for path in js_files: if not is_absolute(path): path = self.static_url(path) if path not in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths )
python
def render_linked_js(self, js_files: Iterable[str]) -> str: """Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] for path in js_files: if not is_absolute(path): path = self.static_url(path) if path not in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<script src="' + escape.xhtml_escape(p) + '" type="text/javascript"></script>' for p in paths )
[ "def", "render_linked_js", "(", "self", ",", "js_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "js_files", ":", "if", "not", "is_absolute", "(", "path", ")", ":", "path", "=", "self", ".", "static_url", "(", "path", ")", "if", "path", "not", "in", "unique_paths", ":", "paths", ".", "append", "(", "path", ")", "unique_paths", ".", "add", "(", "path", ")", "return", "\"\"", ".", "join", "(", "'<script src=\"'", "+", "escape", ".", "xhtml_escape", "(", "p", ")", "+", "'\" type=\"text/javascript\"></script>'", "for", "p", "in", "paths", ")" ]
Default method used to render the final js links for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "js", "links", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L916-L937
26,725
tornadoweb/tornado
tornado/web.py
RequestHandler.render_embed_js
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<![CDATA[\n' + b"\n".join(js_embed) + b"\n//]]>\n</script>" )
python
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<![CDATA[\n' + b"\n".join(js_embed) + b"\n//]]>\n</script>" )
[ "def", "render_embed_js", "(", "self", ",", "js_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "(", "b'<script type=\"text/javascript\">\\n//<![CDATA[\\n'", "+", "b\"\\n\"", ".", "join", "(", "js_embed", ")", "+", "b\"\\n//]]>\\n</script>\"", ")" ]
Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "embedded", "js", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L939-L949
26,726
tornadoweb/tornado
tornado/web.py
RequestHandler.render_linked_css
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] for path in css_files: if not is_absolute(path): path = self.static_url(path) if path not in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<link href="' + escape.xhtml_escape(p) + '" ' 'type="text/css" rel="stylesheet"/>' for p in paths )
python
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] for path in css_files: if not is_absolute(path): path = self.static_url(path) if path not in unique_paths: paths.append(path) unique_paths.add(path) return "".join( '<link href="' + escape.xhtml_escape(p) + '" ' 'type="text/css" rel="stylesheet"/>' for p in paths )
[ "def", "render_linked_css", "(", "self", ",", "css_files", ":", "Iterable", "[", "str", "]", ")", "->", "str", ":", "paths", "=", "[", "]", "unique_paths", "=", "set", "(", ")", "# type: Set[str]", "for", "path", "in", "css_files", ":", "if", "not", "is_absolute", "(", "path", ")", ":", "path", "=", "self", ".", "static_url", "(", "path", ")", "if", "path", "not", "in", "unique_paths", ":", "paths", ".", "append", "(", "path", ")", "unique_paths", ".", "add", "(", "path", ")", "return", "\"\"", ".", "join", "(", "'<link href=\"'", "+", "escape", ".", "xhtml_escape", "(", "p", ")", "+", "'\" '", "'type=\"text/css\" rel=\"stylesheet\"/>'", "for", "p", "in", "paths", ")" ]
Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "css", "links", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L951-L971
26,727
tornadoweb/tornado
tornado/web.py
RequestHandler.render_embed_css
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>"
python
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>"
[ "def", "render_embed_css", "(", "self", ",", "css_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "b'<style type=\"text/css\">\\n'", "+", "b\"\\n\"", ".", "join", "(", "css_embed", ")", "+", "b\"\\n</style>\"" ]
Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output.
[ "Default", "method", "used", "to", "render", "the", "final", "embedded", "css", "for", "the", "rendered", "webpage", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L973-L979
26,728
tornadoweb/tornado
tornado/web.py
RequestHandler.render_string
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
python
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
[ "def", "render_string", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bytes", ":", "# If no template_path is specified, use the path of the calling file", "template_path", "=", "self", ".", "get_template_path", "(", ")", "if", "not", "template_path", ":", "frame", "=", "sys", ".", "_getframe", "(", "0", ")", "web_file", "=", "frame", ".", "f_code", ".", "co_filename", "while", "frame", ".", "f_code", ".", "co_filename", "==", "web_file", ":", "frame", "=", "frame", ".", "f_back", "assert", "frame", ".", "f_code", ".", "co_filename", "is", "not", "None", "template_path", "=", "os", ".", "path", ".", "dirname", "(", "frame", ".", "f_code", ".", "co_filename", ")", "with", "RequestHandler", ".", "_template_loader_lock", ":", "if", "template_path", "not", "in", "RequestHandler", ".", "_template_loaders", ":", "loader", "=", "self", ".", "create_template_loader", "(", "template_path", ")", "RequestHandler", ".", "_template_loaders", "[", "template_path", "]", "=", "loader", "else", ":", "loader", "=", "RequestHandler", ".", "_template_loaders", "[", "template_path", "]", "t", "=", "loader", ".", "load", "(", "template_name", ")", "namespace", "=", "self", ".", "get_template_namespace", "(", ")", "namespace", ".", "update", "(", "kwargs", ")", "return", "t", ".", "generate", "(", "*", "*", "namespace", ")" ]
Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
[ "Generate", "the", "given", "template", "with", "the", "given", "arguments", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L981-L1005
26,729
tornadoweb/tornado
tornado/web.py
RequestHandler.get_template_namespace
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`. """ namespace = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, pgettext=self.locale.pgettext, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.reverse_url, ) namespace.update(self.ui) return namespace
python
def get_template_namespace(self) -> Dict[str, Any]: """Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`. """ namespace = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, pgettext=self.locale.pgettext, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.reverse_url, ) namespace.update(self.ui) return namespace
[ "def", "get_template_namespace", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "namespace", "=", "dict", "(", "handler", "=", "self", ",", "request", "=", "self", ".", "request", ",", "current_user", "=", "self", ".", "current_user", ",", "locale", "=", "self", ".", "locale", ",", "_", "=", "self", ".", "locale", ".", "translate", ",", "pgettext", "=", "self", ".", "locale", ".", "pgettext", ",", "static_url", "=", "self", ".", "static_url", ",", "xsrf_form_html", "=", "self", ".", "xsrf_form_html", ",", "reverse_url", "=", "self", ".", "reverse_url", ",", ")", "namespace", ".", "update", "(", "self", ".", "ui", ")", "return", "namespace" ]
Returns a dictionary to be used as the default template namespace. May be overridden by subclasses to add or modify values. The results of this method will be combined with additional defaults in the `tornado.template` module and keyword arguments to `render` or `render_string`.
[ "Returns", "a", "dictionary", "to", "be", "used", "as", "the", "default", "template", "namespace", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1007-L1028
26,730
tornadoweb/tornado
tornado/web.py
RequestHandler.create_template_loader
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead. """ settings = self.application.settings if "template_loader" in settings: return settings["template_loader"] kwargs = {} if "autoescape" in settings: # autoescape=None means "no escaping", so we have to be sure # to only pass this kwarg if the user asked for it. kwargs["autoescape"] = settings["autoescape"] if "template_whitespace" in settings: kwargs["whitespace"] = settings["template_whitespace"] return template.Loader(template_path, **kwargs)
python
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead. """ settings = self.application.settings if "template_loader" in settings: return settings["template_loader"] kwargs = {} if "autoescape" in settings: # autoescape=None means "no escaping", so we have to be sure # to only pass this kwarg if the user asked for it. kwargs["autoescape"] = settings["autoescape"] if "template_whitespace" in settings: kwargs["whitespace"] = settings["template_whitespace"] return template.Loader(template_path, **kwargs)
[ "def", "create_template_loader", "(", "self", ",", "template_path", ":", "str", ")", "->", "template", ".", "BaseLoader", ":", "settings", "=", "self", ".", "application", ".", "settings", "if", "\"template_loader\"", "in", "settings", ":", "return", "settings", "[", "\"template_loader\"", "]", "kwargs", "=", "{", "}", "if", "\"autoescape\"", "in", "settings", ":", "# autoescape=None means \"no escaping\", so we have to be sure", "# to only pass this kwarg if the user asked for it.", "kwargs", "[", "\"autoescape\"", "]", "=", "settings", "[", "\"autoescape\"", "]", "if", "\"template_whitespace\"", "in", "settings", ":", "kwargs", "[", "\"whitespace\"", "]", "=", "settings", "[", "\"template_whitespace\"", "]", "return", "template", ".", "Loader", "(", "template_path", ",", "*", "*", "kwargs", ")" ]
Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead.
[ "Returns", "a", "new", "template", "loader", "for", "the", "given", "path", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1030-L1049
26,731
tornadoweb/tornado
tornado/web.py
RequestHandler.flush
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ assert self.request.connection is not None chunk = b"".join(self._write_buffer) self._write_buffer = [] if not self._headers_written: self._headers_written = True for transform in self._transforms: assert chunk is not None self._status_code, self._headers, chunk = transform.transform_first_chunk( self._status_code, self._headers, chunk, include_footers ) # Ignore the chunk and only write the headers for HEAD requests if self.request.method == "HEAD": chunk = b"" # Finalize the cookie headers (which have been stored in a side # object so an outgoing cookie could be overwritten before it # is sent). if hasattr(self, "_new_cookie"): for cookie in self._new_cookie.values(): self.add_header("Set-Cookie", cookie.OutputString(None)) start_line = httputil.ResponseStartLine("", self._status_code, self._reason) return self.request.connection.write_headers( start_line, self._headers, chunk ) else: for transform in self._transforms: chunk = transform.transform_chunk(chunk, include_footers) # Ignore the chunk and only write the headers for HEAD requests if self.request.method != "HEAD": return self.request.connection.write(chunk) else: future = Future() # type: Future[None] future.set_result(None) return future
python
def flush(self, include_footers: bool = False) -> "Future[None]": """Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed. """ assert self.request.connection is not None chunk = b"".join(self._write_buffer) self._write_buffer = [] if not self._headers_written: self._headers_written = True for transform in self._transforms: assert chunk is not None self._status_code, self._headers, chunk = transform.transform_first_chunk( self._status_code, self._headers, chunk, include_footers ) # Ignore the chunk and only write the headers for HEAD requests if self.request.method == "HEAD": chunk = b"" # Finalize the cookie headers (which have been stored in a side # object so an outgoing cookie could be overwritten before it # is sent). if hasattr(self, "_new_cookie"): for cookie in self._new_cookie.values(): self.add_header("Set-Cookie", cookie.OutputString(None)) start_line = httputil.ResponseStartLine("", self._status_code, self._reason) return self.request.connection.write_headers( start_line, self._headers, chunk ) else: for transform in self._transforms: chunk = transform.transform_chunk(chunk, include_footers) # Ignore the chunk and only write the headers for HEAD requests if self.request.method != "HEAD": return self.request.connection.write(chunk) else: future = Future() # type: Future[None] future.set_result(None) return future
[ "def", "flush", "(", "self", ",", "include_footers", ":", "bool", "=", "False", ")", "->", "\"Future[None]\"", ":", "assert", "self", ".", "request", ".", "connection", "is", "not", "None", "chunk", "=", "b\"\"", ".", "join", "(", "self", ".", "_write_buffer", ")", "self", ".", "_write_buffer", "=", "[", "]", "if", "not", "self", ".", "_headers_written", ":", "self", ".", "_headers_written", "=", "True", "for", "transform", "in", "self", ".", "_transforms", ":", "assert", "chunk", "is", "not", "None", "self", ".", "_status_code", ",", "self", ".", "_headers", ",", "chunk", "=", "transform", ".", "transform_first_chunk", "(", "self", ".", "_status_code", ",", "self", ".", "_headers", ",", "chunk", ",", "include_footers", ")", "# Ignore the chunk and only write the headers for HEAD requests", "if", "self", ".", "request", ".", "method", "==", "\"HEAD\"", ":", "chunk", "=", "b\"\"", "# Finalize the cookie headers (which have been stored in a side", "# object so an outgoing cookie could be overwritten before it", "# is sent).", "if", "hasattr", "(", "self", ",", "\"_new_cookie\"", ")", ":", "for", "cookie", "in", "self", ".", "_new_cookie", ".", "values", "(", ")", ":", "self", ".", "add_header", "(", "\"Set-Cookie\"", ",", "cookie", ".", "OutputString", "(", "None", ")", ")", "start_line", "=", "httputil", ".", "ResponseStartLine", "(", "\"\"", ",", "self", ".", "_status_code", ",", "self", ".", "_reason", ")", "return", "self", ".", "request", ".", "connection", ".", "write_headers", "(", "start_line", ",", "self", ".", "_headers", ",", "chunk", ")", "else", ":", "for", "transform", "in", "self", ".", "_transforms", ":", "chunk", "=", "transform", ".", "transform_chunk", "(", "chunk", ",", "include_footers", ")", "# Ignore the chunk and only write the headers for HEAD requests", "if", "self", ".", "request", ".", "method", "!=", "\"HEAD\"", ":", "return", "self", ".", "request", ".", "connection", ".", "write", "(", "chunk", ")", "else", ":", "future", "=", "Future", "(", ")", "# type: Future[None]", "future", ".", "set_result", "(", "None", ")", "return", "future" ]
Flushes the current output buffer to the network. The ``callback`` argument, if given, can be used for flow control: it will be run when all flushed data has been written to the socket. Note that only one flush callback can be outstanding at a time; if another flush occurs before the previous flush's callback has been run, the previous callback will be discarded. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 6.0 The ``callback`` argument was removed.
[ "Flushes", "the", "current", "output", "buffer", "to", "the", "network", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1051-L1101
26,732
tornadoweb/tornado
tornado/web.py
RequestHandler.send_error
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`. """ if self._headers_written: gen_log.error("Cannot send error response after headers written") if not self._finished: # If we get an error between writing headers and finishing, # we are unlikely to be able to finish due to a # Content-Length mismatch. Try anyway to release the # socket. try: self.finish() except Exception: gen_log.error("Failed to flush partial response", exc_info=True) return self.clear() reason = kwargs.get("reason") if "exc_info" in kwargs: exception = kwargs["exc_info"][1] if isinstance(exception, HTTPError) and exception.reason: reason = exception.reason self.set_status(status_code, reason=reason) try: self.write_error(status_code, **kwargs) except Exception: app_log.error("Uncaught exception in write_error", exc_info=True) if not self._finished: self.finish()
python
def send_error(self, status_code: int = 500, **kwargs: Any) -> None: """Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`. """ if self._headers_written: gen_log.error("Cannot send error response after headers written") if not self._finished: # If we get an error between writing headers and finishing, # we are unlikely to be able to finish due to a # Content-Length mismatch. Try anyway to release the # socket. try: self.finish() except Exception: gen_log.error("Failed to flush partial response", exc_info=True) return self.clear() reason = kwargs.get("reason") if "exc_info" in kwargs: exception = kwargs["exc_info"][1] if isinstance(exception, HTTPError) and exception.reason: reason = exception.reason self.set_status(status_code, reason=reason) try: self.write_error(status_code, **kwargs) except Exception: app_log.error("Uncaught exception in write_error", exc_info=True) if not self._finished: self.finish()
[ "def", "send_error", "(", "self", ",", "status_code", ":", "int", "=", "500", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "_headers_written", ":", "gen_log", ".", "error", "(", "\"Cannot send error response after headers written\"", ")", "if", "not", "self", ".", "_finished", ":", "# If we get an error between writing headers and finishing,", "# we are unlikely to be able to finish due to a", "# Content-Length mismatch. Try anyway to release the", "# socket.", "try", ":", "self", ".", "finish", "(", ")", "except", "Exception", ":", "gen_log", ".", "error", "(", "\"Failed to flush partial response\"", ",", "exc_info", "=", "True", ")", "return", "self", ".", "clear", "(", ")", "reason", "=", "kwargs", ".", "get", "(", "\"reason\"", ")", "if", "\"exc_info\"", "in", "kwargs", ":", "exception", "=", "kwargs", "[", "\"exc_info\"", "]", "[", "1", "]", "if", "isinstance", "(", "exception", ",", "HTTPError", ")", "and", "exception", ".", "reason", ":", "reason", "=", "exception", ".", "reason", "self", ".", "set_status", "(", "status_code", ",", "reason", "=", "reason", ")", "try", ":", "self", ".", "write_error", "(", "status_code", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "app_log", ".", "error", "(", "\"Uncaught exception in write_error\"", ",", "exc_info", "=", "True", ")", "if", "not", "self", ".", "_finished", ":", "self", ".", "finish", "(", ")" ]
Sends the given HTTP error code to the browser. If `flush()` has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page. Override `write_error()` to customize the error page that is returned. Additional keyword arguments are passed through to `write_error`.
[ "Sends", "the", "given", "HTTP", "error", "code", "to", "the", "browser", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1182-L1218
26,733
tornadoweb/tornado
tornado/web.py
RequestHandler.write_error
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback self.set_header("Content-Type", "text/plain") for line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish( "<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % {"code": status_code, "message": self._reason} )
python
def write_error(self, status_code: int, **kwargs: Any) -> None: """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback self.set_header("Content-Type", "text/plain") for line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish( "<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % {"code": status_code, "message": self._reason} )
[ "def", "write_error", "(", "self", ",", "status_code", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "settings", ".", "get", "(", "\"serve_traceback\"", ")", "and", "\"exc_info\"", "in", "kwargs", ":", "# in debug mode, try to send a traceback", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"text/plain\"", ")", "for", "line", "in", "traceback", ".", "format_exception", "(", "*", "kwargs", "[", "\"exc_info\"", "]", ")", ":", "self", ".", "write", "(", "line", ")", "self", ".", "finish", "(", ")", "else", ":", "self", ".", "finish", "(", "\"<html><title>%(code)d: %(message)s</title>\"", "\"<body>%(code)d: %(message)s</body></html>\"", "%", "{", "\"code\"", ":", "status_code", ",", "\"message\"", ":", "self", ".", "_reason", "}", ")" ]
Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``.
[ "Override", "to", "implement", "custom", "error", "pages", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1220-L1243
26,734
tornadoweb/tornado
tornado/web.py
RequestHandler.locale
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter. """ if not hasattr(self, "_locale"): loc = self.get_user_locale() if loc is not None: self._locale = loc else: self._locale = self.get_browser_locale() assert self._locale return self._locale
python
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter. """ if not hasattr(self, "_locale"): loc = self.get_user_locale() if loc is not None: self._locale = loc else: self._locale = self.get_browser_locale() assert self._locale return self._locale
[ "def", "locale", "(", "self", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "not", "hasattr", "(", "self", ",", "\"_locale\"", ")", ":", "loc", "=", "self", ".", "get_user_locale", "(", ")", "if", "loc", "is", "not", "None", ":", "self", ".", "_locale", "=", "loc", "else", ":", "self", ".", "_locale", "=", "self", ".", "get_browser_locale", "(", ")", "assert", "self", ".", "_locale", "return", "self", ".", "_locale" ]
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter.
[ "The", "locale", "for", "the", "current", "session", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1246-L1264
26,735
tornadoweb/tornado
tornado/web.py
RequestHandler.get_browser_locale
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 locales.append((parts[0], score)) if locales: locales.sort(key=lambda pair: pair[1], reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)
python
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale: """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 locales.append((parts[0], score)) if locales: locales.sort(key=lambda pair: pair[1], reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)
[ "def", "get_browser_locale", "(", "self", ",", "default", ":", "str", "=", "\"en_US\"", ")", "->", "tornado", ".", "locale", ".", "Locale", ":", "if", "\"Accept-Language\"", "in", "self", ".", "request", ".", "headers", ":", "languages", "=", "self", ".", "request", ".", "headers", "[", "\"Accept-Language\"", "]", ".", "split", "(", "\",\"", ")", "locales", "=", "[", "]", "for", "language", "in", "languages", ":", "parts", "=", "language", ".", "strip", "(", ")", ".", "split", "(", "\";\"", ")", "if", "len", "(", "parts", ")", ">", "1", "and", "parts", "[", "1", "]", ".", "startswith", "(", "\"q=\"", ")", ":", "try", ":", "score", "=", "float", "(", "parts", "[", "1", "]", "[", "2", ":", "]", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "score", "=", "0.0", "else", ":", "score", "=", "1.0", "locales", ".", "append", "(", "(", "parts", "[", "0", "]", ",", "score", ")", ")", "if", "locales", ":", "locales", ".", "sort", "(", "key", "=", "lambda", "pair", ":", "pair", "[", "1", "]", ",", "reverse", "=", "True", ")", "codes", "=", "[", "l", "[", "0", "]", "for", "l", "in", "locales", "]", "return", "locale", ".", "get", "(", "*", "codes", ")", "return", "locale", ".", "get", "(", "default", ")" ]
Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
[ "Determines", "the", "user", "s", "locale", "from", "Accept", "-", "Language", "header", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1280-L1302
26,736
tornadoweb/tornado
tornado/web.py
RequestHandler.current_user
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing. """ if not hasattr(self, "_current_user"): self._current_user = self.get_current_user() return self._current_user
python
def current_user(self) -> Any: """The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing. """ if not hasattr(self, "_current_user"): self._current_user = self.get_current_user() return self._current_user
[ "def", "current_user", "(", "self", ")", "->", "Any", ":", "if", "not", "hasattr", "(", "self", ",", "\"_current_user\"", ")", ":", "self", ".", "_current_user", "=", "self", ".", "get_current_user", "(", ")", "return", "self", ".", "_current_user" ]
The authenticated user for this request. This is set in one of two ways: * A subclass may override `get_current_user()`, which will be called automatically the first time ``self.current_user`` is accessed. `get_current_user()` will only be called once per request, and is cached for future access:: def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None * It may be set as a normal variable, typically from an overridden `prepare()`:: @gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie) Note that `prepare()` may be a coroutine while `get_current_user()` may not, so the latter form is necessary if loading the user requires asynchronous operations. The user object may be any type of the application's choosing.
[ "The", "authenticated", "user", "for", "this", "request", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L1305-L1338
26,737
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
26,738
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
26,739
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
26,740
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
26,741
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
26,742
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
26,743
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
26,744
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
26,745
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
26,746
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
26,747
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
26,748
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
26,749
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
26,750
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
26,751
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
26,752
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
26,753
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
26,754
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
26,755
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
26,756
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
26,757
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
26,758
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
26,759
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
26,760
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
26,761
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
26,762
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
26,763
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
26,764
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
26,765
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
26,766
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
26,767
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
26,768
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
26,769
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
26,770
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
26,771
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
26,772
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
26,773
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
26,774
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
26,775
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
26,776
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
26,777
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
26,778
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
26,779
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
26,780
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
26,781
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
26,782
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
26,783
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
26,784
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
26,785
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
26,786
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
26,787
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
26,788
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
26,789
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
26,790
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
26,791
tornadoweb/tornado
tornado/iostream.py
_StreamBuffer.advance
def advance(self, size: int) -> None: """ Advance the current buffer position by ``size`` bytes. """ assert 0 < size <= self._size self._size -= size pos = self._first_pos buffers = self._buffers while buffers and size > 0: is_large, b = buffers[0] b_remain = len(b) - size - pos if b_remain <= 0: buffers.popleft() size -= len(b) - pos pos = 0 elif is_large: pos += size size = 0 else: # Amortized O(1) shrink for Python 2 pos += size if len(b) <= 2 * pos: del typing.cast(bytearray, b)[:pos] pos = 0 size = 0 assert size == 0 self._first_pos = pos
python
def advance(self, size: int) -> None: """ Advance the current buffer position by ``size`` bytes. """ assert 0 < size <= self._size self._size -= size pos = self._first_pos buffers = self._buffers while buffers and size > 0: is_large, b = buffers[0] b_remain = len(b) - size - pos if b_remain <= 0: buffers.popleft() size -= len(b) - pos pos = 0 elif is_large: pos += size size = 0 else: # Amortized O(1) shrink for Python 2 pos += size if len(b) <= 2 * pos: del typing.cast(bytearray, b)[:pos] pos = 0 size = 0 assert size == 0 self._first_pos = pos
[ "def", "advance", "(", "self", ",", "size", ":", "int", ")", "->", "None", ":", "assert", "0", "<", "size", "<=", "self", ".", "_size", "self", ".", "_size", "-=", "size", "pos", "=", "self", ".", "_first_pos", "buffers", "=", "self", ".", "_buffers", "while", "buffers", "and", "size", ">", "0", ":", "is_large", ",", "b", "=", "buffers", "[", "0", "]", "b_remain", "=", "len", "(", "b", ")", "-", "size", "-", "pos", "if", "b_remain", "<=", "0", ":", "buffers", ".", "popleft", "(", ")", "size", "-=", "len", "(", "b", ")", "-", "pos", "pos", "=", "0", "elif", "is_large", ":", "pos", "+=", "size", "size", "=", "0", "else", ":", "# Amortized O(1) shrink for Python 2", "pos", "+=", "size", "if", "len", "(", "b", ")", "<=", "2", "*", "pos", ":", "del", "typing", ".", "cast", "(", "bytearray", ",", "b", ")", "[", ":", "pos", "]", "pos", "=", "0", "size", "=", "0", "assert", "size", "==", "0", "self", ".", "_first_pos", "=", "pos" ]
Advance the current buffer position by ``size`` bytes.
[ "Advance", "the", "current", "buffer", "position", "by", "size", "bytes", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L198-L226
26,792
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.read_until_regex
def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]: """Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ future = self._start_read() self._read_regex = re.compile(regex) self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=e) return future except: # Ensure that the future doesn't log an error because its # failure was never examined. future.add_done_callback(lambda f: f.exception()) raise return future
python
def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]: """Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ future = self._start_read() self._read_regex = re.compile(regex) self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=e) return future except: # Ensure that the future doesn't log an error because its # failure was never examined. future.add_done_callback(lambda f: f.exception()) raise return future
[ "def", "read_until_regex", "(", "self", ",", "regex", ":", "bytes", ",", "max_bytes", ":", "int", "=", "None", ")", "->", "Awaitable", "[", "bytes", "]", ":", "future", "=", "self", ".", "_start_read", "(", ")", "self", ".", "_read_regex", "=", "re", ".", "compile", "(", "regex", ")", "self", ".", "_read_max_bytes", "=", "max_bytes", "try", ":", "self", ".", "_try_inline_read", "(", ")", "except", "UnsatisfiableReadError", "as", "e", ":", "# Handle this the same way as in _handle_events.", "gen_log", ".", "info", "(", "\"Unsatisfiable read, closing connection: %s\"", "%", "e", ")", "self", ".", "close", "(", "exc_info", "=", "e", ")", "return", "future", "except", ":", "# Ensure that the future doesn't log an error because its", "# failure was never examined.", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "f", ".", "exception", "(", ")", ")", "raise", "return", "future" ]
Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
[ "Asynchronously", "read", "until", "we", "have", "matched", "the", "given", "regex", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L349-L384
26,793
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.read_until
def read_until(self, delimiter: bytes, max_bytes: int = None) -> Awaitable[bytes]: """Asynchronously read until we have found the given delimiter. The result includes all the data read including the delimiter. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the delimiter is not found. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ future = self._start_read() self._read_delimiter = delimiter self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=e) return future except: future.add_done_callback(lambda f: f.exception()) raise return future
python
def read_until(self, delimiter: bytes, max_bytes: int = None) -> Awaitable[bytes]: """Asynchronously read until we have found the given delimiter. The result includes all the data read including the delimiter. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the delimiter is not found. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ future = self._start_read() self._read_delimiter = delimiter self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=e) return future except: future.add_done_callback(lambda f: f.exception()) raise return future
[ "def", "read_until", "(", "self", ",", "delimiter", ":", "bytes", ",", "max_bytes", ":", "int", "=", "None", ")", "->", "Awaitable", "[", "bytes", "]", ":", "future", "=", "self", ".", "_start_read", "(", ")", "self", ".", "_read_delimiter", "=", "delimiter", "self", ".", "_read_max_bytes", "=", "max_bytes", "try", ":", "self", ".", "_try_inline_read", "(", ")", "except", "UnsatisfiableReadError", "as", "e", ":", "# Handle this the same way as in _handle_events.", "gen_log", ".", "info", "(", "\"Unsatisfiable read, closing connection: %s\"", "%", "e", ")", "self", ".", "close", "(", "exc_info", "=", "e", ")", "return", "future", "except", ":", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "f", ".", "exception", "(", ")", ")", "raise", "return", "future" ]
Asynchronously read until we have found the given delimiter. The result includes all the data read including the delimiter. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the delimiter is not found. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
[ "Asynchronously", "read", "until", "we", "have", "found", "the", "given", "delimiter", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L386-L417
26,794
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.read_until_close
def read_until_close(self) -> Awaitable[bytes]: """Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` and ``streaming_callback`` arguments have been removed. Use the returned `.Future` (and `read_bytes` with ``partial=True`` for ``streaming_callback``) instead. """ future = self._start_read() if self.closed(): self._finish_read(self._read_buffer_size, False) return future self._read_until_close = True try: self._try_inline_read() except: future.add_done_callback(lambda f: f.exception()) raise return future
python
def read_until_close(self) -> Awaitable[bytes]: """Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` and ``streaming_callback`` arguments have been removed. Use the returned `.Future` (and `read_bytes` with ``partial=True`` for ``streaming_callback``) instead. """ future = self._start_read() if self.closed(): self._finish_read(self._read_buffer_size, False) return future self._read_until_close = True try: self._try_inline_read() except: future.add_done_callback(lambda f: f.exception()) raise return future
[ "def", "read_until_close", "(", "self", ")", "->", "Awaitable", "[", "bytes", "]", ":", "future", "=", "self", ".", "_start_read", "(", ")", "if", "self", ".", "closed", "(", ")", ":", "self", ".", "_finish_read", "(", "self", ".", "_read_buffer_size", ",", "False", ")", "return", "future", "self", ".", "_read_until_close", "=", "True", "try", ":", "self", ".", "_try_inline_read", "(", ")", "except", ":", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "f", ".", "exception", "(", ")", ")", "raise", "return", "future" ]
Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` and ``streaming_callback`` arguments have been removed. Use the returned `.Future` (and `read_bytes` with ``partial=True`` for ``streaming_callback``) instead.
[ "Asynchronously", "reads", "all", "data", "from", "the", "socket", "until", "it", "is", "closed", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L496-L524
26,795
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.write
def write(self, data: Union[bytes, memoryview]) -> "Future[None]": """Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 4.5 Added support for `memoryview` arguments. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ self._check_closed() if data: if ( self.max_write_buffer_size is not None and len(self._write_buffer) + len(data) > self.max_write_buffer_size ): raise StreamBufferFullError("Reached maximum write buffer size") self._write_buffer.append(data) self._total_write_index += len(data) future = Future() # type: Future[None] future.add_done_callback(lambda f: f.exception()) self._write_futures.append((self._total_write_index, future)) if not self._connecting: self._handle_write() if self._write_buffer: self._add_io_state(self.io_loop.WRITE) self._maybe_add_error_listener() return future
python
def write(self, data: Union[bytes, memoryview]) -> "Future[None]": """Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 4.5 Added support for `memoryview` arguments. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead. """ self._check_closed() if data: if ( self.max_write_buffer_size is not None and len(self._write_buffer) + len(data) > self.max_write_buffer_size ): raise StreamBufferFullError("Reached maximum write buffer size") self._write_buffer.append(data) self._total_write_index += len(data) future = Future() # type: Future[None] future.add_done_callback(lambda f: f.exception()) self._write_futures.append((self._total_write_index, future)) if not self._connecting: self._handle_write() if self._write_buffer: self._add_io_state(self.io_loop.WRITE) self._maybe_add_error_listener() return future
[ "def", "write", "(", "self", ",", "data", ":", "Union", "[", "bytes", ",", "memoryview", "]", ")", "->", "\"Future[None]\"", ":", "self", ".", "_check_closed", "(", ")", "if", "data", ":", "if", "(", "self", ".", "max_write_buffer_size", "is", "not", "None", "and", "len", "(", "self", ".", "_write_buffer", ")", "+", "len", "(", "data", ")", ">", "self", ".", "max_write_buffer_size", ")", ":", "raise", "StreamBufferFullError", "(", "\"Reached maximum write buffer size\"", ")", "self", ".", "_write_buffer", ".", "append", "(", "data", ")", "self", ".", "_total_write_index", "+=", "len", "(", "data", ")", "future", "=", "Future", "(", ")", "# type: Future[None]", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "f", ".", "exception", "(", ")", ")", "self", ".", "_write_futures", ".", "append", "(", "(", "self", ".", "_total_write_index", ",", "future", ")", ")", "if", "not", "self", ".", "_connecting", ":", "self", ".", "_handle_write", "(", ")", "if", "self", ".", "_write_buffer", ":", "self", ".", "_add_io_state", "(", "self", ".", "io_loop", ".", "WRITE", ")", "self", ".", "_maybe_add_error_listener", "(", ")", "return", "future" ]
Asynchronously write the given data to this stream. This method returns a `.Future` that resolves (with a result of ``None``) when the write has been completed. The ``data`` argument may be of type `bytes` or `memoryview`. .. versionchanged:: 4.0 Now returns a `.Future` if no callback is given. .. versionchanged:: 4.5 Added support for `memoryview` arguments. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned `.Future` instead.
[ "Asynchronously", "write", "the", "given", "data", "to", "this", "stream", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L526-L563
26,796
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.set_close_callback
def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None: """Call the given callback when the stream is closed. This mostly is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed. However, it is still useful as a way to signal that the stream has been closed while no other read or write is in progress. Unlike other callback-based interfaces, ``set_close_callback`` was not removed in Tornado 6.0. """ self._close_callback = callback self._maybe_add_error_listener()
python
def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None: """Call the given callback when the stream is closed. This mostly is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed. However, it is still useful as a way to signal that the stream has been closed while no other read or write is in progress. Unlike other callback-based interfaces, ``set_close_callback`` was not removed in Tornado 6.0. """ self._close_callback = callback self._maybe_add_error_listener()
[ "def", "set_close_callback", "(", "self", ",", "callback", ":", "Optional", "[", "Callable", "[", "[", "]", ",", "None", "]", "]", ")", "->", "None", ":", "self", ".", "_close_callback", "=", "callback", "self", ".", "_maybe_add_error_listener", "(", ")" ]
Call the given callback when the stream is closed. This mostly is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when the stream is closed. However, it is still useful as a way to signal that the stream has been closed while no other read or write is in progress. Unlike other callback-based interfaces, ``set_close_callback`` was not removed in Tornado 6.0.
[ "Call", "the", "given", "callback", "when", "the", "stream", "is", "closed", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L565-L578
26,797
tornadoweb/tornado
tornado/iostream.py
BaseIOStream.close
def close( self, exc_info: Union[ None, bool, BaseException, Tuple[ "Optional[Type[BaseException]]", Optional[BaseException], Optional[TracebackType], ], ] = False, ) -> None: """Close this stream. If ``exc_info`` is true, set the ``error`` attribute to the current exception from `sys.exc_info` (or if ``exc_info`` is a tuple, use that instead of `sys.exc_info`). """ if not self.closed(): if exc_info: if isinstance(exc_info, tuple): self.error = exc_info[1] elif isinstance(exc_info, BaseException): self.error = exc_info else: exc_info = sys.exc_info() if any(exc_info): self.error = exc_info[1] if self._read_until_close: self._read_until_close = False self._finish_read(self._read_buffer_size, False) if self._state is not None: self.io_loop.remove_handler(self.fileno()) self._state = None self.close_fd() self._closed = True self._signal_closed()
python
def close( self, exc_info: Union[ None, bool, BaseException, Tuple[ "Optional[Type[BaseException]]", Optional[BaseException], Optional[TracebackType], ], ] = False, ) -> None: """Close this stream. If ``exc_info`` is true, set the ``error`` attribute to the current exception from `sys.exc_info` (or if ``exc_info`` is a tuple, use that instead of `sys.exc_info`). """ if not self.closed(): if exc_info: if isinstance(exc_info, tuple): self.error = exc_info[1] elif isinstance(exc_info, BaseException): self.error = exc_info else: exc_info = sys.exc_info() if any(exc_info): self.error = exc_info[1] if self._read_until_close: self._read_until_close = False self._finish_read(self._read_buffer_size, False) if self._state is not None: self.io_loop.remove_handler(self.fileno()) self._state = None self.close_fd() self._closed = True self._signal_closed()
[ "def", "close", "(", "self", ",", "exc_info", ":", "Union", "[", "None", ",", "bool", ",", "BaseException", ",", "Tuple", "[", "\"Optional[Type[BaseException]]\"", ",", "Optional", "[", "BaseException", "]", ",", "Optional", "[", "TracebackType", "]", ",", "]", ",", "]", "=", "False", ",", ")", "->", "None", ":", "if", "not", "self", ".", "closed", "(", ")", ":", "if", "exc_info", ":", "if", "isinstance", "(", "exc_info", ",", "tuple", ")", ":", "self", ".", "error", "=", "exc_info", "[", "1", "]", "elif", "isinstance", "(", "exc_info", ",", "BaseException", ")", ":", "self", ".", "error", "=", "exc_info", "else", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "any", "(", "exc_info", ")", ":", "self", ".", "error", "=", "exc_info", "[", "1", "]", "if", "self", ".", "_read_until_close", ":", "self", ".", "_read_until_close", "=", "False", "self", ".", "_finish_read", "(", "self", ".", "_read_buffer_size", ",", "False", ")", "if", "self", ".", "_state", "is", "not", "None", ":", "self", ".", "io_loop", ".", "remove_handler", "(", "self", ".", "fileno", "(", ")", ")", "self", ".", "_state", "=", "None", "self", ".", "close_fd", "(", ")", "self", ".", "_closed", "=", "True", "self", ".", "_signal_closed", "(", ")" ]
Close this stream. If ``exc_info`` is true, set the ``error`` attribute to the current exception from `sys.exc_info` (or if ``exc_info`` is a tuple, use that instead of `sys.exc_info`).
[ "Close", "this", "stream", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L580-L617
26,798
tornadoweb/tornado
tornado/iostream.py
BaseIOStream._try_inline_read
def _try_inline_read(self) -> None: """Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket. """ # See if we've already got the data from a previous read pos = self._find_read_pos() if pos is not None: self._read_from_buffer(pos) return self._check_closed() pos = self._read_to_buffer_loop() if pos is not None: self._read_from_buffer(pos) return # We couldn't satisfy the read inline, so make sure we're # listening for new data unless the stream is closed. if not self.closed(): self._add_io_state(ioloop.IOLoop.READ)
python
def _try_inline_read(self) -> None: """Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket. """ # See if we've already got the data from a previous read pos = self._find_read_pos() if pos is not None: self._read_from_buffer(pos) return self._check_closed() pos = self._read_to_buffer_loop() if pos is not None: self._read_from_buffer(pos) return # We couldn't satisfy the read inline, so make sure we're # listening for new data unless the stream is closed. if not self.closed(): self._add_io_state(ioloop.IOLoop.READ)
[ "def", "_try_inline_read", "(", "self", ")", "->", "None", ":", "# See if we've already got the data from a previous read", "pos", "=", "self", ".", "_find_read_pos", "(", ")", "if", "pos", "is", "not", "None", ":", "self", ".", "_read_from_buffer", "(", "pos", ")", "return", "self", ".", "_check_closed", "(", ")", "pos", "=", "self", ".", "_read_to_buffer_loop", "(", ")", "if", "pos", "is", "not", "None", ":", "self", ".", "_read_from_buffer", "(", "pos", ")", "return", "# We couldn't satisfy the read inline, so make sure we're", "# listening for new data unless the stream is closed.", "if", "not", "self", ".", "closed", "(", ")", ":", "self", ".", "_add_io_state", "(", "ioloop", ".", "IOLoop", ".", "READ", ")" ]
Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket.
[ "Attempt", "to", "complete", "the", "current", "read", "operation", "from", "buffered", "data", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L817-L837
26,799
tornadoweb/tornado
tornado/iostream.py
BaseIOStream._read_to_buffer
def _read_to_buffer(self) -> Optional[int]: """Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception. """ try: while True: try: if self._user_read_buffer: buf = memoryview(self._read_buffer)[ self._read_buffer_size : ] # type: Union[memoryview, bytearray] else: buf = bytearray(self.read_chunk_size) bytes_read = self.read_from_fd(buf) except (socket.error, IOError, OSError) as e: if errno_from_exception(e) == errno.EINTR: continue # ssl.SSLError is a subclass of socket.error if self._is_connreset(e): # Treat ECONNRESET as a connection close rather than # an error to minimize log spam (the exception will # be available on self.error for apps that care). self.close(exc_info=e) return None self.close(exc_info=e) raise break if bytes_read is None: return 0 elif bytes_read == 0: self.close() return 0 if not self._user_read_buffer: self._read_buffer += memoryview(buf)[:bytes_read] self._read_buffer_size += bytes_read finally: # Break the reference to buf so we don't waste a chunk's worth of # memory in case an exception hangs on to our stack frame. del buf if self._read_buffer_size > self.max_buffer_size: gen_log.error("Reached maximum read buffer size") self.close() raise StreamBufferFullError("Reached maximum read buffer size") return bytes_read
python
def _read_to_buffer(self) -> Optional[int]: """Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception. """ try: while True: try: if self._user_read_buffer: buf = memoryview(self._read_buffer)[ self._read_buffer_size : ] # type: Union[memoryview, bytearray] else: buf = bytearray(self.read_chunk_size) bytes_read = self.read_from_fd(buf) except (socket.error, IOError, OSError) as e: if errno_from_exception(e) == errno.EINTR: continue # ssl.SSLError is a subclass of socket.error if self._is_connreset(e): # Treat ECONNRESET as a connection close rather than # an error to minimize log spam (the exception will # be available on self.error for apps that care). self.close(exc_info=e) return None self.close(exc_info=e) raise break if bytes_read is None: return 0 elif bytes_read == 0: self.close() return 0 if not self._user_read_buffer: self._read_buffer += memoryview(buf)[:bytes_read] self._read_buffer_size += bytes_read finally: # Break the reference to buf so we don't waste a chunk's worth of # memory in case an exception hangs on to our stack frame. del buf if self._read_buffer_size > self.max_buffer_size: gen_log.error("Reached maximum read buffer size") self.close() raise StreamBufferFullError("Reached maximum read buffer size") return bytes_read
[ "def", "_read_to_buffer", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "try", ":", "while", "True", ":", "try", ":", "if", "self", ".", "_user_read_buffer", ":", "buf", "=", "memoryview", "(", "self", ".", "_read_buffer", ")", "[", "self", ".", "_read_buffer_size", ":", "]", "# type: Union[memoryview, bytearray]", "else", ":", "buf", "=", "bytearray", "(", "self", ".", "read_chunk_size", ")", "bytes_read", "=", "self", ".", "read_from_fd", "(", "buf", ")", "except", "(", "socket", ".", "error", ",", "IOError", ",", "OSError", ")", "as", "e", ":", "if", "errno_from_exception", "(", "e", ")", "==", "errno", ".", "EINTR", ":", "continue", "# ssl.SSLError is a subclass of socket.error", "if", "self", ".", "_is_connreset", "(", "e", ")", ":", "# Treat ECONNRESET as a connection close rather than", "# an error to minimize log spam (the exception will", "# be available on self.error for apps that care).", "self", ".", "close", "(", "exc_info", "=", "e", ")", "return", "None", "self", ".", "close", "(", "exc_info", "=", "e", ")", "raise", "break", "if", "bytes_read", "is", "None", ":", "return", "0", "elif", "bytes_read", "==", "0", ":", "self", ".", "close", "(", ")", "return", "0", "if", "not", "self", ".", "_user_read_buffer", ":", "self", ".", "_read_buffer", "+=", "memoryview", "(", "buf", ")", "[", ":", "bytes_read", "]", "self", ".", "_read_buffer_size", "+=", "bytes_read", "finally", ":", "# Break the reference to buf so we don't waste a chunk's worth of", "# memory in case an exception hangs on to our stack frame.", "del", "buf", "if", "self", ".", "_read_buffer_size", ">", "self", ".", "max_buffer_size", ":", "gen_log", ".", "error", "(", "\"Reached maximum read buffer size\"", ")", "self", ".", "close", "(", ")", "raise", "StreamBufferFullError", "(", "\"Reached maximum read buffer size\"", ")", "return", "bytes_read" ]
Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception.
[ "Reads", "from", "the", "socket", "and", "appends", "the", "result", "to", "the", "read", "buffer", "." ]
b8b481770bcdb333a69afde5cce7eaa449128326
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L839-L885