desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Clears the per-request state.
This is run in between requests to allow the previous handler
to be garbage collected (and prevent spurious close callbacks),
and when the connection is closed (to break up cycles and
facilitate garbage collection in cpython).'
| def _clear_request_state(self):
| self._request = None
self._request_finished = False
self._write_callback = None
self._close_callback = None
|
'Sets a callback that will be run when the connection is closed.
Use this instead of accessing
`HTTPConnection.stream.set_close_callback
<.BaseIOStream.set_close_callback>` directly (which was the
recommended approach prior to Tornado 3.0).'
| def set_close_callback(self, callback):
| self._close_callback = stack_context.wrap(callback)
|
'Writes a chunk of output to the stream.'
| def write(self, chunk, callback=None):
| if (not self.stream.closed()):
self._write_callback = stack_context.wrap(callback)
self.stream.write(chunk, self._on_write_complete)
|
'Finishes the request.'
| def finish(self):
| self._request_finished = True
self.stream.set_nodelay(True)
if (not self.stream.writing()):
self._finish_request()
|
'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 = {}
return self._cookies
|
'Writes the given chunk to the response stream.'
| def write(self, chunk, callback=None):
| assert isinstance(chunk, bytes_type)
self.connection.write(chunk, callback=callback)
|
'Finishes this HTTP request on the open connection.'
| 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 must have been constructed
with cert_reqs set in ssl_options, e.g.::
server = HTTPServer(app,
ssl_options=dict(
certfile="foo.crt",
keyfile="foo.key",
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="cacert.crt"))
By default, the return va... | def get_ssl_certificate(self, binary_form=False):
| try:
return self.connection.stream.socket.getpeercert(binary_form=binary_form)
except ssl.SSLError:
return None
|
'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.'
| def decompress(self, value):
| return self.decompressobj.decompress(value)
|
'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, (unicode_type, bytes_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
|
'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)
|
'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_type), '__name__': self.n... |
'``autoescape`` must be either None or a string naming a function
in the template namespace, such as "xhtml_escape".'
| def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None):
| self.autoescape = autoescape
self.namespace = (namespace or {})
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 ``SIGCHILD`` 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)
|
'Initializes the ``SIGCHILD`` 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).'
| @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 ``SIGCHILD`` handler.'
| @classmethod
def uninitialize(cls):
| if (not cls._initialized):
return
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False
|
'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.'
| def write_message(self, message, binary=False):
| if isinstance(message, dict):
message = tornado.escape.json_encode(message)
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
|
'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):
| pass
|
'Handle incoming messages on the WebSocket
This method must be overridden.'
| def on_message(self, message):
| raise NotImplementedError
|
'Send ping frame to the remote end.'
| def ping(self, data):
| 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 WebSocket is closed.'
| def on_close(self):
| pass
|
'Closes this Web Socket.
Once the close handshake is successful the socket will be closed.'
| def close(self):
| self.ws_connection.close()
self.ws_connection = None
|
'Override to enable support for the older "draft76" protocol.
The draft76 version of the websocket protocol is disabled by
default due to security concerns, but it can be enabled by
overriding this method to return True.
Connections using the draft76 protocol do not support the
``binary=True`` flag to `write_message`.
... | def allow_draft76(self):
| return False
|
'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)
|
'Return the url scheme used for this request, either "ws" or "wss".
This is normally decided by HTTPServer, but applications
may wish to override this if they are using an SSL proxy
that does not provide the X-Scheme header as understood
by HTTPServer.
Note that this is only used by the draft76 protocol.'
| def get_websocket_scheme(self):
| return ('wss' if (self.request.protocol == 'https') else 'ws')
|
'Obsolete - catches exceptions from the wrapped function.
This function is normally unncecessary thanks to
`tornado.stack_context`.'
| def async_callback(self, callback, *args, **kwargs):
| return self.ws_connection.async_callback(callback, *args, **kwargs)
|
'Wrap callbacks with this if they are used on asynchronous requests.
Catches exceptions properly and closes this WebSocket if an exception
is uncaught.'
| def async_callback(self, callback, *args, **kwargs):
| if (args or kwargs):
callback = functools.partial(callback, *args, **kwargs)
def wrapper(*args, **kwargs):
try:
return callback(*args, **kwargs)
except Exception:
app_log.error('Uncaught exception in %s', self.request.path, exc_info=True)
self... |
'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()
|
'Generates the challenge response that\'s needed in the handshake
The challenge parameter should be the raw bytes as sent from the
client.'
| def challenge_response(self, challenge):
| key_1 = self.request.headers.get('Sec-Websocket-Key1')
key_2 = self.request.headers.get('Sec-Websocket-Key2')
try:
part_1 = self._calculate_part(key_1)
part_2 = self._calculate_part(key_2)
except ValueError:
raise ValueError('Invalid Keys/Challenge')
return self._generate_... |
'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 = ('Origin', 'Host', 'Sec-Websocket-Key1', 'Sec-Websocket-Key2')
if (not all(map((lambda f: self.request.headers.get(f)), fields))):
raise ValueError('Missing/Invalid WebSocket headers')
|
'Processes the key headers and calculates their key value.
Raises ValueError when feed invalid key.'
| def _calculate_part(self, key):
| number = int(''.join((c for c in key if c.isdigit())))
spaces = len([c2 for c2 in key if c2.isspace()])
try:
key_number = (number // spaces)
except (ValueError, ZeroDivisionError):
raise ValueError
return struct.pack('>I', key_number)
|
'Sends the given message to the client of this Web Socket.'
| def write_message(self, message, binary=False):
| if binary:
raise ValueError('Binary messages not supported by this version of websockets')
if isinstance(message, unicode_type):
message = message.encode('utf-8')
assert isinstance(message, bytes_type)
self.stream.write((('\x00' + message) + '\xff'))
|
'Send ping frame.'
| def write_ping(self, data):
| raise ValueError('Ping messages not supported by this version of websockets')
|
'Closes the WebSocket connection.'
| def close(self):
| if (not self.server_terminated):
if (not self.stream.closed()):
self.stream.write('\xff\x00')
self.server_terminated = True
if self.client_terminated:
if (self._waiting is not None):
self.stream.io_loop.remove_timeout(self._waiting)
self._waiting = None
... |
'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()))
|
'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_type)
try:
self._write_frame(True, opcode, message)
except StreamClosedError:
self._abort()
|
'Send ping frame.'
| def write_ping(self, data):
| assert isinstance(data, bytes_type)
self._write_frame(True, 9, data)
|
'Closes the WebSocket connection.'
| def close(self):
| if (not self.server_terminated):
if (not self.stream.closed()):
self._write_frame(True, 8, '')
self.server_terminated = True
if self.client_terminated:
if (self._waiting is not None):
self.stream.io_loop.remove_timeout(self._waiting)
self._waiting = No... |
'Sends a message to the WebSocket server.'
| def write_message(self, message, binary=False):
| self.protocol.write_message(message, binary)
|
'Reads a message from the WebSocket server.
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
|
'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, self.async_callback(self._on_authentication_verified... |
'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 sevices (including Friendfeed), you must use a
previously-registered callback URI and cannot specify a
callback via this method... | @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):
| args = {'redirect_uri': redirect_uri, 'client_id': client_id}
if extra_params:
args.update(extra_params)
self.redirect(url_concat(self._OAUTH_AUTHORIZE_URL, args))
callback()
|
'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), self.async_callback(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... |
'Fetches the given relative API path, e.g., "/bret/friends"
If the request is a POST, ``post_args`` should be provided. Query
string arguments should be given as keyword arguments.
All the FriendFeed methods are documented at
http://friendfeed.com/api/documentation.
Many methods require an OAuth access token which you ... | @_auth_return_future
def friendfeed_request(self, path, callback, access_token=None, post_args=None, **args):
| url = ('http://friendfeed-api.com/v2' + path)
if access_token:
all_args = {}
all_args.update(args)
all_args.update((post_args or {}))
method = ('POST' if (post_args is not None) else 'GET')
oauth = self._oauth_request_parameters(url, access_token, all_args, method=method)... |
'Authenticates and authorizes for the given Google resource.
Some of the available resources which can be used in the ``oauth_scope``
argument are:
* Gmail Contacts - http://www.google.com/m8/feeds/
* Calendar - http://www.google.com/calendar/feeds/
* Finance - http://finance.google.com/finance/feeds/
You can authorize... | @return_future
def authorize_redirect(self, oauth_scope, 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, oauth_scope=oauth_scope)
self.redirect(((self._OPENID_ENDPOINT + '?') + urllib_parse.urlencode(args)))
callback()
|
'Fetches the authenticated user data upon redirect.'
| @_auth_return_future
def get_authenticated_user(self, callback):
| oauth_ns = ''
for (name, values) in self.request.arguments.items():
if (name.startswith('openid.ns.') and (values[(-1)] == 'http://specs.openid.net/extensions/oauth/1.0')):
oauth_ns = name[10:]
break
token = self.get_argument((('openid.' + oauth_ns) + '.request_token'), '')
... |
'Authenticates/installs this app for the current user.
.. versionchanged:: 3.1
Returns a `.Future` and takes an optional callback. These are
not strictly necessary as this method is synchronous,
but they are supplied for consistency with
`OAuthMixin.authorize_redirect`.'
| @return_future
def authenticate_redirect(self, callback_uri=None, cancel_uri=None, extended_permissions=None, callback=None):
| self.require_setting('facebook_api_key', 'Facebook Connect')
callback_uri = (callback_uri or self.request.uri)
args = {'api_key': self.settings['facebook_api_key'], 'v': '1.0', 'fbconnect': 'true', 'display': 'page', 'next': urlparse.urljoin(self.request.full_url(), callback_uri), 'return_session': 'true... |
'Redirects to an authorization request for the given FB resource.
The available resource names are listed at
http://wiki.developers.facebook.com/index.php/Extended_permission.
The most common resource types include:
* publish_stream
* read_stream
* email
* sms
extended_permissions can be a single permission name or a l... | def authorize_redirect(self, extended_permissions, callback_uri=None, cancel_uri=None, callback=None):
| return self.authenticate_redirect(callback_uri, cancel_uri, extended_permissions, callback=callback)
|
'Fetches the authenticated Facebook user.
The authenticated user includes the special Facebook attributes
\'session_key\' and \'facebook_uid\' in addition to the standard
user attributes like \'name\'.'
| def get_authenticated_user(self, callback):
| self.require_setting('facebook_api_key', 'Facebook Connect')
session = escape.json_decode(self.get_argument('session'))
self.facebook_request(method='facebook.users.getInfo', callback=self.async_callback(self._on_get_user_info, callback, session), session_key=session['session_key'], uids=session['uid'], ... |
'Makes a Facebook API REST request.
We automatically include the Facebook API key and signature, but
it is the callers responsibility to include \'session_key\' and any
other required arguments to the method.
The available Facebook methods are documented here:
http://wiki.developers.facebook.com/index.php/API
Here is a... | def facebook_request(self, method, callback, **args):
| self.require_setting('facebook_api_key', 'Facebook Connect')
self.require_setting('facebook_secret', 'Facebook Connect')
if (not method.startswith('facebook.')):
method = ('facebook.' + method)
args['api_key'] = self.settings['facebook_api_key']
args['v'] = '1.0'
args['method'] = m... |
'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()
|
'Handles the login for the Facebook user, returning a user object.
Example usage::
class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
@tornado.web.asynchronous
@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)
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 = self.async_callback(self._on_facebook_request, callback)
http = self... |
'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()
|
'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. To get the current thread\'s `IOLoop`, use `current()`.'
| @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`.'
| def install(self):
| assert (not IOLoop.initialized())
IOLoop._instance = self
|
'Returns the current thread\'s `IOLoop`.
If an `IOLoop` is currently running or has been marked as current
by `make_current`, returns that instance. Otherwise returns
`IOLoop.instance()`, i.e. the main thread\'s `IOLoop`.
A common pattern for classes that depend on ``IOLoops`` is to use
a default argument to enable pr... | @staticmethod
def current():
| current = getattr(IOLoop._current, 'instance', None)
if (current is None):
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` explictly before starting the `IOLoop`,
so that code run at startup time can find the right
instance.'
| 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()
|
'Registers the given handler to receive the given events for fd.
The ``events`` argument is a bitwise or of the constants
``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.
When an event occurs, ``handler(fd, events)`` will be run.'
| def add_handler(self, fd, handler, events):
| raise NotImplementedError()
|
'Changes the events we listen for fd.'
| def update_handler(self, fd, events):
| raise NotImplementedError()
|
'Stop listening for events on fd.'
| def remove_handler(self, fd):
| raise NotImplementedError()
|
'Sends a signal if the `IOLoop` is blocked for more than
``s`` seconds.
Pass ``seconds=None`` to disable. Requires Python 2.6 on a unixy
platform.
The action parameter is a Python signal handler. Read the
documentation for the `signal` module for more information.
If ``action`` is None, the process will be killed if ... | def set_blocking_signal_threshold(self, seconds, action):
| raise NotImplementedError()
|
'Logs a stack trace if the `IOLoop` is blocked for more than
``s`` seconds.
Equivalent to ``set_blocking_signal_threshold(seconds,
self.log_stack)``'
| def set_blocking_log_threshold(self, seconds):
| self.set_blocking_signal_threshold(seconds, self.log_stack)
|
'Signal handler to log the stack trace of the current thread.
For use with `set_blocking_signal_threshold`.'
| def log_stack(self, signal, frame):
| gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ''.join(traceback.format_stack(frame)))
|
'Starts the I/O loop.
The loop will run until one of the callbacks calls `stop()`, which
will make the loop stop after the current event iteration completes.'
| def start(self):
| raise NotImplementedError()
|
'Stop the I/O loop.
If the event loop is not currently running, the next call to `start()`
will return immediately.
To use asynchronous methods from otherwise-synchronous code (such as
unit tests), you can start and stop the event loop like this::
ioloop = IOLoop()
async_method(ioloop=ioloop, callback=ioloop.stop)
iolo... | def stop(self):
| raise NotImplementedError()
|
'Starts the `IOLoop`, runs the given function, and stops the loop.
If the function returns a `.Future`, the `IOLoop` will run
until the future is resolved. If it raises an exception, the
`IOLoop` will stop and the exception will be re-raised to the
caller.
The keyword-only argument ``timeout`` may be used to set
a max... | def run_sync(self, func, timeout=None):
| future_cell = [None]
def run():
try:
result = func()
except Exception:
future_cell[0] = TracebackFuture()
future_cell[0].set_exc_info(sys.exc_info())
else:
if isinstance(result, Future):
future_cell[0] = result
e... |
'Returns the current time according to the `IOLoop`\'s clock.
The return value is a floating-point number relative to an
unspecified time in the past.
By default, the `IOLoop`\'s time function is `time.time`. However,
it may be configured to use e.g. `time.monotonic` instead.
Calls to `add_timeout` that pass a number ... | def time(self):
| return time.time()
|
'Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current t... | def add_timeout(self, deadline, callback):
| raise NotImplementedError()
|
'Cancels a pending timeout.
The argument is a handle as returned by `add_timeout`. It is
safe to call `remove_timeout` even if the callback has already
been run.'
| def remove_timeout(self, timeout):
| raise NotImplementedError()
|
'Calls the given callback on the next I/O loop iteration.
It is safe to call this method from any thread at any time,
except from a signal handler. Note that this is the **only**
method in `IOLoop` that makes this thread-safety guarantee; all
other interaction with the `IOLoop` must be done from that
`IOLoop`\'s threa... | def add_callback(self, callback, *args, **kwargs):
| raise NotImplementedError()
|
'Calls the given callback on the next I/O loop iteration.
Safe for use from a Python signal handler; should not be used
otherwise.
Callbacks added with this method will be run without any
`.stack_context`, to avoid picking up the context of the function
that was interrupted by the signal.'
| def add_callback_from_signal(self, callback, *args, **kwargs):
| raise NotImplementedError()
|
'Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`.'
| def add_future(self, future, callback):
| assert isinstance(future, Future)
callback = stack_context.wrap(callback)
future.add_done_callback((lambda future: self.add_callback(callback, future)))
|
'Runs a callback with error handling.
For use in subclasses.'
| def _run_callback(self, callback):
| try:
callback()
except Exception:
self.handle_callback_exception(callback)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.