desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the given signed cookie if it validates, or None.
The decoded cookie value is returned as a byte string (unlike
`get_cookie`).'
| def get_secure_cookie(self, name, value=None, max_age_days=31):
| 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)
|
'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(). May be caused by using async operations without the @asynchronous decorator.')
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk)
self.set_header('Content-Type',... |
'Renders the template with the given arguments as the response.'
| def render(self, template_name, **kwargs):
| 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', {}).values():
embed_part = module.embedded_javascript()
if embed_part:
... |
'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, 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`` application setting. 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']
return template.Loader(template_path, **kwargs)
|
'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):
| if self.application._wsgi:
if (callback is not None):
callback()
return
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, ... |
'Finishes this response, ending the HTTP request.'
| def finish(self, chunk=None):
| if self._finished:
raise RuntimeError('finish() called twice. May be caused by using async operations without the @asynchronous decorator.')
if (chunk is not None):
self.write(chunk)
if (not self._headers_written):
if ((self._status_code == ... |
'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):
self.finish()
return
self.clear()
reason = None
if ('exc_info' in kwargs):
exception = kwargs['exc_info'][1]
if (isin... |
'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 hasattr(self, 'get_error_html'):
if ('exc_info' in kwargs):
exc_info = kwargs.pop('exc_info')
kwargs['exception'] = exc_info[1]
try:
raise_exc_info(exc_info)
except Exception:
self.finish(self.get_error_html(status_code, **kw... |
'The local 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.'
| @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 a cached version of `get_current_user`, which you can
override to set the user based on, e.g., a cookie. If that
method is not overridden, this method always returns None.
We lazy-load the current user the first time this method is called
and cache the result after that... | @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.'
| 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')):
token = self.get_cookie('_xsrf')
if (not token):
token = binascii.b2a_hex(uuid.uuid4().bytes)
expires_days = (30 if self.current_user else None)
self.set_cookie('_xsrf', token, expires_days=expires_days)
self._xsrf_to... |
'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")
if (self.xsrf_token != token):
raise HTTPError(403, 'XSRF cookie does ... |
'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.... |
'Obsolete - catches exceptions from the wrapped function.
This function is unnecessary since Tornado 1.1.'
| def async_callback(self, callback, *args, **kwargs):
| if (callback is None):
return None
if (args or kwargs):
callback = functools.partial(callback, *args, **kwargs)
def wrapper(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception as e:
if self._headers_written:
app_log... |
'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):
| etag = self._headers.get('Etag')
inm = utf8(self.request.headers.get('If-None-Match', ''))
return bool((etag and inm and (inm.find(etag) >= 0)))
|
'Executes this request with the given output transforms.'
| 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... |
'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)
|
'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):
| if (not host_pattern.endswith('$')):
host_pattern += '$'
handlers = []
if (self.handlers and (self.handlers[(-1)][0].pattern == '.*$')):
self.handlers.insert((-1), (re.compile(host_pattern), handlers))
else:
self.handlers.append((re.compile(host_pattern), handlers))
for spec ... |
'Called by HTTPServer to execute the request.'
| def __call__(self, request):
| transforms = [t(request) for t in self.transforms]
handler = None
args = []
kwargs = {}
handlers = self._get_host_handlers(request)
if (not handlers):
handler = RedirectHandler(self, request, url=(('http://' + self.default_host) + '/'))
else:
for spec in handlers:
... |
'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):
| if (name in self.named_handlers):
return self.named_handlers[name].reverse(*args)
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 (absolute_path + os.path.sep).startswith(root)):
raise HTTPError(403, '%s is not in root static directory', self.path)
if (os.path.isdir(absolute_path) and (self.default_filename is not None)):
if (not self.request.path.endswith('/')):
... |
'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_type):
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. It will only
be called if a partial result is requested from `get_content`
.. versionadded:: 3.1'
| 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)
return mime_type
|
'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)
|
'Overridden in subclasses to return this module\'s output.'
| def render(self, *args, **kwargs):
| raise NotImplementedError()
|
'Returns a JavaScript string that will be embedded in the page.'
| def embedded_javascript(self):
| return None
|
'Returns a list of JavaScript files required by this module.'
| def javascript_files(self):
| return None
|
'Returns a CSS string that will be embedded in the page.'
| def embedded_css(self):
| return None
|
'Returns a list of CSS files required by this module.'
| def css_files(self):
| return None
|
'Returns a CSS string that will be put in the <head/> element'
| def html_head(self):
| return None
|
'Returns an HTML string that will be put in 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)
|
'Parameters:
* ``pattern``: Regular expression to be matched. Any groups
in the regex will be passed in to the handler\'s get/post/etc
methods as arguments.
* ``handler_class``: `RequestHandler` subclass to be invoked.
* ``kwargs`` (optional): A dictionary of additional arguments
to be passed to the handler\'s constru... | def __init__(self, pattern, handler_class, kwargs=None, name=None):
| if (not pattern.endswith('$')):
pattern += '$'
self.regex = re.compile(pattern)
assert (len(self.regex.groupindex) in (0, self.regex.groups)), ('groups in url regexes must either be all named or all positional: %r' % self.regex.pattern)
self.handler_class = ha... |
'Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return (\'/%s/%s/\', 2).'
| def _find_groups(self):
| pattern = self.regex.pattern
if pattern.startswith('^'):
pattern = pattern[1:]
if pattern.endswith('$'):
pattern = pattern[:(-1)]
if (self.regex.groups != pattern.count('(')):
return (None, None)
pieces = []
for fragment in pattern.split('('):
if (')' in fragment)... |
'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
|
'Run ``callback`` when we read the given regex pattern.
The callback will get the data read (including the data that
matched the regex and anything that came before it) as an argument.'
| def read_until_regex(self, regex, callback):
| self._set_read_callback(callback)
self._read_regex = re.compile(regex)
self._try_inline_read()
|
'Run ``callback`` when we read the given delimiter.
The callback will get the data read (including the delimiter)
as an argument.'
| def read_until(self, delimiter, callback):
| self._set_read_callback(callback)
self._read_delimiter = delimiter
self._try_inline_read()
|
'Run callback when we read the given number of bytes.
If a ``streaming_callback`` is given, it will be called with chunks
of data as they become available, and the argument to the final
``callback`` will be empty. Otherwise, the ``callback`` gets
the data as an argument.'
| def read_bytes(self, num_bytes, callback, streaming_callback=None):
| self._set_read_callback(callback)
assert isinstance(num_bytes, numbers.Integral)
self._read_bytes = num_bytes
self._streaming_callback = stack_context.wrap(streaming_callback)
self._try_inline_read()
|
'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 argument to the final
``callback`` will be empty. Otherwise, the ``callback`` gets the
data as an argument.
Subject to ``max_buffer_size`` limit from `IOStre... | def read_until_close(self, callback, streaming_callback=None):
| 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_callback(self._streaming_callback, self._consume(self._read_buffer_size))
self._run_callback(self._read_callb... |
'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.'
| def write(self, data, callback=None):
| assert isinstance(data, bytes_type)
self._check_closed()
if data:
WRITE_BUFFER_CHUNK_SIZE = (128 * 1024)
if (len(data) > WRITE_BUFFER_CHUNK_SIZE):
for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE):
self._write_buffer.append(data[i:(i + WRITE_BUFFER_CHUNK_SIZE)... |
'Call the given callback when the stream is closed.'
| def set_close_callback(self, callback):
| self._close_callback = stack_context.wrap(callback)
|
'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)
|
'Returns true if we are currently writing to the stream.'
| def writing(self):
| return bool(self._write_buffer)
|
'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):
| if self._read_from_buffer():
return
self._check_closed()
try:
try:
self._pending_callbacks += 1
while (not self.closed()):
if (self._read_to_buffer() == 0):
break
finally:
self._pending_callbacks -= 1
except ... |
'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):
| try:
chunk = self.read_from_fd()
except (socket.error, IOError, OSError) as e:
if (e.args[0] in _ERRNO_CONNRESET):
self.close(exc_info=True)
return
self.close(exc_info=True)
raise
if (chunk is None):
return 0
self._read_buffer.append(chunk)... |
'Attempts to complete the currently-pending read from the buffer.
Returns True if the read was completed.'
| def _read_from_buffer(self):
| if ((self._streaming_callback is not None) and self._read_buffer_size):
bytes_to_consume = self._read_buffer_size
if (self._read_bytes is not None):
bytes_to_consume = min(self._read_bytes, bytes_to_consume)
self._read_bytes -= bytes_to_consume
self._run_callback(self... |
'Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler.
Implementation notes: Reads and writes have a fast path and a
slow path. The fast path reads synchronously from socket
buffers, while the slow path uses `_add_io_state` to schedule
an IOLoop callback. Note that in both cases, the callback is
run asynchro... | def _add_io_state(self, state):
| if self.closed():
return
if (self._state is None):
self._state = (ioloop.IOLoop.ERROR | state)
with stack_context.NullContext():
self.io_loop.add_handler(self.fileno(), self._handle_events, self._state)
elif (not (self._state & state)):
self._state = (self._state ... |
'Connects the socket to a remote address without blocking.
May only be called if the socket passed to the constructor was
not previously connected. The address parameter is in the
same format as for `socket.connect <socket.socket.connect>`,
i.e. a ``(host, port)`` tuple. If ``callback`` is specified,
it will be calle... | def connect(self, address, callback=None, server_hostname=None):
| self._connecting = True
try:
self.socket.connect(address)
except socket.error as e:
if ((e.args[0] != errno.EINPROGRESS) and (e.args[0] not in _ERRNO_WOULDBLOCK)):
gen_log.warning('Connect error on fd %d: %s', self.socket.fileno(), e)
self.close(exc_inf... |
'The ``ssl_options`` keyword argument may either be a dictionary
of keywords arguments for `ssl.wrap_socket`, or an `ssl.SSLContext`
object.'
| def __init__(self, *args, **kwargs):
| self._ssl_options = kwargs.pop('ssl_options', {})
super(SSLIOStream, self).__init__(*args, **kwargs)
self._ssl_accepting = True
self._handshake_reading = False
self._handshake_writing = False
self._ssl_connect_callback = None
self._server_hostname = None
|
'Returns True if peercert is valid according to the configured
validation mode and hostname.
The ssl handshake already tested the certificate for a valid
CA signature; the only thing that remains is to check
the hostname.'
| def _verify_cert(self, peercert):
| if isinstance(self._ssl_options, dict):
verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE)
elif isinstance(self._ssl_options, ssl.SSLContext):
verify_mode = self._ssl_options.verify_mode
assert (verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL))
if ((verif... |
'Application is the name of the binary that generated the logs.
eg: dbchk.py, itunes-trends.py etc... For the backend, the name is fixed at \'viewfinder\'.
log_type is either \'full\' or \'error\'.'
| def __init__(self, application, log_type):
| self._app = application
self._log_type = log_type
|
'The base directory for raw logs.'
| def RawDirectory(self):
| return os.path.join(self._app, self._log_type)
|
'Base directory for the merged logs.'
| def MergedDirectory(self):
| return os.path.join(self.kMergedLogsPrefix, self._app, self._log_type)
|
'Path to the registry file containing the list of processed raw logs.'
| def ProcessedRegistryPath(self):
| return os.path.join(self.MergedDirectory(), self.kRegistryName)
|
'Given the full path to a raw log, return the instance name, or None if parsing fails.'
| def RawLogPathToInstance(self, path):
| tokens = path.split('/')
if ((len(tokens) != 5) or (tokens[0] != self._app) or (tokens[1] != self._log_type)):
return None
return tokens[3]
|
'Extract (date, instance) from the full path to a merged log file. Return None if parsing fails.'
| def _SplitLogPathName(self, path):
| path_tokens = path.split('/')
if ((len(path_tokens) != 5) or (path_tokens[0] != self.kMergedLogsPrefix) or (path_tokens[1] != self._app) or (path_tokens[2] != self._log_type)):
return None
return (path_tokens[3], path_tokens[4])
|
'Extract the instance name from a merged log path. Return None if parsing fails.'
| def MergedLogPathToInstance(self, path):
| parsed = self._SplitLogPathName(path)
return (parsed[1] if (parsed is not None) else None)
|
'Extract the date from a merged log path. Return None if parsing fails.'
| def MergedLogPathToDate(self, path):
| parsed = self._SplitLogPathName(path)
return (parsed[0] if (parsed is not None) else None)
|
'user_id is the user\'s viewfinder ID.'
| def __init__(self, user_id):
| self._user_id = user_id
|
'The base directory for analytics logs.'
| def RawDirectory(self):
| return (self._user_id + '/')
|
'Base directory for the merged logs.'
| def MergedDirectory(self):
| return (self.kMergedLogsPrefix + '/')
|
'Path to the registry file containing the list of processed analytics logs for the given user.'
| def ProcessedRegistryPath(self):
| return os.path.join(self.MergedDirectory(), self.kRegistryDir, self._user_id)
|
'Parse the full path to a user log file.
Returns a tuple consisting of: (type, user_id, device_id, version). Currently-known types are "analytics" or "log".
Some log files do not have a version in the path, in which case the version part of the tuple will be None.
Returns None if parsing failed.'
| def ParseRawLogPath(self, path):
| res = re.match(kUserLogPathRe, path)
if (res is None):
return None
assert (len(res.groups()) == 4)
(user_id, device_id, version, typ) = res.groups()
assert (user_id == self._user_id)
return (typ, user_id, device_id, version)
|
'user_id is the user\'s viewfinder ID.'
| def __init__(self, user_id):
| self._user_id = user_id
|
'The base directory for this user\'s crash logs.'
| def RawDirectory(self):
| return (self._user_id + '/')
|
'Base directory for this user\'s merged crash logs.'
| def MergedDirectory(self):
| return (os.path.join(self.kMergedLogsPrefix, self._user_id) + '/')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.