desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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)
|
'Equivalent to td.total_seconds() (introduced in python 2.7).'
| @staticmethod
def timedelta_to_seconds(td):
| return ((td.microseconds + ((td.seconds + ((td.days * 24) * 3600)) * (10 ** 6))) / float((10 ** 6)))
|
'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
|
'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 exeption will be... | 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
|
'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 self.code.startswith('ru'):
relative = 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:
ful... |
'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))
|
'A sequence of (name, value) pairs.
.. versionadded:: 3.1'
| def items(self):
| return [(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(((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(((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
file_name = frame.f_back.f_code.co_filename
if (file_name == options_file):
file_name =... |
'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.'
| def parse_config_file(self, path, final=True):
| config = {}
with open(path) as f:
exec_in(f.read(), config, config)
for name in config:
if (name in self._options):
self._options[name].set(config[name])
if final:
self.run_parse_callbacks()
|
'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):
| sockets = bind_sockets(port, address=address, family=family, backlog=backlog)
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):
| for (fd, sock) in self._sockets.items():
self.io_loop.remove_handler(fd)
sock.close()
|
'Override to handle a new `.IOStream` from an incoming connection.'
| def handle_stream(self, stream, address):
| raise NotImplementedError()
|
'This test makes sure that a second call to wait()
clears the first timeout.'
| def test_subsequent_wait_calls(self):
| self.io_loop.add_timeout((self.io_loop.time() + 0.01), self.stop)
self.wait(timeout=0.02)
self.io_loop.add_timeout((self.io_loop.time() + 0.03), self.stop)
self.wait(timeout=0.15)
|
'This test makes sure that AsyncTestCase calls super methods for
setUp and tearDown.
InheritBoth is a subclass of both AsyncTestCase and
SetUpTearDown, with the ordering so that the super of
AsyncTestCase will be SetUpTearDown.'
| def test_set_up_tear_down(self):
| events = []
result = unittest.TestResult()
class SetUpTearDown(unittest.TestCase, ):
def setUp(self):
events.append('setUp')
def tearDown(self):
events.append('tearDown')
class InheritBoth(AsyncTestCase, SetUpTearDown, ):
def test(self):
events... |
'A missing SSL key should cause an immediate exception.'
| def test_missing_key(self):
| application = Application()
module_dir = os.path.dirname(__file__)
existing_certificate = os.path.join(module_dir, 'test.crt')
self.assertRaises(ValueError, HTTPServer, application, ssl_options={'certfile': '/__mising__.crt'})
self.assertRaises(ValueError, HTTPServer, application, ssl_options={'cert... |
'In this test the writer writes an \'x\' to its fd. The reader
reads it, check the value and ends the test.'
| def _testReadWrite(self):
| self.shouldWrite = True
def checkReadInput(fd):
self.assertEquals(fd.read(1), 'x')
self._reactor.stop()
def writeOnce(fd):
if self.shouldWrite:
self.shouldWrite = False
fd.write('x')
self._reader = Reader(self._p1, checkReadInput)
self._writer = Writer... |
'In this test we have no writer. Make sure the reader doesn\'t
read anything.'
| def _testNoWriter(self):
| def checkReadInput(fd):
self.fail('Must not be called.')
def stopTest():
self._writer.close()
self._reactor.stop()
self._reader = Reader(self._p1, checkReadInput)
self._writer = Writer(self._p2, (lambda fd: fd.write('x')))
self._reactor.addWriter(self._writer)
se... |
'Runs callback(arg) after a number of IOLoop iterations.'
| def delay_callback(self, iterations, callback, arg):
| if (iterations == 0):
callback(arg)
else:
self.io_loop.add_callback(functools.partial(self.delay_callback, (iterations - 1), callback, arg))
|
'Traceback-aware replacement for
`~concurrent.futures.Future.set_exception`.'
| def set_exc_info(self, exc_info):
| self.__exc_info = exc_info
self.set_exception(exc_info[1])
|
'Closes the HTTPClient, freeing any resources used.'
| def close(self):
| if (not self._closed):
self._async_client.close()
self._io_loop.close()
self._closed = True
|
'Executes a request, returning an `HTTPResponse`.
The request may be either a string URL or an `HTTPRequest` object.
If it is a string, we construct an `HTTPRequest` using any additional
kwargs: ``HTTPRequest(request, **kwargs)``
If an error occurs during the fetch, we raise an `HTTPError`.'
| def fetch(self, request, **kwargs):
| response = self._io_loop.run_sync(functools.partial(self._async_client.fetch, request, **kwargs))
response.rethrow()
return response
|
'Destroys this HTTP client, freeing any file descriptors used.
Not needed in normal use, but may be helpful in unittests that
create and destroy http clients. No other methods may be called
on the `AsyncHTTPClient` after ``close()``.'
| def close(self):
| if (self._async_clients().get(self.io_loop) is self):
del self._async_clients()[self.io_loop]
|
'Executes a request, asynchronously returning an `HTTPResponse`.
The request may be either a string URL or an `HTTPRequest` object.
If it is a string, we construct an `HTTPRequest` using any additional
kwargs: ``HTTPRequest(request, **kwargs)``
This method returns a `.Future` whose result is an
`HTTPResponse`. The ``F... | def fetch(self, request, callback=None, **kwargs):
| if (not isinstance(request, HTTPRequest)):
request = HTTPRequest(url=request, **kwargs)
request.headers = httputil.HTTPHeaders(request.headers)
request = _RequestProxy(request, self.defaults)
future = TracebackFuture()
if (callback is not None):
callback = stack_context.wrap(callback... |
'Configures the `AsyncHTTPClient` subclass to use.
``AsyncHTTPClient()`` actually creates an instance of a subclass.
This method may be called with either a class object or the
fully-qualified name of such a class (or ``None`` to use the default,
``SimpleAsyncHTTPClient``)
If additional keyword arguments are given, the... | @classmethod
def configure(cls, impl, **kwargs):
| super(AsyncHTTPClient, cls).configure(impl, **kwargs)
|
'All parameters except ``url`` are optional.
:arg string url: URL to fetch
:arg string method: HTTP method, e.g. "GET" or "POST"
:arg headers: Additional HTTP headers to pass on the request
:arg body: HTTP body to pass on the request
:type headers: `~tornado.httputil.HTTPHeaders` or `dict`
:arg string auth_username: Us... | def __init__(self, url, method='GET', headers=None, body=None, auth_username=None, auth_password=None, auth_mode=None, connect_timeout=None, request_timeout=None, if_modified_since=None, follow_redirects=None, max_redirects=None, user_agent=None, use_gzip=None, network_interface=None, streaming_callback=None, header_ca... | if (headers is None):
headers = httputil.HTTPHeaders()
if if_modified_since:
headers['If-Modified-Since'] = httputil.format_timestamp(if_modified_since)
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.proxy_username = proxy_username
self.proxy_password = proxy_pass... |
'If there was an error on the request, raise an `HTTPError`.'
| def rethrow(self):
| if self.error:
raise self.error
|
'Parses the given WSGI environment to construct the request.'
| def __init__(self, environ):
| self.method = environ['REQUEST_METHOD']
self.path = urllib_parse.quote(from_wsgi_str(environ.get('SCRIPT_NAME', '')))
self.path += urllib_parse.quote(from_wsgi_str(environ.get('PATH_INFO', '')))
self.uri = self.path
self.arguments = {}
self.query = environ.get('QUERY_STRING', '')
if self.que... |
'Returns True if this request supports HTTP/1.1 semantics'
| def supports_http_1_1(self):
| return (self.version == 'HTTP/1.1')
|
'A dictionary of Cookie.Morsel objects.'
| @property
def cookies(self):
| if (not hasattr(self, '_cookies')):
self._cookies = Cookie.SimpleCookie()
if ('Cookie' in self.headers):
try:
self._cookies.load(native_str(self.headers['Cookie']))
except Exception:
self._cookies = None
return self._cookies
|
'Reconstructs the full URL for this request.'
| def full_url(self):
| return (((self.protocol + '://') + self.host) + self.uri)
|
'Returns the amount of time it took for this request to execute.'
| def request_time(self):
| if (self._finish_time is None):
return (time.time() - self._start_time)
else:
return (self._finish_time - self._start_time)
|
'Converts a `tornado.httpserver.HTTPRequest` to a WSGI environment.'
| @staticmethod
def environ(request):
| hostport = request.host.split(':')
if (len(hostport) == 2):
host = hostport[0]
port = int(hostport[1])
else:
host = request.host
port = (443 if (request.protocol == 'https') else 80)
environ = {'REQUEST_METHOD': request.method, 'SCRIPT_NAME': '', 'PATH_INFO': to_wsgi_str(... |
'Called by libcurl when it wants to change the file descriptors
it cares about.'
| def _handle_socket(self, event, fd, multi, data):
| event_map = {pycurl.POLL_NONE: ioloop.IOLoop.NONE, pycurl.POLL_IN: ioloop.IOLoop.READ, pycurl.POLL_OUT: ioloop.IOLoop.WRITE, pycurl.POLL_INOUT: (ioloop.IOLoop.READ | ioloop.IOLoop.WRITE)}
if (event == pycurl.POLL_REMOVE):
if (fd in self._fds):
self.io_loop.remove_handler(fd)
del ... |
'Called by libcurl to schedule a timeout.'
| def _set_timeout(self, msecs):
| if (self._timeout is not None):
self.io_loop.remove_timeout(self._timeout)
self._timeout = self.io_loop.add_timeout((self.io_loop.time() + (msecs / 1000.0)), self._handle_timeout)
|
'Called by IOLoop when there is activity on one of our
file descriptors.'
| def _handle_events(self, fd, events):
| action = 0
if (events & ioloop.IOLoop.READ):
action |= pycurl.CSELECT_IN
if (events & ioloop.IOLoop.WRITE):
action |= pycurl.CSELECT_OUT
while True:
try:
(ret, num_handles) = self._socket_action(fd, action)
except pycurl.error as e:
ret = e.args[0]... |
'Called by IOLoop when the requested timeout has passed.'
| def _handle_timeout(self):
| with stack_context.NullContext():
self._timeout = None
while True:
try:
(ret, num_handles) = self._socket_action(pycurl.SOCKET_TIMEOUT, 0)
except pycurl.error as e:
ret = e.args[0]
if (ret != pycurl.E_CALL_MULTI_PERFORM):
... |
'Called by IOLoop periodically to ask libcurl to process any
events it may have forgotten about.'
| def _handle_force_timeout(self):
| with stack_context.NullContext():
while True:
try:
(ret, num_handles) = self._multi.socket_all()
except pycurl.error as e:
ret = e.args[0]
if (ret != pycurl.E_CALL_MULTI_PERFORM):
break
self._finish_pending_requests(... |
'Process any requests that were completed by the last
call to multi.socket_action.'
| def _finish_pending_requests(self):
| while True:
(num_q, ok_list, err_list) = self._multi.info_read()
for curl in ok_list:
self._finish(curl)
for (curl, errnum, errmsg) in err_list:
self._finish(curl, errnum, errmsg)
if (num_q == 0):
break
self._process_queue()
|
'Called by the runner after the generator has yielded.
No other methods will be called on this object before ``start``.'
| def start(self, runner):
| raise NotImplementedError()
|
'Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.'
| def is_ready(self):
| raise NotImplementedError()
|
'Returns the value to use as the result of the yield expression.
This method will only be called once, and only after `is_ready`
has returned true.'
| def get_result(self):
| raise NotImplementedError()
|
'Adds ``key`` to the list of callbacks.'
| def register_callback(self, key):
| if (key in self.pending_callbacks):
raise KeyReuseError(('key %r is already pending' % (key,)))
self.pending_callbacks.add(key)
|
'Returns true if a result is available for ``key``.'
| def is_ready(self, key):
| if (key not in self.pending_callbacks):
raise UnknownKeyError(('key %r is not pending' % (key,)))
return (key in self.results)
|
'Sets the result for ``key`` and attempts to resume the generator.'
| def set_result(self, key, result):
| self.results[key] = result
self.run()
|
'Returns the result for ``key`` and unregisters it.'
| def pop_result(self, key):
| self.pending_callbacks.remove(key)
return self.results.pop(key)
|
'Starts or resumes the generator, running until it reaches a
yield point that is not ready.'
| def run(self):
| if (self.running or self.finished):
return
try:
self.running = True
while True:
if (self.exc_info is None):
try:
if (not self.yield_point.is_ready()):
return
next = self.yield_point.get_result()
... |
'Creates a AsyncHTTPClient.
Only a single AsyncHTTPClient instance exists per IOLoop
in order to provide limitations on the number of pending connections.
force_instance=True may be used to suppress this behavior.
max_clients is the number of concurrent requests that can be
in progress. Note that this arguments are on... | def initialize(self, io_loop, max_clients=10, hostname_mapping=None, max_buffer_size=104857600, resolver=None, defaults=None):
| super(SimpleAsyncHTTPClient, self).initialize(io_loop, defaults=defaults)
self.max_clients = max_clients
self.queue = collections.deque()
self.active = {}
self.max_buffer_size = max_buffer_size
if resolver:
self.resolver = resolver
self.own_resolver = False
else:
self... |
'Adds a new value for the given key.'
| def add(self, name, value):
| norm_name = _normalized_headers[name]
self._last_key = norm_name
if (norm_name in self):
dict.__setitem__(self, norm_name, ((native_str(self[norm_name]) + ',') + native_str(value)))
self._as_list[norm_name].append(value)
else:
self[norm_name] = value
|
'Returns all values for the given header as a list.'
| def get_list(self, name):
| norm_name = _normalized_headers[name]
return self._as_list.get(norm_name, [])
|
'Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.'
| def get_all(self):
| for (name, values) in self._as_list.items():
for value in values:
(yield (name, value))
|
'Updates the dictionary with a single header line.
>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get(\'content-type\')
\'text/html\''
| def parse_line(self, line):
| if line[0].isspace():
new_part = (' ' + line.lstrip())
self._as_list[self._last_key][(-1)] += new_part
dict.__setitem__(self, self._last_key, (self[self._last_key] + new_part))
else:
(name, value) = line.split(':', 1)
self.add(name, value.strip())
|
'Returns a dictionary from HTTP header text.
>>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
>>> sorted(h.items())
[(\'Content-Length\', \'42\'), (\'Content-Type\', \'text/html\')]'
| @classmethod
def parse(cls, headers):
| h = cls()
for line in headers.splitlines():
if line:
h.parse_line(line)
return h
|
'Hook for subclass initialization.
A dictionary passed as the third argument of a url spec will be
supplied as keyword arguments to initialize().
Example::
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
app = Application([
(r\'/user/(.*)\', Profil... | def initialize(self):
| pass
|
'An alias for `self.application.settings <Application.settings>`.'
| @property
def settings(self):
| return self.application.settings
|
'Called at the beginning of a request before `get`/`post`/etc.
Override this method to perform common initialization regardless
of the request method.
Asynchronous support: Decorate this method with `.gen.coroutine`
or `.return_future` to make it asynchronous (the
`asynchronous` decorator cannot be used on `prepare`).... | def prepare(self):
| pass
|
'Called after the end of a request.
Override this method to perform cleanup, logging, etc.
This method is a counterpart to `prepare`. ``on_finish`` may
not produce any output, as it is called after the response
has been sent to the client.'
| def on_finish(self):
| pass
|
'Called in async handlers if the client closed the connection.
Override this to clean up resources associated with
long-lived connections. Note that this method is called only if
the connection was closed during asynchronous processing; if you
need to do cleanup after every request override `on_finish`
instead.
Proxie... | def on_connection_close(self):
| pass
|
'Resets all headers and content for this response.'
| def clear(self):
| self._headers = httputil.HTTPHeaders({'Server': ('TornadoServer/%s' % tornado.version), 'Content-Type': 'text/html; charset=UTF-8', 'Date': httputil.format_timestamp(time.time())})
self.set_default_headers()
if ((not self.request.supports_http_1_1()) and getattr(self.request, 'connection', None) and (not... |
'Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom ``Server`` header.
Note that setting such headers in the normal flow of request
processing may not do what you want, since headers may be reset
during error handling.'
| def set_default_headers(self):
| pass
|
'Sets the status code for our response.
:arg int status_code: Response status code. If ``reason`` is ``None``,
it must be present in `httplib.responses <http.client.responses>`.
:arg string reason: Human-readable reason phrase describing the status
code. If ``None``, it will be filled in from
`httplib.responses <http.c... | def set_status(self, status_code, reason=None):
| self._status_code = status_code
if (reason is not None):
self._reason = escape.native_str(reason)
else:
try:
self._reason = httputil.responses[status_code]
except KeyError:
raise ValueError('unknown status code %d', status_code)
|
'Returns the status code for our response.'
| def get_status(self):
| return self._status_code
|
'Sets the given response header name and value.
If a datetime is given, we automatically format it according to the
HTTP specification. If the value is not a string, we convert it to
a string. All header values are then encoded as UTF-8.'
| def set_header(self, name, value):
| self._headers[name] = self._convert_header_value(value)
|
'Adds the given response header and value.
Unlike `set_header`, `add_header` may be called multiple times
to return multiple values for the same header.'
| def add_header(self, name, value):
| self._headers.add(name, self._convert_header_value(value))
|
'Clears an outgoing header, undoing a previous `set_header` call.
Note that this method does not apply to multi-valued headers
set by `add_header`.'
| def clear_header(self, name):
| if (name in self._headers):
del self._headers[name]
|
'Returns the value of the argument with the given name.
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_argument(self, name, default=_ARG_DEFAULT, strip=True):
| args = self.get_arguments(name, strip=strip)
if (not args):
if (default is self._ARG_DEFAULT):
raise MissingArgumentError(name)
return default
return args[(-1)]
|
'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):
| values = []
for v in self.request.arguments.get(name, []):
v = self.decode_argument(v, name=name)
if isinstance(v, unicode_type):
v = RequestHandler._remove_control_chars_regex.sub(' ', v)
if strip:
v = v.strip()
values.append(v)
return values
|
'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):
| return _unicode(value)
|
'An alias for `self.request.cookies <.httpserver.HTTPRequest.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 http://docs.python.org/library/cookie.html#morsel-objects
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.'
| 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.'
| def clear_all_cookies(self):
| for name in self.request.cookies:
self.clear_cookie(name)
|
'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, **kwargs):
| self.set_cookie(name, self.create_signed_value(name, value), 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.'
| def create_signed_value(self, name, value):
| self.require_setting('cookie_secret', 'secure cookies')
return create_signed_value(self.application.settings['cookie_secret'], name, value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.