desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
The returned values are always unicode.'
| def get_arguments(self, name, strip=True):
| assert isinstance(strip, bool)
return self._get_arguments(name, self.request.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.
The returned value is always unicode.
... | def get_body_argument(self, name, default=_ARG_DEFAULT, strip=True):
| return self._get_argument(name, default, 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.
The returned values are always unicode.
.. versionadded:: 3.2'
| def get_body_arguments(self, name, strip=True):
| return self._get_arguments(name, self.request.body_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.
The returned value is always u... | def get_query_argument(self, name, default=_ARG_DEFAULT, strip=True):
| return self._get_argument(name, default, 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.
The returned values are always unicode.
.. versionadded:: 3.2'
| def get_query_arguments(self, name, strip=True):
| return self._get_arguments(name, self.request.query_arguments, strip)
|
'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... | def decode_argument(self, value, name=None):
| try:
return _unicode(value)
except UnicodeDecodeError:
raise HTTPError(400, ('Invalid unicode in %s: %r' % ((name or 'url'), value[:40])))
|
'An alias for
`self.request.cookies <.httputil.HTTPServerRequest.cookies>`.'
| @property
def cookies(self):
| return self.request.cookies
|
'Gets the value of the cookie with the given name, else default.'
| def get_cookie(self, name, default=None):
| if ((self.request.cookies is not None) and (name in self.request.cookies)):
return self.request.cookies[name].value
return default
|
'Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See https://docs.python.org/2/library/cookie.html#Cookie.Morsel
for available attributes.'
| def set_cookie(self, name, value, domain=None, expires=None, path='/', expires_days=None, **kwargs):
| name = escape.native_str(name)
value = escape.native_str(value)
if re.search('[\\x00-\\x20]', (name + value)):
raise ValueError(('Invalid cookie %r: %r' % (name, value)))
if (not hasattr(self, '_new_cookie')):
self._new_cookie = Cookie.SimpleCookie()
if (name in self._new_co... |
'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).'
| def clear_cookie(self, name, path='/', domain=None):
| expires = (datetime.datetime.utcnow() - datetime.timedelta(days=365))
self.set_cookie(name, value='', path=path, expires=expires, domain=domain)
|
'Deletes all the cookies the user sent with this request.
See `clear_cookie` for more information on the path and domain
parameters.
.. versionchanged:: 3.2
Added the ``path`` and ``domain`` parameters.'
| def clear_all_cookies(self, path='/', domain=None):
| for name in self.request.cookies:
self.clear_cookie(name, path=path, domain=domain)
|
'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 ``e... | def set_secure_cookie(self, name, value, expires_days=30, version=None, **kwargs):
| self.set_cookie(name, self.create_signed_value(name, value, version=version), expires_days=expires_days, **kwargs)
|
'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 ... | def create_signed_value(self, name, value, version=None):
| 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 f... |
'Returns the given signed cookie if it validates, or None.
The decoded cookie value is returned as a byte string (unlike
`get_cookie`).
.. versionchanged:: 3.2.1
Added the ``min_version`` argument. Introduced cookie version 2;
both versions 1 and 2 are accepted by default.'
| def get_secure_cookie(self, name, value=None, max_age_days=31, min_version=None):
| 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 signing key version of the secure cookie.
The version is returned as int.'
| def get_secure_cookie_key_version(self, name, value=None):
| self.require_setting('cookie_secret', 'secure cookies')
if (value is None):
value = self.get_cookie(name)
return get_signature_key_version(value)
|
'Sends a redirect to the given (optionally relative) URL.
If the ``status`` argument is specified, that value is used as the
HTTP status code; otherwise either 301 (permanent) or 302
(temporary) is chosen based on the ``permanent`` argument.
The default is 302 (temporary).'
| def redirect(self, url, permanent=False, status=None):
| if self._headers_written:
raise Exception('Cannot redirect after headers have been written')
if (status is None):
status = (301 if permanent else 302)
else:
assert (isinstance(status, int) and (300 <= status <= 399))
self.set_status(status)
self.set_header('... |
'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* ... | def write(self, chunk):
| 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 ... |
'Renders the template with the given arguments as the response.'
| def render(self, template_name, **kwargs):
| if self._finished:
raise RuntimeError('Cannot render() after finish()')
html = self.render_string(template_name, **kwargs)
js_embed = []
js_files = []
css_embed = []
css_files = []
html_heads = []
html_bodies = []
for module in getattr(self, '_active_modules', {}).va... |
'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.'
| def render_linked_js(self, js_files):
| paths = []
unique_paths = set()
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)) + '" ... |
'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.'
| def render_embed_js(self, js_embed):
| return (('<script type="text/javascript">\n//<![CDATA[\n' + '\n'.join(js_embed)) + '\n//]]>\n</script>')
|
'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.'
| def render_linked_css(self, css_files):
| paths = []
unique_paths = set()
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)) + '" ... |
'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.'
| def render_embed_css(self, css_embed):
| return (('<style type="text/css">\n' + '\n'.join(css_embed)) + '\n</style>')
|
'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.'
| def render_string(self, template_name, **kwargs):
| 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
template_path = os.path.dirname(frame.f_code.co_filename)
with RequestH... |
'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`.'
| def get_template_namespace(self):
| 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 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.'
| def create_template_loader(self, template_path):
| settings = self.application.settings
if ('template_loader' in settings):
return settings['template_loader']
kwargs = {}
if ('autoescape' in settings):
kwargs['autoescape'] = settings['autoescape']
if ('template_whitespace' in settings):
kwargs['whitespace'] = settings['templa... |
'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 bee... | def flush(self, include_footers=False, callback=None):
| chunk = ''.join(self._write_buffer)
self._write_buffer = []
if (not self._headers_written):
self._headers_written = True
for transform in self._transforms:
(self._status_code, self._headers, chunk) = transform.transform_first_chunk(self._status_code, self._headers, chunk, include... |
'Finishes this response, ending the HTTP request.'
| def finish(self, chunk=None):
| if self._finished:
raise RuntimeError('finish() called twice')
if (chunk is not None):
self.write(chunk)
if (not self._headers_written):
if ((self._status_code == 200) and (self.request.method in ('GET', 'HEAD')) and ('Etag' not in self._headers)):
self.set_etag_hea... |
'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 ... | def send_error(self, status_code=500, **kwargs):
| if self._headers_written:
gen_log.error('Cannot send error response after headers written')
if (not self._finished):
try:
self.finish()
except Exception:
gen_log.error('Failed to flush partial response', exc_info=T... |
'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 "curr... | def write_error(self, status_code, **kwargs):
| if (self.settings.get('serve_traceback') and ('exc_info' in kwargs)):
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</t... |
'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.'
| @property
def locale(self):
| if (not hasattr(self, '_locale')):
self._locale = self.get_user_locale()
if (not self._locale):
self._locale = self.get_browser_locale()
assert self._locale
return self._locale
|
'Override to determine the locale from the authenticated user.
If None is returned, we fall back to `get_browser_locale()`.
This method should return a `tornado.locale.Locale` object,
most likely obtained via a call like ``tornado.locale.get("en")``'
| def get_user_locale(self):
| return None
|
'Determines the user\'s locale from ``Accept-Language`` header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4'
| def get_browser_locale(self, default='en_US'):
| 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:
... |
'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... | @property
def current_user(self):
| if (not hasattr(self, '_current_user')):
self._current_user = self.get_current_user()
return self._current_user
|
'Override to determine the current user from, e.g., a cookie.
This method may not be a coroutine.'
| def get_current_user(self):
| return None
|
'Override to customize the login URL based on the request.
By default, we use the ``login_url`` application setting.'
| def get_login_url(self):
| self.require_setting('login_url', '@tornado.web.authenticated')
return self.application.settings['login_url']
|
'Override to customize template path for each handler.
By default, we use the ``template_path`` application setting.
Return None to load templates relative to the calling file.'
| def get_template_path(self):
| return self.application.settings.get('template_path')
|
'The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an \'_xsrf\' cookie
and include the same \'_xsrf\' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-sit... | @property
def xsrf_token(self):
| if (not hasattr(self, '_xsrf_token')):
(version, token, timestamp) = self._get_raw_xsrf_token()
output_version = self.settings.get('xsrf_cookie_version', 2)
cookie_kwargs = self.settings.get('xsrf_cookie_kwargs', {})
if (output_version == 1):
self._xsrf_token = binascii.b... |
'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 (wil... | def _get_raw_xsrf_token(self):
| 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
... |
'Convert a cookie string into a the tuple form returned by
_get_raw_xsrf_token.'
| def _decode_xsrf_token(self, cookie):
| try:
m = _signed_value_version_re.match(utf8(cookie))
if m:
version = int(m.group(1))
if (version == 2):
(_, mask, masked_token, timestamp) = cookie.split('|')
mask = binascii.a2b_hex(utf8(mask))
token = _websocket_mask(mask, bi... |
'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... | def check_xsrf_cookie(self):
| 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._ge... |
'An HTML ``<input/>`` element to be included with all POST forms.
It defines the ``_xsrf`` input value, which we check on all POST
requests to prevent cross-site request forgery. If you have set
the ``xsrf_cookies`` application setting, you must include this
HTML within all of your HTML forms.
In a template, this metho... | def xsrf_form_html(self):
| return (('<input type="hidden" name="_xsrf" value="' + escape.xhtml_escape(self.xsrf_token)) + '"/>')
|
'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... | def static_url(self, path, include_host=None, **kwargs):
| 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.... |
'Raises an exception if the given app setting is not defined.'
| def require_setting(self, name, feature='this feature'):
| if (not self.application.settings.get(name)):
raise Exception(("You must define the '%s' setting in your application to use %s" % (name, feature)))
|
'Alias for `Application.reverse_url`.'
| def reverse_url(self, name, *args):
| return self.application.reverse_url(name, *args)
|
'Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations,
or may return None to disable tornado\'s default etag support.'
| def compute_etag(self):
| hasher = hashlib.sha1()
for part in self._write_buffer:
hasher.update(part)
return ('"%s"' % hasher.hexdigest())
|
'Sets the response\'s Etag header using ``self.compute_etag()``.
Note: no header will be set if ``compute_etag()`` returns ``None``.
This method is called automatically when the request is finished.'
| def set_etag_header(self):
| etag = self.compute_etag()
if (etag is not None):
self.set_header('Etag', etag)
|
'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 call... | def check_etag_header(self):
| computed_etag = utf8(self._headers.get('Etag', ''))
etags = re.findall('\\*|(?:W/)?"[^"]*"', utf8(self.request.headers.get('If-None-Match', '')))
if ((not computed_etag) or (not etags)):
return False
match = False
if (etags[0] == '*'):
match = True
else:
def val(x):
... |
'Executes this request with the given output transforms.'
| @gen.coroutine
def _execute(self, transforms, *args, **kwargs):
| 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... |
'Implement this method to handle streamed request data.
Requires the `.stream_request_body` decorator.'
| def data_received(self, chunk):
| raise NotImplementedError()
|
'Logs the current request.
Sort of deprecated since this functionality was moved to the
Application, but left in place for the benefit of existing apps
that have overridden this method.'
| def _log(self):
| self.application.log_request(self)
|
'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'
| def log_exception(self, typ, value, tb):
| 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('Uncaught exception %s\n%r',... |
'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 m... | def listen(self, port, address='', **kwargs):
| from tornado.httpserver import HTTPServer
server = HTTPServer(self, **kwargs)
server.listen(port, address)
return server
|
'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.'
| def add_handlers(self, host_pattern, host_handlers):
| 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)])
|
'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 l... | def get_handler_delegate(self, request, target_class, target_kwargs=None, path_args=None, path_kwargs=None):
| return _HandlerDelegate(self, request, target_class, target_kwargs, path_args, path_kwargs)
|
'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.'
| def reverse_url(self, name, *args):
| 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))
|
'Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
``log_function``.'
| def log_request(self, handler):
| if ('log_function' in self.settings):
self.settings['log_function'](handler)
return
if (handler.get_status() < 400):
log_method = access_log.info
elif (handler.get_status() < 500):
log_method = access_log.warning
else:
log_method = access_log.error
request_tim... |
'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'
| def compute_etag(self):
| version_hash = self._get_cached_version(self.absolute_path)
if (not version_hash):
return None
return ('"%s"' % (version_hash,))
|
'Sets the content and caching headers on the response.
.. versionadded:: 3.1'
| def set_headers(self):
| 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(... |
'Returns True if the headers indicate that we should return 304.
.. versionadded:: 3.1'
| def should_return_304(self):
| if self.check_etag_header():
return True
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])
if (if_since... |
'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 t... | @classmethod
def get_absolute_path(cls, root, path):
| abspath = os.path.abspath(os.path.join(root, path))
return abspath
|
'Validate and return the absolute path.
``root`` is the configured path for the `StaticFileHandler`,
and ``path`` is the result of `get_absolute_path`
This is an instance method called during request processing,
so it may raise `HTTPError` or use methods like
`RequestHandler.redirect` (return None after redirecting to
... | def validate_absolute_path(self, root, absolute_path):
| root = os.path.abspath(root)
if (not root.endswith(os.path.sep)):
root += os.path.sep
if (not (absolute_path + os.path.sep).startswith(root)):
raise HTTPError(403, '%s is not in root static directory', self.path)
if (os.path.isdir(absolute_path) and (self.default_filena... |
'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... | @classmethod
def get_content(cls, abspath, start=None, end=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))
else:
remaining = None
while True:
chunk_size = (64 * 1024)
if ((remaining is not None) and (r... |
'Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file\'s contents.
.. versionadded:: 3.1'
| @classmethod
def get_content_version(cls, abspath):
| data = cls.get_content(abspath)
hasher = hashlib.md5()
if isinstance(data, bytes):
hasher.update(data)
else:
for chunk in data:
hasher.update(chunk)
return hasher.hexdigest()
|
'Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
.. versionadded:: 3.1
.. versionchanged:: 4.0
This method is now always called, instead of only when
partial results are requested.'
| def get_content_size(self):
| stat_result = self._stat()
return stat_result[stat.ST_SIZE]
|
'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'
| def get_modified_time(self):
| stat_result = self._stat()
modified = datetime.datetime.utcfromtimestamp(stat_result[stat.ST_MTIME])
return modified
|
'Returns the ``Content-Type`` header to be used for this request.
.. versionadded:: 3.1'
| def get_content_type(self):
| (mime_type, encoding) = mimetypes.guess_type(self.absolute_path)
if (encoding == 'gzip'):
return 'application/gzip'
elif (encoding is not None):
return 'application/octet-stream'
elif (mime_type is not None):
return mime_type
else:
return 'application/octet-stream'
|
'For subclass to add extra headers to the response'
| def set_extra_headers(self, path):
| pass
|
'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`` arg... | def get_cache_time(self, path, modified, mime_type):
| return (self.CACHE_MAX_AGE if ('v' in self.request.arguments) else 0)
|
'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 `~RequestHandl... | @classmethod
def make_static_url(cls, settings, path, include_version=True):
| 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))
|
'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`.'
| def parse_url_path(self, url_path):
| if (os.path.sep != '/'):
url_path = url_path.replace('/', os.path.sep)
return url_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 prev... | @classmethod
def get_version(cls, settings, path):
| abs_path = cls.get_absolute_path(settings['static_path'], path)
return cls._get_cached_version(abs_path)
|
'Override in subclasses to return this module\'s output.'
| def render(self, *args, **kwargs):
| raise NotImplementedError()
|
'Override to return a JavaScript string
to be embedded in the page.'
| def embedded_javascript(self):
| return None
|
'Override to return a list of JavaScript files needed by this module.
If the return values are relative paths, they will be passed to
`RequestHandler.static_url`; otherwise they will be used as-is.'
| def javascript_files(self):
| return None
|
'Override to return a CSS string
that will be embedded in the page.'
| def embedded_css(self):
| return None
|
'Override to returns a list of CSS files required by this module.
If the return values are relative paths, they will be passed to
`RequestHandler.static_url`; otherwise they will be used as-is.'
| def css_files(self):
| return None
|
'Override to return an HTML string that will be put in the <head/>
element.'
| def html_head(self):
| return None
|
'Override to return an HTML string that will be put at the end of
the <body/> element.'
| def html_body(self):
| return None
|
'Renders a template and returns it as a string.'
| def render_string(self, path, **kwargs):
| return self.handler.render_string(path, **kwargs)
|
'`BaseIOStream` constructor.
:arg io_loop: The `.IOLoop` to use; defaults to `.IOLoop.current`.
Deprecated since Tornado 4.1.
:arg max_buffer_size: Maximum amount of incoming data to buffer;
defaults to 100MB.
:arg read_chunk_size: Amount of data to read at one time from the
underlying transport; defaults to 64KB.
:arg... | def __init__(self, io_loop=None, max_buffer_size=None, read_chunk_size=None, max_write_buffer_size=None):
| self.io_loop = (io_loop or ioloop.IOLoop.current())
self.max_buffer_size = (max_buffer_size or 104857600)
self.read_chunk_size = min((read_chunk_size or 65536), (self.max_buffer_size // 2))
self.max_write_buffer_size = max_write_buffer_size
self.error = None
self._read_buffer = bytearray()
s... |
'Returns the file descriptor for this stream.'
| def fileno(self):
| raise NotImplementedError()
|
'Closes the file underlying this stream.
``close_fd`` is called by `BaseIOStream` and should not be called
elsewhere; other users should call `close` instead.'
| def close_fd(self):
| raise NotImplementedError()
|
'Attempts to write ``data`` to the underlying file.
Returns the number of bytes written.'
| def write_to_fd(self, data):
| raise NotImplementedError()
|
'Attempts to read from the underlying file.
Returns ``None`` if there was nothing to read (the socket
returned `~errno.EWOULDBLOCK` or equivalent), otherwise
returns the data. When possible, should return no more than
``self.read_chunk_size`` bytes at a time.'
| def read_from_fd(self):
| raise NotImplementedError()
|
'Returns information about any error on the underlying file.
This method is called after the `.IOLoop` has signaled an error on the
file descriptor, and should return an Exception (such as `socket.error`
with additional information, or None if no such information is
available.'
| def get_fd_error(self):
| return None
|
'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 a callback is given, it will be run
with the data as an argument; if not, this method returns a
`.Future`.
If ``max_bytes`` is not None, the connection will be closed
if ... | def read_until_regex(self, regex, callback=None, max_bytes=None):
| future = self._set_read_callback(callback)
self._read_regex = re.compile(regex)
self._read_max_bytes = max_bytes
try:
self._try_inline_read()
except UnsatisfiableReadError as e:
gen_log.info(('Unsatisfiable read, closing connection: %s' % e))
self.close(exc_info=T... |
'Asynchronously read until we have found the given delimiter.
The result includes all the data read including the delimiter.
If a callback is given, it will be run with the data as an argument;
if not, this method returns a `.Future`.
If ``max_bytes`` is not None, the connection will be closed
if more than ``max_bytes`... | def read_until(self, delimiter, callback=None, max_bytes=None):
| future = self._set_read_callback(callback)
self._read_delimiter = delimiter
self._read_max_bytes = max_bytes
try:
self._try_inline_read()
except UnsatisfiableReadError as e:
gen_log.info(('Unsatisfiable read, closing connection: %s' % e))
self.close(exc_info=True)... |
'Asynchronously read a number of bytes.
If a ``streaming_callback`` is given, it will be called with chunks
of data as they become available, and the final result will be empty.
Otherwise, the result is all the data that was read.
If a callback is given, it will be run with the data as an argument;
if not, this method ... | def read_bytes(self, num_bytes, callback=None, streaming_callback=None, partial=False):
| future = self._set_read_callback(callback)
assert isinstance(num_bytes, numbers.Integral)
self._read_bytes = num_bytes
self._read_partial = partial
self._streaming_callback = stack_context.wrap(streaming_callback)
try:
self._try_inline_read()
except:
if (future is not None):
... |
'Asynchronously reads all data from the socket until it is closed.
If a ``streaming_callback`` is given, it will be called with chunks
of data as they become available, and the final result will be empty.
Otherwise, the result is all the data that was read.
If a callback is given, it will be run with the data as an arg... | def read_until_close(self, callback=None, streaming_callback=None):
| future = self._set_read_callback(callback)
self._streaming_callback = stack_context.wrap(streaming_callback)
if self.closed():
if (self._streaming_callback is not None):
self._run_read_callback(self._read_buffer_size, True)
self._run_read_callback(self._read_buffer_size, False)
... |
'Asynchronously write the given data to this stream.
If ``callback`` is given, we call it when all of the buffered write
data has been successfully written to the stream. If there was
previously buffered write data and an old write callback, that
callback is simply overwritten with this new callback.
If no ``callback``... | def write(self, data, callback=None):
| self._check_closed()
if data:
if ((self.max_write_buffer_size is not None) and ((self._write_buffer_size + len(data)) > self.max_write_buffer_size)):
raise StreamBufferFullError('Reached maximum write buffer size')
if self._write_buffer_frozen:
self._pending_w... |
'Call the given callback when the stream is closed.
This is not necessary for applications that use the `.Future`
interface; all outstanding ``Futures`` will resolve with a
`StreamClosedError` when the stream is closed.'
| def set_close_callback(self, callback):
| self._close_callback = stack_context.wrap(callback)
self._maybe_add_error_listener()
|
'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`).'
| def close(self, exc_info=False):
| if (not self.closed()):
if exc_info:
if (not isinstance(exc_info, tuple)):
exc_info = sys.exc_info()
if any(exc_info):
self.error = exc_info[1]
if self._read_until_close:
if ((self._streaming_callback is not None) and self._read_buf... |
'Returns true if we are currently reading from the stream.'
| def reading(self):
| return ((self._read_callback is not None) or (self._read_future is not None))
|
'Returns true if we are currently writing to the stream.'
| def writing(self):
| return (self._write_buffer_size > 0)
|
'Returns true if the stream has been closed.'
| def closed(self):
| return self._closed
|
'Sets the no-delay flag for this stream.
By default, data written to TCP streams may be held for a time
to make the most efficient use of bandwidth (according to
Nagle\'s algorithm). The no-delay flag requests that data be
written as soon as possible, even if doing so would consume
additional bandwidth.
This flag is c... | def set_nodelay(self, value):
| pass
|
'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.'
| def _try_inline_read(self):
| self._run_streaming_callback()
pos = self._find_read_pos()
if (pos is not None):
self._read_from_buffer(pos)
return
self._check_closed()
try:
pos = self._read_to_buffer_loop()
except Exception:
self._maybe_run_close_callback()
raise
if (pos is not None... |
'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.'
| def _read_to_buffer(self):
| while True:
try:
chunk = self.read_from_fd()
except (socket.error, IOError, OSError) as e:
if (errno_from_exception(e) == errno.EINTR):
continue
if self._is_connreset(e):
self.close(exc_info=True)
return
... |
'Attempts to complete the currently-pending read from the buffer.
The argument is either a position in the read buffer or None,
as returned by _find_read_pos.'
| def _read_from_buffer(self, pos):
| self._read_bytes = self._read_delimiter = self._read_regex = None
self._read_partial = False
self._run_read_callback(pos, False)
|
'Attempts to find a position in the read buffer that satisfies
the currently-pending read.
Returns a position in the buffer if the current read can be satisfied,
or None if it cannot.'
| def _find_read_pos(self):
| if ((self._read_bytes is not None) and ((self._read_buffer_size >= self._read_bytes) or (self._read_partial and (self._read_buffer_size > 0)))):
num_bytes = min(self._read_bytes, self._read_buffer_size)
return num_bytes
elif (self._read_delimiter is not None):
if self._read_buffer:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.