desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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()`` method (and optionally a
``close()`` method, which may be called when the `IOLoop` is shut
down).
The ``events`` argument is a bitwise or of the con... | def add_handler(self, fd, handler, events):
| raise NotImplementedError()
|
'Changes the events we listen for ``fd``.
.. versionchanged:: 4.0
Added the ability to pass file-like objects in addition to
raw file descriptors.'
| def update_handler(self, fd, events):
| raise NotImplementedError()
|
'Stop listening for events on ``fd``.
.. versionchanged:: 4.0
Added the ability to pass file-like objects in addition to
raw file descriptors.'
| def remove_handler(self, fd):
| raise NotImplementedError()
|
'Sends a signal if the `IOLoop` is blocked for more than
``s`` seconds.
Pass ``seconds=None`` to disable. Requires Python 2.6 on a unixy
platform.
The action parameter is a Python signal handler. Read the
documentation for the `signal` module for more information.
If ``action`` is None, the process will be killed if ... | def set_blocking_signal_threshold(self, seconds, action):
| raise NotImplementedError()
|
'Logs a stack trace if the `IOLoop` is blocked for more than
``s`` seconds.
Equivalent to ``set_blocking_signal_threshold(seconds,
self.log_stack)``'
| def set_blocking_log_threshold(self, seconds):
| self.set_blocking_signal_threshold(seconds, self.log_stack)
|
'Signal handler to log the stack trace of the current thread.
For use with `set_blocking_signal_threshold`.'
| def log_stack(self, signal, frame):
| gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ''.join(traceback.format_stack(frame)))
|
'Starts the I/O loop.
The loop will run until one of the callbacks calls `stop()`, which
will make the loop stop after the current event iteration completes.'
| def start(self):
| raise NotImplementedError()
|
'The IOLoop catches and logs exceptions, so it\'s
important that log output be visible. However, python\'s
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the actual log entry, so we
must explicitly configure logging if we\'ve made i... | def _setup_logging(self):
| if (not any([logging.getLogger().handlers, logging.getLogger('tornado').handlers, logging.getLogger('tornado.application').handlers])):
logging.basicConfig()
|
'Stop the I/O loop.
If the event loop is not currently running, the next call to `start()`
will return immediately.
To use asynchronous methods from otherwise-synchronous code (such as
unit tests), you can start and stop the event loop like this::
ioloop = IOLoop()
async_method(ioloop=ioloop, callback=ioloop.stop)
iolo... | def stop(self):
| raise NotImplementedError()
|
'Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`run_sync()` will return the yieldable\'s result). If it raises
an exception, the `IOL... | def run_sync(self, func, timeout=None):
| future_cell = [None]
def run():
try:
result = func()
if (result is not None):
from tornado.gen import convert_yielded
result = convert_yielded(result)
except Exception:
future_cell[0] = TracebackFuture()
future_cell[... |
'Returns the current time according to the `IOLoop`\'s clock.
The return value is a floating-point number relative to an
unspecified time in the past.
By default, the `IOLoop`\'s time function is `time.time`. However,
it may be configured to use e.g. `time.monotonic` instead.
Calls to `add_timeout` that pass a number ... | def time(self):
| return time.time()
|
'Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current t... | def add_timeout(self, deadline, callback, *args, **kwargs):
| if isinstance(deadline, numbers.Real):
return self.call_at(deadline, callback, *args, **kwargs)
elif isinstance(deadline, datetime.timedelta):
return self.call_at((self.time() + timedelta_to_seconds(deadline)), callback, *args, **kwargs)
else:
raise TypeError(('Unsupported deadlin... |
'Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. ver... | def call_later(self, delay, callback, *args, **kwargs):
| return self.call_at((self.time() + delay), callback, *args, **kwargs)
|
'Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel(... | def call_at(self, when, callback, *args, **kwargs):
| return self.add_timeout(when, callback, *args, **kwargs)
|
'Cancels a pending timeout.
The argument is a handle as returned by `add_timeout`. It is
safe to call `remove_timeout` even if the callback has already
been run.'
| def remove_timeout(self, timeout):
| raise NotImplementedError()
|
'Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time,
except from a signal handler. Note that this is the **only**
method in `IOLoop` that makes this thread-safety guarantee; all
other interaction with the `IOLoop` must be done from that
`IOLoop`\'s threa... | def add_callback(self, callback, *args, **kwargs):
| raise NotImplementedError()
|
'Calls the given callback on the next I/O loop iteration.
Safe for use from a Python signal handler; should not be used
otherwise.
Callbacks added with this method will be run without any
`.stack_context`, to avoid picking up the context of the function
that was interrupted by the signal.'
| def add_callback_from_signal(self, callback, *args, **kwargs):
| raise NotImplementedError()
|
'Calls the given callback on the next IOLoop iteration.
Unlike all other callback-related methods on IOLoop,
``spawn_callback`` does not associate the callback with its caller\'s
``stack_context``, so it is suitable for fire-and-forget callbacks
that should not interfere with the caller.
.. versionadded:: 4.0'
| def spawn_callback(self, callback, *args, **kwargs):
| with stack_context.NullContext():
self.add_callback(callback, *args, **kwargs)
|
'Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`.'
| def add_future(self, future, callback):
| assert is_future(future)
callback = stack_context.wrap(callback)
future.add_done_callback((lambda future: self.add_callback(callback, future)))
|
'Runs a callback with error handling.
For use in subclasses.'
| def _run_callback(self, callback):
| try:
ret = callback()
if (ret is not None):
from tornado import gen
try:
ret = gen.convert_yielded(ret)
except gen.BadYieldError:
pass
else:
self.add_future(ret, self._discard_future_result)
except Ex... |
'Avoid unhandled-exception warnings from spawned coroutines.'
| def _discard_future_result(self, future):
| future.result()
|
'This method is called whenever a callback run by the `IOLoop`
throws an exception.
By default simply logs the exception as an error. Subclasses
may override this method to customize reporting of exceptions.
The exception itself is not passed explicitly, but is available
in `sys.exc_info`.'
| def handle_callback_exception(self, callback):
| app_log.error('Exception in callback %r', callback, exc_info=True)
|
'Returns an (fd, obj) pair from an ``fd`` parameter.
We accept both raw file descriptors and file-like objects as
input to `add_handler` and related methods. When a file-like
object is passed, we must retain the object itself so we can
close it correctly when the `IOLoop` shuts down, but the
poller interfaces favor fi... | def split_fd(self, fd):
| try:
return (fd.fileno(), fd)
except AttributeError:
return (fd, fd)
|
'Utility method to close an ``fd``.
If ``fd`` is a file-like object, we close it directly; otherwise
we use `os.close`.
This method is provided for use by `IOLoop` subclasses (in
implementations of ``IOLoop.close(all_fds=True)`` and should
not generally be used by application code.
.. versionadded:: 4.0'
| def close_fd(self, fd):
| try:
try:
fd.close()
except AttributeError:
os.close(fd)
except OSError:
pass
|
'Starts the timer.'
| def start(self):
| self._running = True
self._next_timeout = self.io_loop.time()
self._schedule_next()
|
'Stops the timer.'
| def stop(self):
| self._running = False
if (self._timeout is not None):
self.io_loop.remove_timeout(self._timeout)
self._timeout = None
|
'Return True if this `.PeriodicCallback` has been started.
.. versionadded:: 4.1'
| def is_running(self):
| return self._running
|
'Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate`
that can serve the request.
Routing implementations may pass additional kwargs to extend the routing logic.
:arg httputil.HTTPServerRequest request: current HTTP request.
:arg kwargs: additional keyword arguments passed by routin... | def find_handler(self, request, **kwargs):
| raise NotImplementedError()
|
'Returns url string for a given route name and arguments
or ``None`` if no match is found.
:arg str name: route name.
:arg args: url parameters.
:returns: parametrized url string for a given route name (or ``None``).'
| def reverse_url(self, name, *args):
| raise NotImplementedError()
|
'Constructs a router from an ordered list of rules::
RuleRouter([
Rule(PathMatches("/handler"), Target),
# ... more rules
You can also omit explicit `Rule` constructor and use tuples of arguments::
RuleRouter([
(PathMatches("/handler"), Target),
`PathMatches` is a default matcher, so the example above can be simplified... | def __init__(self, rules=None):
| self.rules = []
if rules:
self.add_rules(rules)
|
'Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor).'
| def add_rules(self, rules):
| for rule in rules:
if isinstance(rule, (tuple, list)):
assert (len(rule) in (2, 3, 4))
if isinstance(rule[0], basestring_type):
rule = Rule(PathMatches(rule[0]), *rule[1:])
else:
rule = Rule(*rule)
self.rules.append(self.process_rul... |
'Override this method for additional preprocessing of each rule.
:arg Rule rule: a rule to be processed.
:returns: the same or modified Rule instance.'
| def process_rule(self, rule):
| return rule
|
'Returns an instance of `~.httputil.HTTPMessageDelegate` for a
Rule\'s target. This method is called by `~.find_handler` and can be
extended to provide additional target types.
:arg target: a Rule\'s target.
:arg httputil.HTTPServerRequest request: current request.
:arg target_params: additional parameters that can be ... | def get_target_delegate(self, target, request, **target_params):
| if isinstance(target, Router):
return target.find_handler(request, **target_params)
elif isinstance(target, httputil.HTTPServerConnectionDelegate):
return target.start_request(request.server_connection, request.connection)
elif callable(target):
return _CallableAdapter(partial(target... |
'Constructs a Rule instance.
:arg Matcher matcher: a `Matcher` instance used for determining
whether the rule should be considered a match for a specific
request.
:arg target: a Rule\'s target (typically a ``RequestHandler`` or
`~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
depending on r... | def __init__(self, matcher, target, target_kwargs=None, name=None):
| if isinstance(target, str):
target = import_object(target)
self.matcher = matcher
self.target = target
self.target_kwargs = (target_kwargs if target_kwargs else {})
self.name = name
|
'Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of parameters to be passed to the target handler
(for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
can be passed for proper `~.web.RequestHandler` instantiation).
An empty dict is... | def match(self, request):
| raise NotImplementedError()
|
'Reconstructs full url from matcher instance and additional arguments.'
| def reverse(self, *args):
| return None
|
'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)... |
'Parameters:
* ``pattern``: Regular expression to be matched. Any capturing
groups in the regex will be passed in to the handler\'s
get/post/etc methods as arguments (by keyword if named, by
position if unnamed. Named and unnamed capturing groups may
may not be mixed in the same rule).
* ``handler``: `~.web.RequestHand... | def __init__(self, pattern, handler, kwargs=None, name=None):
| super(URLSpec, self).__init__(PathMatches(pattern), handler, kwargs, name)
self.regex = self.matcher.regex
self.handler_class = self.target
self.kwargs = kwargs
|
':arg bool no_keep_alive: If true, always close the connection after
one request.
:arg int chunk_size: how much data to read into memory at once
:arg int max_header_size: maximum amount of data for HTTP headers
:arg float header_timeout: how long to wait for all headers (seconds)
:arg int max_body_size: maximum amount... | def __init__(self, no_keep_alive=False, chunk_size=None, max_header_size=None, header_timeout=None, max_body_size=None, body_timeout=None, decompress=False):
| self.no_keep_alive = no_keep_alive
self.chunk_size = (chunk_size or 65536)
self.max_header_size = (max_header_size or 65536)
self.header_timeout = header_timeout
self.max_body_size = max_body_size
self.body_timeout = body_timeout
self.decompress = decompress
|
':arg stream: an `.IOStream`
:arg bool is_client: client or server
:arg params: a `.HTTP1ConnectionParameters` instance or ``None``
:arg context: an opaque application-defined object that can be accessed
as ``connection.context``.'
| def __init__(self, stream, is_client, params=None, context=None):
| self.is_client = is_client
self.stream = stream
if (params is None):
params = HTTP1ConnectionParameters()
self.params = params
self.context = context
self.no_keep_alive = params.no_keep_alive
self._max_body_size = (self.params.max_body_size or self.stream.max_buffer_size)
self._b... |
'Read a single HTTP response.
Typical client-mode usage is to write a request using `write_headers`,
`write`, and `finish`, and then call ``read_response``.
:arg delegate: a `.HTTPMessageDelegate`
Returns a `.Future` that resolves to None after the full response has
been read.'
| def read_response(self, delegate):
| if self.params.decompress:
delegate = _GzipMessageDelegate(delegate, self.params.chunk_size)
return self._read_message(delegate)
|
'Clears the callback attributes.
This allows the request handler to be garbage collected more
quickly in CPython by breaking up reference cycles.'
| def _clear_callbacks(self):
| self._write_callback = None
self._write_future = None
self._close_callback = None
if (self.stream is not None):
self.stream.set_close_callback(None)
|
'Sets a callback that will be run when the connection is closed.
.. deprecated:: 4.0
Use `.HTTPMessageDelegate.on_connection_close` instead.'
| def set_close_callback(self, callback):
| self._close_callback = stack_context.wrap(callback)
|
'Take control of the underlying stream.
Returns the underlying `.IOStream` object and stops all further
HTTP processing. May only be called during
`.HTTPMessageDelegate.headers_received`. Intended for implementing
protocols like websockets that tunnel over an HTTP handshake.'
| def detach(self):
| self._clear_callbacks()
stream = self.stream
self.stream = None
if (not self._finish_future.done()):
self._finish_future.set_result(None)
return stream
|
'Sets the body timeout for a single request.
Overrides the value from `.HTTP1ConnectionParameters`.'
| def set_body_timeout(self, timeout):
| self._body_timeout = timeout
|
'Sets the body size limit for a single request.
Overrides the value from `.HTTP1ConnectionParameters`.'
| def set_max_body_size(self, max_body_size):
| self._max_body_size = max_body_size
|
'Implements `.HTTPConnection.write_headers`.'
| def write_headers(self, start_line, headers, chunk=None, callback=None):
| lines = []
if self.is_client:
self._request_start_line = start_line
lines.append(utf8(('%s %s HTTP/1.1' % (start_line[0], start_line[1]))))
self._chunking_output = ((start_line.method in ('POST', 'PUT', 'PATCH')) and ('Content-Length' not in headers) and ('Transfer-Encoding' not in... |
'Implements `.HTTPConnection.write`.
For backwards compatibility is is allowed but deprecated to
skip `write_headers` and instead call `write()` with a
pre-encoded header block.'
| def write(self, chunk, callback=None):
| future = None
if self.stream.closed():
future = self._write_future = Future()
self._write_future.set_exception(iostream.StreamClosedError())
self._write_future.exception()
else:
if (callback is not None):
self._write_callback = stack_context.wrap(callback)
... |
'Implements `.HTTPConnection.finish`.'
| def finish(self):
| if ((self._expected_content_remaining is not None) and (self._expected_content_remaining != 0) and (not self.stream.closed())):
self.stream.close()
raise httputil.HTTPOutputError(('Tried to write %d bytes less than Content-Length' % self._expected_content_remaining))
if self... |
':arg stream: an `.IOStream`
:arg params: a `.HTTP1ConnectionParameters` or None
:arg context: an opaque application-defined object that is accessible
as ``connection.context``'
| def __init__(self, stream, params=None, context=None):
| self.stream = stream
if (params is None):
params = HTTP1ConnectionParameters()
self.params = params
self.context = context
self._serving_future = None
|
'Closes the connection.
Returns a `.Future` that resolves after the serving loop has exited.'
| @gen.coroutine
def close(self):
| self.stream.close()
try:
(yield self._serving_future)
except Exception:
pass
|
'Starts serving requests on this connection.
:arg delegate: a `.HTTPServerConnectionDelegate`'
| def start_serving(self, delegate):
| assert isinstance(delegate, httputil.HTTPServerConnectionDelegate)
self._serving_future = self._server_request_loop(delegate)
self.stream.io_loop.add_future(self._serving_future, (lambda f: f.result()))
|
'Proxy all unknown attributes to the original method.
This is important for some of the decorators in the `unittest`
module, such as `unittest.skipIf`.'
| def __getattr__(self, name):
| return getattr(self.orig_method, name)
|
'Creates a new `.IOLoop` for this test. May be overridden in
subclasses for tests that require a specific `.IOLoop` (usually
the singleton `.IOLoop.instance()`).'
| def get_new_ioloop(self):
| return IOLoop()
|
'Stops the `.IOLoop`, causing one pending (or future) call to `wait()`
to return.
Keyword arguments or a single positional argument passed to `stop()` are
saved and will be returned by `wait()`.'
| def stop(self, _arg=None, **kwargs):
| assert ((_arg is None) or (not kwargs))
self.__stop_args = (kwargs or _arg)
if self.__running:
self.io_loop.stop()
self.__running = False
self.__stopped = True
|
'Runs the `.IOLoop` until stop is called or timeout has passed.
In the event of a timeout, an exception will be thrown. The
default timeout is 5 seconds; it may be overridden with a
``timeout`` keyword argument or globally with the
``ASYNC_TEST_TIMEOUT`` environment variable.
If ``condition`` is not None, the `.IOLoop`... | def wait(self, condition=None, timeout=None):
| if (timeout is None):
timeout = get_async_test_timeout()
if (not self.__stopped):
if timeout:
def timeout_func():
try:
raise self.failureException(('Async operation timed out after %s seconds' % timeout))
except Ex... |
'Should be overridden by subclasses to return a
`tornado.web.Application` or other `.HTTPServer` callback.'
| def get_app(self):
| raise NotImplementedError()
|
'Convenience method to synchronously fetch a url.
The given path will be appended to the local server\'s host and
port. Any additional kwargs will be passed directly to
`.AsyncHTTPClient.fetch` (and so could be used to pass
``method="POST"``, ``body="..."``, etc).'
| def fetch(self, path, **kwargs):
| self.http_client.fetch(self.get_url(path), self.stop, **kwargs)
return self.wait()
|
'May be overridden by subclasses to return additional
keyword arguments for the server.'
| def get_httpserver_options(self):
| return {}
|
'Returns the port used by the server.
A new port is chosen for each test.'
| def get_http_port(self):
| return self.__port
|
'Returns an absolute url for the given path on the test server.'
| def get_url(self, path):
| return ('%s://localhost:%s%s' % (self.get_protocol(), self.get_http_port(), path))
|
'May be overridden by subclasses to select SSL options.
By default includes a self-signed testing certificate.'
| def get_ssl_options(self):
| module_dir = os.path.dirname(__file__)
return dict(certfile=os.path.join(module_dir, 'test', 'test.crt'), keyfile=os.path.join(module_dir, 'test', 'test.key'))
|
'Constructs an ExpectLog context manager.
:param logger: Logger object (or name of logger) to watch. Pass
an empty string to watch the root logger.
:param regex: Regular expression to match. Any log entries on
the specified logger that match this regex will be suppressed.
:param required: If true, an exception will b... | def __init__(self, logger, regex, required=True):
| if isinstance(logger, basestring_type):
logger = logging.getLogger(logger)
self.logger = logger
self.regex = re.compile(regex)
self.required = required
self.matched = False
self.logged_stack = False
|
'Returns the closest match for the given locale code.'
| @classmethod
def get_closest(cls, *locale_codes):
| for code in locale_codes:
if (not code):
continue
code = code.replace('-', '_')
parts = code.split('_')
if (len(parts) > 2):
continue
elif (len(parts) == 2):
code = ((parts[0].lower() + '_') + parts[1].upper())
if (code in _supporte... |
'Returns the Locale for the given locale code.
If it is not supported, we raise an exception.'
| @classmethod
def get(cls, code):
| if (not hasattr(cls, '_cache')):
cls._cache = {}
if (code not in cls._cache):
assert (code in _supported_locales)
translations = _translations.get(code, None)
if (translations is None):
locale = CSVLocale(code, {})
elif _use_gettext:
locale = Gette... |
'Returns the translation for the given message for this locale.
If ``plural_message`` is given, you must also provide
``count``. We return ``plural_message`` when ``count != 1``,
and we return the singular form for the given message when
``count == 1``.'
| def translate(self, message, plural_message=None, count=None):
| raise NotImplementedError()
|
'Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July 10, 1980") with
``full_format=True``.
This method is primarily intended for dates in the past.
For dates i... | def format_date(self, date, gmt_offset=0, relative=True, shorter=False, full_format=False):
| if isinstance(date, numbers.Real):
date = datetime.datetime.utcfromtimestamp(date)
now = datetime.datetime.utcnow()
if (date > now):
if (relative and ((date - now).seconds < 60)):
date = now
else:
full_format = True
local_date = (date - datetime.timedelta(... |
'Formats the given date as a day of week.
Example: "Monday, January 22". You can remove the day of week with
``dow=False``.'
| def format_day(self, date, gmt_offset=0, dow=True):
| local_date = (date - datetime.timedelta(minutes=gmt_offset))
_ = self.translate
if dow:
return (_('%(weekday)s, %(month_name)s %(day)s') % {'month_name': self._months[(local_date.month - 1)], 'weekday': self._weekdays[local_date.weekday()], 'day': str(local_date.day)})
else:
return... |
'Returns a comma-separated list for the given list of parts.
The format is, e.g., "A, B and C", "A and B" or just "A" for lists
of size 1.'
| def list(self, parts):
| _ = self.translate
if (len(parts) == 0):
return ''
if (len(parts) == 1):
return parts[0]
comma = (u' \u0648 ' if self.code.startswith('fa') else u', ')
return (_('%(commas)s and %(last)s') % {'commas': comma.join(parts[:(-1)]), 'last': parts[(len(parts) - 1)]})
|
'Returns a comma-separated number for the given integer.'
| def friendly_number(self, value):
| if (self.code not in ('en', 'en_US')):
return str(value)
value = str(value)
parts = []
while value:
parts.append(value[(-3):])
value = value[:(-3)]
return ','.join(reversed(parts))
|
'Allows to set context for translation, accepts plural forms.
Usage example::
pgettext("law", "right")
pgettext("good", "right")
Plural message example::
pgettext("organization", "club", "clubs", len(clubs))
pgettext("stick", "club", "clubs", len(clubs))
To generate POT file with context, add following options to step ... | def pgettext(self, context, message, plural_message=None, count=None):
| if (plural_message is not None):
assert (count is not None)
msgs_with_ctxt = (('%s%s%s' % (context, CONTEXT_SEPARATOR, message)), ('%s%s%s' % (context, CONTEXT_SEPARATOR, plural_message)), count)
result = self.ngettext(*msgs_with_ctxt)
if (CONTEXT_SEPARATOR in result):
re... |
'A sequence of (name, value) pairs.
.. versionadded:: 3.1'
| def items(self):
| return [(opt.name, opt.value()) for (name, opt) in self._options.items()]
|
'The set of option-groups created by ``define``.
.. versionadded:: 3.1'
| def groups(self):
| return set((opt.group_name for opt in self._options.values()))
|
'The names and values of options in a group.
Useful for copying options into Application settings::
from tornado.options import define, parse_command_line, options
define(\'template_path\', group=\'application\')
define(\'static_path\', group=\'application\')
parse_command_line()
application = Application(
handlers, **... | def group_dict(self, group):
| return dict(((opt.name, opt.value()) for (name, opt) in self._options.items() if ((not group) or (group == opt.group_name))))
|
'The names and values of all options.
.. versionadded:: 3.1'
| def as_dict(self):
| return dict(((opt.name, opt.value()) for (name, opt) in self._options.items()))
|
'Defines a new command line option.
If ``type`` is given (one of str, float, int, datetime, or timedelta)
or can be inferred from the ``default``, we parse the command line
arguments based on the given type. If ``multiple`` is True, we accept
comma-separated values, and the option value is always a list.
For multi-valu... | def define(self, name, default=None, type=None, help=None, metavar=None, multiple=False, group=None, callback=None):
| if (name in self._options):
raise Error(('Option %r already defined in %s' % (name, self._options[name].file_name)))
frame = sys._getframe(0)
options_file = frame.f_code.co_filename
if ((frame.f_back.f_code.co_filename == options_file) and (frame.f_back.f_code.co_name == 'define')... |
'Parses all options given on the command line (defaults to
`sys.argv`).
Note that ``args[0]`` is ignored since it is the program name
in `sys.argv`.
We return a list of all arguments that are not parsed as options.
If ``final`` is ``False``, parse callbacks will not be run.
This is useful for applications that wish to ... | def parse_command_line(self, args=None, final=True):
| if (args is None):
args = sys.argv
remaining = []
for i in range(1, len(args)):
if (not args[i].startswith('-')):
remaining = args[i:]
break
if (args[i] == '--'):
remaining = args[(i + 1):]
break
arg = args[i].lstrip('-')
... |
'Parses and loads the Python config file at the given path.
If ``final`` is ``False``, parse callbacks will not be run.
This is useful for applications that wish to combine configurations
from multiple sources.
.. versionchanged:: 4.1
Config files are now always interpreted as utf-8 instead of
the system default encodi... | def parse_config_file(self, path, final=True):
| config = {'__file__': os.path.abspath(path)}
with open(path, 'rb') as f:
exec_in(native_str(f.read()), config, config)
for name in config:
normalized = self._normalize_name(name)
if (normalized in self._options):
self._options[normalized].set(config[name])
if final:
... |
'Prints all the command line options to stderr (or another file).'
| def print_help(self, file=None):
| if (file is None):
file = sys.stderr
print(('Usage: %s [OPTIONS]' % sys.argv[0]), file=file)
print('\nOptions:\n', file=file)
by_group = {}
for option in self._options.values():
by_group.setdefault(option.group_name, []).append(option)
for (filename, o) in sorted(by_group.i... |
'Adds a parse callback, to be invoked when option parsing is done.'
| def add_parse_callback(self, callback):
| self._parse_callbacks.append(stack_context.wrap(callback))
|
'Returns a wrapper around self that is compatible with
`mock.patch <unittest.mock.patch>`.
The `mock.patch <unittest.mock.patch>` function (included in
the standard library `unittest.mock` package since Python 3.3,
or in the third-party ``mock`` package for older versions of
Python) is incompatible with objects like ``... | def mockable(self):
| return _Mockable(self)
|
'Starts accepting connections on the given port.
This method may be called more than once to listen on multiple ports.
`listen` takes effect immediately; it is not necessary to call
`TCPServer.start` afterwards. It is, however, necessary to start
the `.IOLoop`.'
| def listen(self, port, address=''):
| sockets = bind_sockets(port, address=address)
self.add_sockets(sockets)
|
'Makes this server start accepting connections on the given sockets.
The ``sockets`` parameter is a list of socket objects such as
those returned by `~tornado.netutil.bind_sockets`.
`add_sockets` is typically used in combination with that
method and `tornado.process.fork_processes` to provide greater
control over the i... | def add_sockets(self, sockets):
| if (self.io_loop is None):
self.io_loop = IOLoop.current()
for sock in sockets:
self._sockets[sock.fileno()] = sock
add_accept_handler(sock, self._handle_connection, io_loop=self.io_loop)
|
'Singular version of `add_sockets`. Takes a single socket object.'
| def add_socket(self, socket):
| self.add_sockets([socket])
|
'Binds this server to the given port on the given address.
To start the server, call `start`. If you want to run this server
in a single process, you can call `listen` as a shortcut to the
sequence of `bind` and `start` calls.
Address may be either an IP address or hostname. If it\'s a hostname,
the server will listen... | def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128, reuse_port=False):
| sockets = bind_sockets(port, address=address, family=family, backlog=backlog, reuse_port=reuse_port)
if self._started:
self.add_sockets(sockets)
else:
self._pending_sockets.extend(sockets)
|
'Starts this server in the `.IOLoop`.
By default, we run the server in this process and do not fork any
additional child process.
If num_processes is ``None`` or <= 0, we detect the number of cores
available on this machine and fork that number of child
processes. If num_processes is given and > 1, we fork that
specifi... | def start(self, num_processes=1):
| assert (not self._started)
self._started = True
if (num_processes != 1):
process.fork_processes(num_processes)
sockets = self._pending_sockets
self._pending_sockets = []
self.add_sockets(sockets)
|
'Stops listening for new connections.
Requests currently in progress may still continue after the
server is stopped.'
| def stop(self):
| if self._stopped:
return
self._stopped = True
for (fd, sock) in self._sockets.items():
assert (sock.fileno() == fd)
self.io_loop.remove_handler(fd)
sock.close()
|
'Override to handle a new `.IOStream` from an incoming connection.
This method may be a coroutine; if so any exceptions it raises
asynchronously will be logged. Accepting of incoming connections
will not be blocked by this coroutine.
If this `TCPServer` is configured for SSL, ``handle_stream``
may be called before the ... | def handle_stream(self, stream, address):
| raise NotImplementedError()
|
'Return the request payload - so we can check it is being kept'
| def patch(self):
| self.write(self.request.body)
|
'Performs a GET and HEAD request and returns the GET response.
Fails if any ``Content-*`` headers returned by the two requests
differ.'
| def get_and_head(self, *args, **kwargs):
| head_response = self.fetch(method='HEAD', *args, **kwargs)
get_response = self.fetch(method='GET', *args, **kwargs)
content_headers = set()
for h in itertools.chain(head_response.headers, get_response.headers):
if h.startswith('Content-'):
content_headers.add(h)
for h in content_... |
'Fail when trying to use the source IP Address \'8.8.8.8\'.'
| def test_source_ip_fail(self):
| self.assertRaises(socket.error, self.do_test_connect, socket.AF_INET, '127.0.0.1', source_ip='8.8.8.8')
|
'Success when trying to use the source IP Address \'127.0.0.1\''
| def test_source_ip_success(self):
| self.do_test_connect(socket.AF_INET, '127.0.0.1', source_ip='127.0.0.1')
|
'Fail when trying to use source port 1.'
| @skipIfNonUnix
def test_source_port_fail(self):
| self.assertRaises(socket.error, self.do_test_connect, socket.AF_INET, '127.0.0.1', source_port=1)
|
'Test cases copied from Python\'s Lib/test/test_http_cookies.py'
| def test_python_cookies(self):
| self.assertEqual(parse_cookie('chips=ahoy; vienna=finger'), {'chips': 'ahoy', 'vienna': 'finger'})
self.assertEqual(parse_cookie('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'), {'keebler': '"E=mc2', 'L': '\\"Loves\\"', 'fudge': '\\012', '': '"'})
self.assertEqual(parse_cookie('keebler=E=mc2'), {'k... |
'Cookie strings that go against RFC6265 but browsers will send if set
via document.cookie.'
| def test_invalid_cookies(self):
| self.assertIn('django_language', parse_cookie('abc=def; unnamed; django_language=en').keys())
self.assertEqual(parse_cookie('a=b; "; c=d'), {'a': 'b', '': '"', 'c': 'd'})
self.assertEqual(parse_cookie('a b c=d e = f; gh=i'), {'a b c': 'd e = f', 'gh': 'i'})
s... |
'Record the resolution of a Future returned by Condition.wait.'
| def record_done(self, future, key):
| def callback(_):
if (not future.result()):
self.history.append('timeout')
else:
self.history.append(key)
future.add_done_callback(callback)
|
'Basic test of IOStream\'s ability to return Futures.'
| @gen_test
def test_future_interface(self):
| stream = self._make_client_iostream()
connect_result = (yield stream.connect(('127.0.0.1', self.get_http_port())))
self.assertIs(connect_result, stream)
(yield stream.write('GET / HTTP/1.0\r\n\r\n'))
first_line = (yield stream.read_until('\r\n'))
self.assertEqual(first_line, 'HTTP/1.1 2... |
'Test that write() Futures are never orphaned.'
| def test_future_write(self):
| (m, n) = (10000, 1000)
nproducers = 10
total_bytes = ((m * n) * nproducers)
(server, client) = self.make_iostream_pair(max_buffer_size=total_bytes)
@gen.coroutine
def produce():
data = ('x' * m)
for i in range(n):
(yield server.write(data))
@gen.coroutine
def ... |
'Simulate a blocking sleep by advancing the clock.'
| def sleep(self, t):
| self.fts.sleep(t)
|
'When a file object is used instead of a numeric file descriptor,
the object should be closed (by IOLoop.close(all_fds=True),
not just the fd.'
| def test_close_file_object(self):
| class SocketWrapper(object, ):
def __init__(self, sockobj):
self.sockobj = sockobj
self.closed = False
def fileno(self):
return self.sockobj.fileno()
def close(self):
self.closed = True
self.sockobj.close()
(sockobj, port) = bin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.