desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'The handler callback receives the same fd object it passed in.'
def test_handler_callback_file_object(self):
(server_sock, port) = bind_unused_port() fds = [] def handle_connection(fd, events): fds.append(fd) (conn, addr) = server_sock.accept() conn.close() self.stop() self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ) with contextlib.closing(socket.socket...
'Calling start() twice should raise an error, not deadlock.'
def test_reentrant(self):
returned_from_start = [False] got_exception = [False] def callback(): try: self.io_loop.start() returned_from_start[0] = True except Exception: got_exception[0] = True self.stop() self.io_loop.add_callback(callback) self.wait() self.ass...
'Uncaught exceptions get logged by the IOLoop.'
def test_exception_logging(self):
with NullContext(): self.io_loop.add_callback((lambda : (1 / 0))) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, 'Exception in callback'): self.wait()
'The IOLoop examines exceptions from Futures and logs them.'
def test_exception_logging_future(self):
with NullContext(): @gen.coroutine def callback(): self.io_loop.add_callback(self.stop) (1 / 0) self.io_loop.add_callback(callback) with ExpectLog(app_log, 'Exception in callback'): self.wait()
'The IOLoop examines exceptions from awaitables and logs them.'
@skipBefore35 def test_exception_logging_native_coro(self):
namespace = exec_test(globals(), locals(), '\n async def callback():\n self.io_loop.add_callback(self.stop)\n 1 / 0\n ') with NullContext(): ...
'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.0), 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') existing_key = os.path.join(module_dir, 'test.key') self.assertRaises((ValueError, IOError), HTTPServer, application, ssl_options={'certfile': '/__mising__.crt'}) self.a...
'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))
'Runners shouldn\'t GC if future is alive'
@gen_test def test_gc(self):
weakref_scope = [None] def callback(): gc.collect(2) weakref_scope[0]().set_result(123) @gen.coroutine def tester(): fut = Future() weakref_scope[0] = weakref.ref(fut) self.io_loop.add_callback(callback) (yield fut) (yield gen.with_timeout(datetime.tim...
'Close a websocket connection and wait for the server side. If we don\'t wait here, there are sometimes leak warnings in the tests.'
@gen.coroutine def close(self, ws):
ws.close() (yield self.close_future)
'Gets called when we decorate a class'
def __call__(self, _handler):
name = ((self.name and self.name) or _handler.__name__) self._routes.append((self._uri, _handler, name)) return _handler
'Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout.'
def wait(self, timeout=None):
waiter = Future() self._waiters.append(waiter) if timeout: def on_timeout(): waiter.set_result(False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback((lambda _...
'Wake ``n`` waiters.'
def notify(self, n=1):
waiters = [] while (n and self._waiters): waiter = self._waiters.popleft() if (not waiter.done()): n -= 1 waiters.append(waiter) for waiter in waiters: waiter.set_result(True)
'Wake all waiters.'
def notify_all(self):
self.notify(len(self._waiters))
'Return ``True`` if the internal flag is true.'
def is_set(self):
return self._future.done()
'Set the internal flag to ``True``. All waiters are awakened. Calling `.wait` once the flag is set will not block.'
def set(self):
if (not self._future.done()): self._future.set_result(None)
'Reset the internal flag to ``False``. Calls to `.wait` will block until `.set` is called.'
def clear(self):
if self._future.done(): self._future = Future()
'Block until the internal flag is true. Returns a Future, which raises `tornado.gen.TimeoutError` after a timeout.'
def wait(self, timeout=None):
if (timeout is None): return self._future else: return gen.with_timeout(timeout, self._future)
'Increment the counter and wake one waiter.'
def release(self):
self._value += 1 while self._waiters: waiter = self._waiters.popleft() if (not waiter.done()): self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) break
'Decrement the counter. Returns a Future. Block if the counter is zero and wait for a `.release`. The Future raises `.TimeoutError` after the deadline.'
def acquire(self, timeout=None):
waiter = Future() if (self._value > 0): self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout(): waiter.set_exception(gen.TimeoutError()) self._garbage_colle...
'Increment the counter and wake one waiter.'
def release(self):
if (self._value >= self._initial_value): raise ValueError('Semaphore released too many times') super(BoundedSemaphore, self).release()
'Attempt to lock. Returns a Future. Returns a Future, which raises `tornado.gen.TimeoutError` after a timeout.'
def acquire(self, timeout=None):
return self._block.acquire(timeout)
'Unlock. The first coroutine in line waiting for `acquire` gets the lock. If not locked, raise a `RuntimeError`.'
def release(self):
try: self._block.release() except ValueError: raise RuntimeError('release unlocked lock')
'Cancel the operation, if possible. Tornado ``Futures`` do not support cancellation, so this method always returns False.'
def cancel(self):
return False
'Returns True if the operation has been cancelled. Tornado ``Futures`` do not support cancellation, so this method always returns False.'
def cancelled(self):
return False
'Returns True if this operation is currently running.'
def running(self):
return (not self._done)
'Returns True if the future has finished running.'
def done(self):
return self._done
'If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used.'
def result(self, timeout=None):
self._clear_tb_log() if (self._result is not None): return self._result if (self._exc_info is not None): try: raise_exc_info(self._exc_info) finally: self = None self._check_done() return self._result
'If the operation raised an exception, return the `Exception` object. Otherwise returns None. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used.'
def exception(self, timeout=None):
self._clear_tb_log() if (self._exc_info is not None): return self._exc_info[1] else: self._check_done() return None
'Attaches the given callback to the `Future`. It will be invoked with the `Future` as its argument when the Future has finished running and its result is available. In Tornado consider using `.IOLoop.add_future` instead of calling `add_done_callback` directly.'
def add_done_callback(self, fn):
if self._done: fn(self) else: self._callbacks.append(fn)
'Sets the result of a ``Future``. It is undefined to call any of the ``set`` methods more than once on the same object.'
def set_result(self, result):
self._result = result self._set_done()
'Sets the exception of a ``Future.``'
def set_exception(self, exception):
self.set_exc_info((exception.__class__, exception, getattr(exception, '__traceback__', None)))
'Returns a tuple in the same format as `sys.exc_info` or None. .. versionadded:: 4.0'
def exc_info(self):
self._clear_tb_log() return self._exc_info
'Sets the exception information of a ``Future.`` Preserves tracebacks on Python 2. .. versionadded:: 4.0'
def set_exc_info(self, exc_info):
self._exc_info = exc_info self._log_traceback = True if (not _GC_CYCLE_FINALIZERS): self._tb_logger = _TracebackLogger(exc_info) try: self._set_done() finally: if (self._log_traceback and (self._tb_logger is not None)): self._tb_logger.activate() self._exc_inf...
'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` unless the ``raise_error`` ke...
def fetch(self, request, **kwargs):
response = self._io_loop.run_sync(functools.partial(self._async_client.fetch, request, **kwargs)) return response
'Destroys this HTTP client, freeing any file descriptors used. This method is **not needed in normal use** due to the way that `AsyncHTTPClient` objects are transparently reused. ``close()`` is generally only necessary when either the `.IOLoop` is also being closed, or the ``force_instance=True`` argument was used when...
def close(self):
if self._closed: return self._closed = True if (self._instance_cache is not None): if (self._instance_cache.get(self.io_loop) is not self): raise RuntimeError('inconsistent AsyncHTTPClient cache') del self._instance_cache[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`. By defau...
def fetch(self, request, callback=None, raise_error=True, **kwargs):
if self._closed: raise RuntimeError('fetch() called on closed AsyncHTTPClient') if (not isinstance(request, HTTPRequest)): request = HTTPRequest(url=request, **kwargs) elif kwargs: raise ValueError("kwargs can't be used if request is an HTTPRequest...
'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 :type headers: `~tornado.httputil.HTTPHeaders` or `dict` :arg body: HTTP request body as a string (byte or unicode; if unicode the...
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...
self.headers = headers if if_modified_since: self.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_password self.proxy_auth_mode = pro...
'If there was an error on the request, raise an `HTTPError`.'
def rethrow(self):
if self.error: raise self.error
'Converts a `tornado.httputil.HTTPServerRequest` 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._multi.socket_action(fd, action) except pycurl.error as e: ret = e.a...
'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._multi.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()
'Returns True if this iterator has no more results.'
def done(self):
if (self._finished or self._unfinished): return False self.current_index = self.current_future = None return True
'Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs.'
def next(self):
self._running_future = TracebackFuture() if self._finished: self._return_result(self._finished.popleft()) return self._running_future
'Called set the returned future\'s state that of the future we yielded, and set the current future for the iterator.'
def _return_result(self, done):
chain_future(done, self._running_future) self.current_future = done self.current_index = self._unfinished.pop(done)
'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()
'Adapts a `.Future` to the `YieldPoint` interface. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated.'
def __init__(self, future, io_loop=None):
self.future = future self.io_loop = (io_loop or IOLoop.current())
'Adds ``key`` to the list of callbacks.'
def register_callback(self, key):
if (self.pending_callbacks is None): self.pending_callbacks = set() self.results = {} 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 ((self.pending_callbacks is None) or (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 if ((self.yield_point is not None) and self.yield_point.is_ready()): try: self.future.set_result(self.yield_point.get_result()) except: self.future.set_exc_info(sys.exc_info()) self.yield_point = None 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: future = self.future if (not future.done()): return self.future = None try: orig_stack_contexts = stack_context._state.contexts ...
'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. Note that because of this implicit reuse, unless ``force_instance`` is used, only the first call to th...
def initialize(self, io_loop, max_clients=10, hostname_mapping=None, max_buffer_size=104857600, resolver=None, defaults=None, max_header_size=None, max_body_size=None):
super(SimpleAsyncHTTPClient, self).initialize(io_loop, defaults=defaults) self.max_clients = max_clients self.queue = collections.deque() self.active = {} self.waiting = {} self.max_buffer_size = max_buffer_size self.max_header_size = max_header_size self.max_body_size = max_body_size ...
'Timeout callback of request. Construct a timeout HTTPResponse when a timeout occurs. :arg object key: A simple object to mark the request. :info string key: More detailed timeout information.'
def _on_timeout(self, key, info=None):
(request, callback, timeout_handle) = self.waiting[key] self.queue.remove((key, request, callback)) error_message = ('Timeout {0}'.format(info) if info else 'Timeout') timeout_response = HTTPResponse(request, 599, error=HTTPError(599, error_message), request_time=(self.io_loop.time() - request.start_...
'Timeout callback of _HTTPConnection instance. Raise a timeout HTTPError when a timeout occurs. :info string key: More detailed timeout information.'
def _on_timeout(self, info=None):
self._timeout = None error_message = ('Timeout {0}'.format(info) if info else 'Timeout') if (self.final_callback is not None): raise HTTPError(599, error_message)
'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): self._dict[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 self._dict[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 _CRLF_RE.split(headers): if line: h.parse_line(line) return h
'Returns True if this request supports HTTP/1.1 semantics. .. deprecated:: 4.0 Applications are less likely to need this information with the introduction of `.HTTPConnection`. If you still need it, access the ``version`` attribute directly.'
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: parsed = parse_cookie(self.headers['Cookie']) except Exception: pass else: for (k, v) in parsed.items(): ...
'Writes the given chunk to the response stream. .. deprecated:: 4.0 Use ``request.connection`` and the `.HTTPConnection` methods to write the response.'
def write(self, chunk, callback=None):
assert isinstance(chunk, bytes) assert self.version.startswith('HTTP/1.'), 'deprecated interface only supported in HTTP/1.x' self.connection.write(chunk, callback=callback)
'Finishes this HTTP request on the open connection. .. deprecated:: 4.0 Use ``request.connection`` and the `.HTTPConnection` methods to write the response.'
def finish(self):
self.connection.finish() self._finish_time = time.time()
'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)
'Returns the client\'s SSL certificate, if any. To use client certificates, the HTTPServer\'s `ssl.SSLContext.verify_mode` field must be set, e.g.:: ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_ctx.load_cert_chain("foo.crt", "foo.key") ssl_ctx.load_verify_locations("cacerts.pem") ssl_ctx.verify_mod...
def get_ssl_certificate(self, binary_form=False):
try: return self.connection.stream.socket.getpeercert(binary_form=binary_form) except SSLError: return None
'This method is called by the server when a new request has started. :arg server_conn: is an opaque object representing the long-lived (e.g. tcp-level) connection. :arg request_conn: is a `.HTTPConnection` object for a single request/response exchange. This method should return a `.HTTPMessageDelegate`.'
def start_request(self, server_conn, request_conn):
raise NotImplementedError()
'This method is called when a connection has been closed. :arg server_conn: is a server connection that has previously been passed to ``start_request``.'
def on_close(self, server_conn):
pass
'Called when the HTTP headers have been received and parsed. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine` depending on whether this is a client or server message. :arg headers: a `.HTTPHeaders` instance. Some `.HTTPConnection` methods can only be called during ``headers_received``. May return a `.Futu...
def headers_received(self, start_line, headers):
pass
'Called when a chunk of data has been received. May return a `.Future` for flow control.'
def data_received(self, chunk):
pass
'Called after the last chunk of data has been received.'
def finish(self):
pass
'Called if the connection is closed without finishing the request. If ``headers_received`` is called, either ``finish`` or ``on_connection_close`` will be called, but not both.'
def on_connection_close(self):
pass
'Write an HTTP header block. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`. :arg headers: a `.HTTPHeaders` instance. :arg chunk: the first (optional) chunk of data. This is an optimization so that small responses can be written in the same call as their headers. :arg callback: a callback to be run whe...
def write_headers(self, start_line, headers, chunk=None, callback=None):
raise NotImplementedError()
'Writes a chunk of body data. The callback will be run when the write is complete. If no callback is given, returns a Future.'
def write(self, chunk, callback=None):
raise NotImplementedError()
'Indicates that the last body data has been written.'
def finish(self):
raise NotImplementedError()
'Hook for subclass initialization. Called for each request. 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([...
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):
if _has_stream_request_body(self.__class__): if (not self.request.body.done()): self.request.body.set_exception(iostream.StreamClosedError()) self.request.body.exception()
'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() self._write_buffer = [] self._status_code = 200 self._reason = httputil.responses[200]
'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):
return self._get_argument(name, default, self.request.arguments, strip)