desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return l...
def default(self, o):
raise TypeError((repr(o) + ' is not JSON serializable'))
'Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) \'{"foo": ["bar", "baz"]}\''
def encode(self, o):
if isinstance(o, basestring): if isinstance(o, str): _encoding = self.encoding if ((_encoding is not None) and (not (_encoding == 'utf-8'))): o = o.decode(_encoding) if self.ensure_ascii: return encode_basestring_ascii(o) else: ...
'Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)'
def iterencode(self, o, _one_shot=False):
if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if (self.encoding != 'utf-8'): def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): i...
'``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook...
def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True):
self.encoding = encoding self.object_hook = object_hook self.parse_float = (parse_float or float) self.parse_int = (parse_int or int) self.parse_constant = (parse_constant or _CONSTANTS.__getitem__) self.strict = strict self.parse_object = JSONObject self.parse_array = JSONArray self...
'Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)'
def decode(self, s, _w=WHITESPACE.match):
(obj, end) = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if (end != len(s)): raise ValueError(errmsg('Extra data', s, end, len(s))) return obj
'Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end.'
def raw_decode(self, s, idx=0):
try: (obj, end) = self.scan_once(s, idx) except StopIteration: raise ValueError('No JSON object could be decoded') return (obj, end)
':arg bool color: Enables color support. :arg string fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. :arg dict colors: color mappings from logging level to terminal colo...
def __init__(self, fmt=DEFAULT_FORMAT, datefmt=DEFAULT_DATE_FORMAT, style='%', color=True, colors=DEFAULT_COLORS):
logging.Formatter.__init__(self, datefmt=datefmt) self._fmt = fmt self._colors = {} if (color and _stderr_supports_color()): if (curses is not None): fg_color = (curses.tigetstr('setaf') or curses.tigetstr('setf') or '') if ((3, 0) < sys.version_info < (3, 2, 3)): ...
'Returns the read file descriptor for this waker. Must be suitable for use with ``select()`` or equivalent on the local platform.'
def fileno(self):
raise NotImplementedError()
'Returns the write file descriptor for this waker.'
def write_fileno(self):
raise NotImplementedError()
'Triggers activity on the waker\'s file descriptor.'
def wake(self):
raise NotImplementedError()
'Called after the listen has woken up to do any necessary cleanup.'
def consume(self):
raise NotImplementedError()
'Closes the waker\'s file descriptor(s).'
def close(self):
raise NotImplementedError()
'Rewrite the ``remote_ip`` and ``protocol`` fields.'
def _apply_xheaders(self, headers):
ip = headers.get('X-Forwarded-For', self.remote_ip) for ip in (cand.strip() for cand in reversed(ip.split(','))): if (ip not in self.trusted_downstream): break ip = headers.get('X-Real-Ip', ip) if netutil.is_valid_ip(ip): self.remote_ip = ip proto_header = headers.get('X-...
'Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next request on the same connection.'
def _unapply_xheaders(self):
self.remote_ip = self._orig_remote_ip self.protocol = self._orig_protocol
'Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields ...
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
raise NotImplementedError()
'Closes the `Resolver`, freeing any resources used. .. versionadded:: 3.1'
def close(self):
pass
'Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_length`` is given, some input data may be left over in ``unconsumed_tail``; you must retrieve this value and pass i...
def decompress(self, value, max_length=None):
return self.decompressobj.decompress(value, max_length)
'Returns the unconsumed portion left over'
@property def unconsumed_tail(self):
return self.decompressobj.unconsumed_tail
'Return any remaining buffered data not yet returned by decompress. Also checks for errors such as truncated input. No other methods may be called on this object after `flush`.'
def flush(self):
return self.decompressobj.flush()
'Returns the base class of a configurable hierarchy. This will normally return the class in which it is defined. (which is *not* necessarily the same as the cls classmethod parameter).'
@classmethod def configurable_base(cls):
raise NotImplementedError()
'Returns the implementation class to be used if none is configured.'
@classmethod def configurable_default(cls):
raise NotImplementedError()
'Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters.'
@classmethod def configure(cls, impl, **kwargs):
base = cls.configurable_base() if isinstance(impl, (str, unicode_type)): impl = import_object(impl) if ((impl is not None) and (not issubclass(impl, cls))): raise ValueError(('Invalid subclass of %s' % cls)) base.__impl_class = impl base.__impl_kwargs = kwargs
'Returns the currently configured class.'
@classmethod def configured_class(cls):
base = cls.configurable_base() if (cls.__impl_class is None): base.__impl_class = cls.configurable_default() return base.__impl_class
'Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present.'
def get_old_value(self, args, kwargs, default=None):
if ((self.arg_pos is not None) and (len(args) > self.arg_pos)): return args[self.arg_pos] else: return kwargs.get(self.name, default)
'Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None ...
def replace(self, new_value, args, kwargs):
if ((self.arg_pos is not None) and (len(args) > self.arg_pos)): old_value = args[self.arg_pos] args = list(args) args[self.arg_pos] = new_value else: old_value = kwargs.get(self.name) kwargs[self.name] = new_value return (old_value, args, kwargs)
'Construct a Template. :arg str template_string: the contents of the template file. :arg str name: the filename from which the template was loaded (used for error message). :arg tornado.template.BaseLoader loader: the `~tornado.template.BaseLoader` responsible for this template, used to resolve ``{% include %}`` and ``...
def __init__(self, template_string, name='<string>', loader=None, compress_whitespace=_UNSET, autoescape=_UNSET, whitespace=None):
self.name = escape.native_str(name) if (compress_whitespace is not _UNSET): if (whitespace is not None): raise Exception('cannot set both whitespace and compress_whitespace') whitespace = ('single' if compress_whitespace else 'all') if (whitespace is None): ...
'Generate this template with the given arguments.'
def generate(self, **kwargs):
namespace = {'escape': escape.xhtml_escape, 'xhtml_escape': escape.xhtml_escape, 'url_escape': escape.url_escape, 'json_encode': escape.json_encode, 'squeeze': escape.squeeze, 'linkify': escape.linkify, 'datetime': datetime, '_tt_utf8': escape.utf8, '_tt_string_types': (unicode_type, bytes), '__name__': self.name.r...
'Construct a template loader. :arg str autoescape: The name of a function in the template namespace, such as "xhtml_escape", or ``None`` to disable autoescaping by default. :arg dict namespace: A dictionary to be added to the default template namespace, or ``None``. :arg str whitespace: A string specifying default beha...
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None, whitespace=None):
self.autoescape = autoescape self.namespace = (namespace or {}) self.whitespace = whitespace self.templates = {} self.lock = threading.RLock()
'Resets the cache of compiled templates.'
def reset(self):
with self.lock: self.templates = {}
'Converts a possibly-relative path to absolute (used internally).'
def resolve_path(self, name, parent_path=None):
raise NotImplementedError()
'Loads a template.'
def load(self, name, parent_path=None):
name = self.resolve_path(name, parent_path=parent_path) with self.lock: if (name not in self.templates): self.templates[name] = self._create_template(name) return self.templates[name]
'Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than one ``IOLoop`` it may be necessary to ...
def set_exit_callback(self, callback):
self._exit_callback = stack_context.wrap(callback) Subprocess.initialize(self.io_loop) Subprocess._waiting[self.pid] = self Subprocess._try_cleanup_process(self.pid)
'Returns a `.Future` which resolves when the process exits. Usage:: ret = yield proc.wait_for_exit() This is a coroutine-friendly alternative to `set_exit_callback` (and a replacement for the blocking `subprocess.Popen.wait`). By default, raises `subprocess.CalledProcessError` if the process has a non-zero exit status....
def wait_for_exit(self, raise_error=True):
future = Future() def callback(ret): if ((ret != 0) and raise_error): future.set_exception(CalledProcessError(ret, None)) else: future.set_result(ret) self.set_exit_callback(callback) return future
'Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are each running in separate threads). .. versionchanged:: 4.1 The ``io_loo...
@classmethod def initialize(cls, io_loop=None):
if cls._initialized: return if (io_loop is None): io_loop = ioloop.IOLoop.current() cls._old_sigchld = signal.signal(signal.SIGCHLD, (lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))) cls._initialized = True
'Removes the ``SIGCHLD`` handler.'
@classmethod def uninitialize(cls):
if (not cls._initialized): return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
'Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return ad...
@staticmethod def split(addrinfo):
primary = [] secondary = [] primary_af = addrinfo[0][0] for (af, addr) in addrinfo: if (af == primary_af): primary.append((af, addr)) else: secondary.append((af, addr)) return (primary, secondary)
'Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). Using the ``source_ip`` kwarg, one can specify the source IP address to use when establishing the connection. In case the user needs to resolve and use a specific interface, it has to be handle...
@gen.coroutine def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None, max_buffer_size=None, source_ip=None, source_port=None):
addrinfo = (yield self.resolver.resolve(host, port, af)) connector = _Connector(addrinfo, self.io_loop, functools.partial(self._create_stream, max_buffer_size, source_ip=source_ip, source_port=source_port)) (af, addr, stream) = (yield connector.start()) if (ssl_options is not None): stream = (yi...
'The interval for websocket keep-alive pings. Set websocket_ping_interval = 0 to disable pings.'
@property def ping_interval(self):
return self.settings.get('websocket_ping_interval', None)
'If no ping is received in this many seconds, close the websocket connection (VPNs, etc. can fail to cleanly close ws connections). Default is max of 3 pings or 30 seconds.'
@property def ping_timeout(self):
return self.settings.get('websocket_ping_timeout', None)
'Maximum allowed message size. If the remote peer sends a message larger than this, the connection will be closed. Default is 10MiB.'
@property def max_message_size(self):
return self.settings.get('websocket_max_message_size', None)
'Sends the given message to the client of this Web Socket. The message may be either a string or a dict (which will be encoded as json). If the ``binary`` argument is false, the message will be sent as utf8; in binary mode any byte string is allowed. If the connection is already closed, raises `WebSocketClosedError`. ...
def write_message(self, message, binary=False):
if (self.ws_connection is None): raise WebSocketClosedError() if isinstance(message, dict): message = tornado.escape.json_encode(message) return self.ws_connection.write_message(message, binary=binary)
'Invoked when a new WebSocket requests specific subprotocols. ``subprotocols`` is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, or ``None`` to not select a subprotocol. Failure to select a subprotocol does not automati...
def select_subprotocol(self, subprotocols):
return None
'Override to return compression options for the connection. If this method returns None (the default), compression will be disabled. If it returns a dict (even an empty one), it will be enabled. The contents of the dict may be used to control the following compression options: ``compression_level`` specifies the comp...
def get_compression_options(self):
return None
'Invoked when a new WebSocket is opened. The arguments to `open` are extracted from the `tornado.web.URLSpec` regular expression, just like the arguments to `tornado.web.RequestHandler.get`.'
def open(self, *args, **kwargs):
pass
'Handle incoming messages on the WebSocket This method must be overridden. .. versionchanged:: 4.5 ``on_message`` can be a coroutine.'
def on_message(self, message):
raise NotImplementedError
'Send ping frame to the remote end.'
def ping(self, data):
if (self.ws_connection is None): raise WebSocketClosedError() self.ws_connection.write_ping(data)
'Invoked when the response to a ping frame is received.'
def on_pong(self, data):
pass
'Invoked when the a ping frame is received.'
def on_ping(self, data):
pass
'Invoked when the WebSocket is closed. If the connection was closed cleanly and a status code or reason phrase was supplied, these values will be available as the attributes ``self.close_code`` and ``self.close_reason``. .. versionchanged:: 4.0 Added ``close_code`` and ``close_reason`` attributes.'
def on_close(self):
pass
'Closes this Web Socket. Once the close handshake is successful the socket will be closed. ``code`` may be a numeric status code, taken from the values defined in `RFC 6455 section 7.4.1 <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_. ``reason`` may be a textual message about why the connection is closing. Thes...
def close(self, code=None, reason=None):
if self.ws_connection: self.ws_connection.close(code, reason) self.ws_connection = None
'Override to enable support for allowing alternate origins. The ``origin`` argument is the value of the ``Origin`` HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebS...
def check_origin(self, origin):
parsed_origin = urlparse(origin) origin = parsed_origin.netloc origin = origin.lower() host = self.request.headers.get('Host') return (origin == host)
'Set the no-delay flag for this stream. By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle\'s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwi...
def set_nodelay(self, value):
self.stream.set_nodelay(value)
'Runs the given callback with exception handling. If the callback is a coroutine, returns its Future. On error, aborts the websocket connection and returns None.'
def _run_callback(self, callback, *args, **kwargs):
try: result = callback(*args, **kwargs) except Exception: app_log.error('Uncaught exception in %s', getattr(self.request, 'path', None), exc_info=True) self._abort() else: if (result is not None): result = gen.convert_yielded(result) self.stre...
'Instantly aborts the WebSocket connection by closing the socket'
def _abort(self):
self.client_terminated = True self.server_terminated = True self.stream.close() self.close()
'Verifies all invariant- and required headers If a header is missing or have an incorrect value ValueError will be raised'
def _handle_websocket_headers(self):
fields = ('Host', 'Sec-Websocket-Key', 'Sec-Websocket-Version') if (not all(map((lambda f: self.request.headers.get(f)), fields))): raise ValueError('Missing/Invalid WebSocket headers')
'Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key.'
@staticmethod def compute_accept_value(key):
sha1 = hashlib.sha1() sha1.update(utf8(key)) sha1.update('258EAFA5-E914-47DA-95CA-C5AB0DC85B11') return native_str(base64.b64encode(sha1.digest()))
'Process the headers sent by the server to this client connection. \'key\' is the websocket handshake challenge/response key.'
def _process_server_headers(self, key, headers):
assert (headers['Upgrade'].lower() == 'websocket') assert (headers['Connection'].lower() == 'upgrade') accept = self.compute_accept_value(key) assert (headers['Sec-Websocket-Accept'] == accept) extensions = self._parse_extensions_header(headers) for ext in extensions: if ((ext[0] == 'per...
'Converts a websocket agreed_parameters set to keyword arguments for our compressor objects.'
def _get_compressor_options(self, side, agreed_parameters, compression_options=None):
options = dict(persistent=((side + '_no_context_takeover') not in agreed_parameters)) wbits_header = agreed_parameters.get((side + '_max_window_bits'), None) if (wbits_header is None): options['max_wbits'] = zlib.MAX_WBITS else: options['max_wbits'] = int(wbits_header) options['compr...
'Sends the given message to the client of this Web Socket.'
def write_message(self, message, binary=False):
if binary: opcode = 2 else: opcode = 1 message = tornado.escape.utf8(message) assert isinstance(message, bytes) self._message_bytes_out += len(message) flags = 0 if self._compressor: message = self._compressor.compress(message) flags |= self.RSV1 return se...
'Send ping frame.'
def write_ping(self, data):
assert isinstance(data, bytes) self._write_frame(True, 9, data)
'Execute on_message, returning its Future if it is a coroutine.'
def _handle_message(self, opcode, data):
if self.client_terminated: return if self._frame_compressed: data = self._decompressor.decompress(data) if (opcode == 1): self._message_bytes_in += len(data) try: decoded = data.decode('utf-8') except UnicodeDecodeError: self._abort() ...
'Closes the WebSocket connection.'
def close(self, code=None, reason=None):
if (not self.server_terminated): if (not self.stream.closed()): if ((code is None) and (reason is not None)): code = 1000 if (code is None): close_data = '' else: close_data = struct.pack('>H', code) if (reason i...
'Start sending periodic pings to keep the connection alive'
def start_pinging(self):
if (self.ping_interval > 0): self.last_ping = self.last_pong = IOLoop.current().time() self.ping_callback = PeriodicCallback(self.periodic_ping, (self.ping_interval * 1000)) self.ping_callback.start()
'Send a ping to keep the websocket alive Called periodically if the websocket_ping_interval is set and non-zero.'
def periodic_ping(self):
if (self.stream.closed() and (self.ping_callback is not None)): self.ping_callback.stop() return now = IOLoop.current().time() since_last_pong = (now - self.last_pong) since_last_ping = (now - self.last_ping) if ((since_last_ping < (2 * self.ping_interval)) and (since_last_pong > sel...
'Closes the websocket connection. ``code`` and ``reason`` are documented under `WebSocketHandler.close`. .. versionadded:: 3.2 .. versionchanged:: 4.0 Added the ``code`` and ``reason`` arguments.'
def close(self, code=None, reason=None):
if (self.protocol is not None): self.protocol.close(code, reason) self.protocol = None
'Sends a message to the WebSocket server.'
def write_message(self, message, binary=False):
return self.protocol.write_message(message, binary)
'Reads a message from the WebSocket server. If on_message_callback was specified at WebSocket initialization, this function will never return messages Returns a future whose result is the message, or None if the connection is closed. If a callback argument is given it will be called with the future when it is ready.'
def read_message(self, callback=None):
assert (self.read_future is None) future = TracebackFuture() if self.read_queue: future.set_result(self.read_queue.popleft()) else: self.read_future = future if (callback is not None): self.io_loop.add_future(future, callback) return future
'Number of items allowed in the queue.'
@property def maxsize(self):
return self._maxsize
'Number of items in the queue.'
def qsize(self):
return len(self._queue)
'Put an item into the queue, perhaps waiting until there is room. Returns a Future, which raises `tornado.gen.TimeoutError` after a timeout.'
def put(self, item, timeout=None):
try: self.put_nowait(item) except QueueFull: future = Future() self._putters.append((item, future)) _set_timeout(future, timeout) return future else: return gen._null_future
'Put an item into the queue without blocking. If no free slot is immediately available, raise `QueueFull`.'
def put_nowait(self, item):
self._consume_expired() if self._getters: assert self.empty(), 'queue non-empty, why are getters waiting?' getter = self._getters.popleft() self.__put_internal(item) getter.set_result(self._get()) elif self.full(): raise QueueFull else: self...
'Remove and return an item from the queue. Returns a Future which resolves once an item is available, or raises `tornado.gen.TimeoutError` after a timeout.'
def get(self, timeout=None):
future = Future() try: future.set_result(self.get_nowait()) except QueueEmpty: self._getters.append(future) _set_timeout(future, timeout) return future
'Remove and return an item from the queue without blocking. Return an item if one is immediately available, else raise `QueueEmpty`.'
def get_nowait(self):
self._consume_expired() if self._putters: assert self.full(), 'queue not full, why are putters waiting?' (item, putter) = self._putters.popleft() self.__put_internal(item) putter.set_result(None) return self._get() elif self.qsize(): return s...
'Indicate that a formerly enqueued task is complete. Used by queue consumers. For each `.get` used to fetch a task, a subsequent call to `.task_done` tells the queue that the processing on the task is complete. If a `.join` is blocking, it resumes when all items have been processed; that is, when every `.put` is matche...
def task_done(self):
if (self._unfinished_tasks <= 0): raise ValueError('task_done() called too many times') self._unfinished_tasks -= 1 if (self._unfinished_tasks == 0): self._finished.set()
'Block until all items in the queue are processed. Returns a Future, which raises `tornado.gen.TimeoutError` after a timeout.'
def join(self, timeout=None):
return self._finished.wait(timeout)
'Redirects to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI with additional parameters including ``openid.mode``. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don\'t need all ...
@return_future def authenticate_redirect(self, callback_uri=None, ax_attrs=['name', 'email', 'language', 'username'], callback=None):
callback_uri = (callback_uri or self.request.uri) args = self._openid_args(callback_uri, ax_attrs=ax_attrs) self.redirect(((self._OPENID_ENDPOINT + '?') + urllib_parse.urlencode(args))) callback()
'Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the `authenticate_redirect()` method (which is often the same as the one that calls it; in that case you would call `get_authenticated_user` if the ``openid.mode`` parameter is present and `au...
@_auth_return_future def get_authenticated_user(self, callback, http_client=None):
args = dict(((k, v[(-1)]) for (k, v) in self.request.arguments.items())) args['openid.mode'] = u'check_authentication' url = self._OPENID_ENDPOINT if (http_client is None): http_client = self.get_auth_http_client() http_client.fetch(url, functools.partial(self._on_authentication_verified, ca...
'Returns the `.AsyncHTTPClient` instance to be used for auth requests. May be overridden by subclasses to use an HTTP client other than the default.'
def get_auth_http_client(self):
return httpclient.AsyncHTTPClient()
'Redirects the user to obtain OAuth authorization for this service. The ``callback_uri`` may be omitted if you have previously registered a callback URI with the third-party service. For some services (including Friendfeed), you must use a previously-registered callback URI and cannot specify a callback via this metho...
@return_future def authorize_redirect(self, callback_uri=None, extra_params=None, http_client=None, callback=None):
if (callback_uri and getattr(self, '_OAUTH_NO_CALLBACKS', False)): raise Exception('This service does not support oauth_callback') if (http_client is None): http_client = self.get_auth_http_client() if (getattr(self, '_OAUTH_VERSION', '1.0a') == '1.0a'): http_client.fe...
'Gets the OAuth authorized user and access token. This method should be called from the handler for your OAuth callback URL to complete the registration process. We run the callback with the authenticated user dictionary. This dictionary will contain an ``access_key`` which can be used to make authorized requests to t...
@_auth_return_future def get_authenticated_user(self, callback, http_client=None):
future = callback request_key = escape.utf8(self.get_argument('oauth_token')) oauth_verifier = self.get_argument('oauth_verifier', None) request_cookie = self.get_cookie('_oauth_request_token') if (not request_cookie): future.set_exception(AuthError('Missing OAuth request token c...
'Subclasses must override this to return their OAuth consumer keys. The return value should be a `dict` with keys ``key`` and ``secret``.'
def _oauth_consumer_token(self):
raise NotImplementedError()
'Subclasses must override this to get basic information about the user. Should return a `.Future` whose result is a dictionary containing information about the user, which may have been retrieved by using ``access_token`` to make a request to the service. The access token will be added to the returned dictionary to mak...
@return_future def _oauth_get_user_future(self, access_token, callback):
self._oauth_get_user(access_token, callback)
'Returns the OAuth parameters as a dict for the given request. parameters should include all POST arguments and query string arguments that will be sent with the request.'
def _oauth_request_parameters(self, url, access_token, parameters={}, method='GET'):
consumer_token = self._oauth_consumer_token() base_args = dict(oauth_consumer_key=escape.to_basestring(consumer_token['key']), oauth_token=escape.to_basestring(access_token['key']), oauth_signature_method='HMAC-SHA1', oauth_timestamp=str(int(time.time())), oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid....
'Returns the `.AsyncHTTPClient` instance to be used for auth requests. May be overridden by subclasses to use an HTTP client other than the default.'
def get_auth_http_client(self):
return httpclient.AsyncHTTPClient()
'Redirects the user to obtain OAuth authorization for this service. Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call ``get_authenticated_user`` in the handler for your redirect URL to compl...
@return_future def authorize_redirect(self, redirect_uri=None, client_id=None, client_secret=None, extra_params=None, callback=None, scope=None, response_type='code'):
args = {'redirect_uri': redirect_uri, 'client_id': client_id, 'response_type': response_type} if extra_params: args.update(extra_params) if scope: args['scope'] = ' '.join(scope) self.redirect(url_concat(self._OAUTH_AUTHORIZE_URL, args)) callback()
'Fetches the given URL auth an OAuth2 access token. If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. Example usage: ..testcode:: class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated @tornado.gen...
@_auth_return_future def oauth2_request(self, url, callback, access_token=None, post_args=None, **args):
all_args = {} if access_token: all_args['access_token'] = access_token all_args.update(args) if all_args: url += ('?' + urllib_parse.urlencode(all_args)) callback = functools.partial(self._on_oauth2_request, callback) http = self.get_auth_http_client() if (post_args is no...
'Returns the `.AsyncHTTPClient` instance to be used for auth requests. May be overridden by subclasses to use an HTTP client other than the default. .. versionadded:: 4.3'
def get_auth_http_client(self):
return httpclient.AsyncHTTPClient()
'Just like `~OAuthMixin.authorize_redirect`, but auto-redirects if authorized. This is generally the right interface to use if you are using Twitter for single-sign on. .. versionchanged:: 3.1 Now returns a `.Future` and takes an optional callback, for compatibility with `.gen.coroutine`.'
@return_future def authenticate_redirect(self, callback_uri=None, callback=None):
http = self.get_auth_http_client() http.fetch(self._oauth_request_token_url(callback_uri=callback_uri), functools.partial(self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None, callback))
'Fetches the given API path, e.g., ``statuses/user_timeline/btaylor`` The path should not include the format or API version number. (we automatically use JSON format and API version 1). If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. All the Twitt...
@_auth_return_future def twitter_request(self, path, callback=None, access_token=None, post_args=None, **args):
if (path.startswith('http:') or path.startswith('https:')): url = path else: url = ((self._TWITTER_BASE_URL + path) + '.json') if access_token: all_args = {} all_args.update(args) all_args.update((post_args or {})) method = ('POST' if (post_args is not None) e...
'Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this package, this method does not...
@_auth_return_future def get_authenticated_user(self, redirect_uri, code, callback):
http = self.get_auth_http_client() body = urllib_parse.urlencode({'redirect_uri': redirect_uri, 'code': code, 'client_id': self.settings[self._OAUTH_SETTINGS_KEY]['key'], 'client_secret': self.settings[self._OAUTH_SETTINGS_KEY]['secret'], 'grant_type': 'authorization_code'}) http.fetch(self._OAUTH_ACCESS_TO...
'Callback function for the exchange to the access token.'
def _on_access_token(self, future, response):
if response.error: future.set_exception(AuthError(('Google auth error: %s' % str(response)))) return args = escape.json_decode(response.body) future.set_result(args)
'Handles the login for the Facebook user, returning a user object. Example usage: .. testcode:: class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.gen.coroutine def get(self): if self.get_argument("code", False): user = yield self.get_authenticated_user( redirect_uri=...
@_auth_return_future def get_authenticated_user(self, redirect_uri, client_id, client_secret, code, callback, extra_fields=None):
http = self.get_auth_http_client() args = {'redirect_uri': redirect_uri, 'code': code, 'client_id': client_id, 'client_secret': client_secret} fields = set(['id', 'name', 'first_name', 'last_name', 'locale', 'picture', 'link']) if extra_fields: fields.update(extra_fields) http.fetch(self._oa...
'Fetches the given relative API path, e.g., "/btaylor/picture" If the request is a POST, ``post_args`` should be provided. Query string arguments should be given as keyword arguments. An introduction to the Facebook Graph API can be found at http://developers.facebook.com/docs/api Many methods require an OAuth access t...
@_auth_return_future def facebook_request(self, path, callback, access_token=None, post_args=None, **args):
url = (self._FACEBOOK_BASE_URL + path) oauth_future = self.oauth2_request(url, access_token=access_token, post_args=post_args, **args) chain_future(oauth_future, callback)
'Returns a global `IOLoop` instance. Most applications have a single, global `IOLoop` running on the main thread. Use this method to get this instance from another thread. In most other cases, it is better to use `current()` to get the current thread\'s `IOLoop`.'
@staticmethod def instance():
if (not hasattr(IOLoop, '_instance')): with IOLoop._instance_lock: if (not hasattr(IOLoop, '_instance')): IOLoop._instance = IOLoop() return IOLoop._instance
'Returns true if the singleton instance has been created.'
@staticmethod def initialized():
return hasattr(IOLoop, '_instance')
'Installs this `IOLoop` object as the singleton instance. This is normally not necessary as `instance()` will create an `IOLoop` on demand, but you may want to call `install` to use a custom subclass of `IOLoop`. When using an `IOLoop` subclass, `install` must be called prior to creating any objects that implicitly cre...
def install(self):
assert (not IOLoop.initialized()) IOLoop._instance = self
'Clear the global `IOLoop` instance. .. versionadded:: 4.0'
@staticmethod def clear_instance():
if hasattr(IOLoop, '_instance'): del IOLoop._instance
'Returns the current thread\'s `IOLoop`. If an `IOLoop` is currently running or has been marked as current by `make_current`, returns that instance. If there is no current `IOLoop`, returns `IOLoop.instance()` (i.e. the main thread\'s `IOLoop`, creating one if necessary) if ``instance`` is true. In general you should ...
@staticmethod def current(instance=True):
current = getattr(IOLoop._current, 'instance', None) if ((current is None) and instance): return IOLoop.instance() return current
'Makes this the `IOLoop` for the current thread. An `IOLoop` automatically becomes current for its thread when it is started, but it is sometimes useful to call `make_current` explicitly before starting the `IOLoop`, so that code run at startup time can find the right instance. .. versionchanged:: 4.1 An `IOLoop` creat...
def make_current(self):
IOLoop._current.instance = self
'Closes the `IOLoop`, freeing any resources used. If ``all_fds`` is true, all file descriptors registered on the IOLoop will be closed (not just the ones created by the `IOLoop` itself). Many applications will only use a single `IOLoop` that runs for the entire lifetime of the process. In that case closing the `IOLoop...
def close(self, all_fds=False):
raise NotImplementedError()