Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def set(self) -> None:
if not self._value:
self._value = True
for fut in self._waiters:
if not fut.done():
fut.set_result(None) | [
"Set the internal flag to ``True``. All waiters are awakened.\n\n Calling `.wait` once the flag is set will not block.\n "
] |
Please provide a description of the function:def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
fut = Future() # type: Future[None]
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_call... | [
"Block until the internal flag is true.\n\n Returns an awaitable, which raises `tornado.util.TimeoutError` after a\n timeout.\n "
] |
Please provide a description of the function:def release(self) -> None:
self._value += 1
while self._waiters:
waiter = self._waiters.popleft()
if not waiter.done():
self._value -= 1
# If the waiter is a coroutine paused at
... | [
"Increment the counter and wake one waiter."
] |
Please provide a description of the function:def acquire(
self, timeout: Union[float, datetime.timedelta] = None
) -> Awaitable[_ReleasingContextManager]:
waiter = Future() # type: Future[_ReleasingContextManager]
if self._value > 0:
self._value -= 1
waiter.... | [
"Decrement the counter. Returns an awaitable.\n\n Block if the counter is zero and wait for a `.release`. The awaitable\n raises `.TimeoutError` after the deadline.\n "
] |
Please provide a description of the function:def release(self) -> None:
if self._value >= self._initial_value:
raise ValueError("Semaphore released too many times")
super(BoundedSemaphore, self).release() | [
"Increment the counter and wake one waiter."
] |
Please provide a description of the function:def acquire(
self, timeout: Union[float, datetime.timedelta] = None
) -> Awaitable[_ReleasingContextManager]:
return self._block.acquire(timeout) | [
"Attempt to lock. Returns an awaitable.\n\n Returns an awaitable, which raises `tornado.util.TimeoutError` after a\n timeout.\n "
] |
Please provide a description of the function:def read_response(self, delegate: httputil.HTTPMessageDelegate) -> Awaitable[bool]:
if self.params.decompress:
delegate = _GzipMessageDelegate(delegate, self.params.chunk_size)
return self._read_message(delegate) | [
"Read a single HTTP response.\n\n Typical client-mode usage is to write a request using `write_headers`,\n `write`, and `finish`, and then call ``read_response``.\n\n :arg delegate: a `.HTTPMessageDelegate`\n\n Returns a `.Future` that resolves to a bool after the full response has\n ... |
Please provide a description of the function:def _clear_callbacks(self) -> None:
self._write_callback = None
self._write_future = None # type: Optional[Future[None]]
self._close_callback = None # type: Optional[Callable[[], None]]
if self.stream is not None:
self.s... | [
"Clears the callback attributes.\n\n This allows the request handler to be garbage collected more\n quickly in CPython by breaking up reference cycles.\n "
] |
Please provide a description of the function:def detach(self) -> iostream.IOStream:
self._clear_callbacks()
stream = self.stream
self.stream = None # type: ignore
if not self._finish_future.done():
future_set_result_unless_cancelled(self._finish_future, None)
... | [
"Take control of the underlying stream.\n\n Returns the underlying `.IOStream` object and stops all further\n HTTP processing. May only be called during\n `.HTTPMessageDelegate.headers_received`. Intended for implementing\n protocols like websockets that tunnel over an HTTP handshake.\... |
Please provide a description of the function:def write_headers(
self,
start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
headers: httputil.HTTPHeaders,
chunk: bytes = None,
) -> "Future[None]":
lines = []
if self.is_client:
... | [
"Implements `.HTTPConnection.write_headers`."
] |
Please provide a description of the function:def write(self, chunk: bytes) -> "Future[None]":
future = None
if self.stream.closed():
future = self._write_future = Future()
self._write_future.set_exception(iostream.StreamClosedError())
self._write_future.excep... | [
"Implements `.HTTPConnection.write`.\n\n For backwards compatibility it is allowed but deprecated to\n skip `write_headers` and instead call `write()` with a\n pre-encoded header block.\n "
] |
Please provide a description of the function:def finish(self) -> None:
if (
self._expected_content_remaining is not None
and self._expected_content_remaining != 0
and not self.stream.closed()
):
self.stream.close()
raise httputil.HTTPO... | [
"Implements `.HTTPConnection.finish`."
] |
Please provide a description of the function:async def close(self) -> None:
self.stream.close()
# Block until the serving loop is done, but ignore any exceptions
# (start_serving is already responsible for logging them).
assert self._serving_future is not None
try:
... | [
"Closes the connection.\n\n Returns a `.Future` that resolves after the serving loop has exited.\n "
] |
Please provide a description of the function:def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None:
assert isinstance(delegate, httputil.HTTPServerConnectionDelegate)
fut = gen.convert_yielded(self._server_request_loop(delegate))
self._serving_future = fut
... | [
"Starts serving requests on this connection.\n\n :arg delegate: a `.HTTPServerConnectionDelegate`\n "
] |
Please provide a description of the function:def websocket_connect(
url: Union[str, httpclient.HTTPRequest],
callback: Callable[["Future[WebSocketClientConnection]"], None] = None,
connect_timeout: float = None,
on_message_callback: Callable[[Union[None, str, bytes]], None] = None,
compression_optio... | [
"Client-side websocket support.\n\n Takes a url and returns a Future whose result is a\n `WebSocketClientConnection`.\n\n ``compression_options`` is interpreted in the same way as the\n return value of `.WebSocketHandler.get_compression_options`.\n\n The connection supports two styles of operation. I... |
Please provide a description of the function:def write_message(
self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False
) -> "Future[None]":
if self.ws_connection is None or self.ws_connection.is_closing():
raise WebSocketClosedError()
if isinstance(messag... | [
"Sends the given message to the client of this Web Socket.\n\n The message may be either a string or a dict (which will be\n encoded as json). If the ``binary`` argument is false, the\n message will be sent as utf8; in binary mode any byte string\n is allowed.\n\n If the connecti... |
Please provide a description of the function:def ping(self, data: Union[str, bytes] = b"") -> None:
data = utf8(data)
if self.ws_connection is None or self.ws_connection.is_closing():
raise WebSocketClosedError()
self.ws_connection.write_ping(data) | [
"Send ping frame to the remote end.\n\n The data argument allows a small amount of data (up to 125\n bytes) to be sent as a part of the ping message. Note that not\n all websocket implementations expose this data to\n applications.\n\n Consider using the ``websocket_ping_interval`... |
Please provide a description of the function:def close(self, code: int = None, reason: str = None) -> None:
if self.ws_connection:
self.ws_connection.close(code, reason)
self.ws_connection = None | [
"Closes this Web Socket.\n\n Once the close handshake is successful the socket will be closed.\n\n ``code`` may be a numeric status code, taken from the values\n defined in `RFC 6455 section 7.4.1\n <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.\n ``reason`` may be a textu... |
Please provide a description of the function:def check_origin(self, origin: str) -> bool:
parsed_origin = urlparse(origin)
origin = parsed_origin.netloc
origin = origin.lower()
host = self.request.headers.get("Host")
# Check to see that origin matches host directly, in... | [
"Override to enable support for allowing alternate origins.\n\n The ``origin`` argument is the value of the ``Origin`` HTTP\n header, the url responsible for initiating this request. This\n method is not called for clients that do not send this header;\n such requests are always allowed... |
Please provide a description of the function:def set_nodelay(self, value: bool) -> None:
assert self.ws_connection is not None
self.ws_connection.set_nodelay(value) | [
"Set the no-delay flag for this stream.\n\n By default, small messages may be delayed and/or combined to minimize\n the number of packets sent. This can sometimes cause 200-500ms delays\n due to the interaction between Nagle's algorithm and TCP delayed\n ACKs. To reduce this delay (at ... |
Please provide a description of the function:def _run_callback(
self, callback: Callable, *args: Any, **kwargs: Any
) -> "Optional[Future[Any]]":
try:
result = callback(*args, **kwargs)
except Exception:
self.handler.log_exception(*sys.exc_info())
... | [
"Runs the given callback with exception handling.\n\n If the callback is a coroutine, returns its Future. On error, aborts the\n websocket connection and returns None.\n "
] |
Please provide a description of the function:def _abort(self) -> None:
self.client_terminated = True
self.server_terminated = True
if self.stream is not None:
self.stream.close() # forcibly tear down the connection
self.close() | [
"Instantly aborts the WebSocket connection by closing the socket"
] |
Please provide a description of the function:def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:
fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version")
if not all(map(lambda f: handler.request.headers.get(f), fields)):
raise ValueError("Missing/Invalid W... | [
"Verifies all invariant- and required headers\n\n If a header is missing or have an incorrect value ValueError will be\n raised\n "
] |
Please provide a description of the function:def compute_accept_value(key: Union[str, bytes]) -> str:
sha1 = hashlib.sha1()
sha1.update(utf8(key))
sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value
return native_str(base64.b64encode(sha1.digest())) | [
"Computes the value for the Sec-WebSocket-Accept header,\n given the value for Sec-WebSocket-Key.\n "
] |
Please provide a description of the function:def _process_server_headers(
self, key: Union[str, bytes], headers: httputil.HTTPHeaders
) -> None:
assert headers["Upgrade"].lower() == "websocket"
assert headers["Connection"].lower() == "upgrade"
accept = self.compute_accept_va... | [
"Process the headers sent by the server to this client connection.\n\n 'key' is the websocket handshake challenge/response key.\n "
] |
Please provide a description of the function:def _get_compressor_options(
self,
side: str,
agreed_parameters: Dict[str, Any],
compression_options: Dict[str, Any] = None,
) -> Dict[str, Any]:
options = dict(
persistent=(side + "_no_context_takeover") not i... | [
"Converts a websocket agreed_parameters set to keyword arguments\n for our compressor objects.\n "
] |
Please provide a description of the function:def write_message(
self, message: Union[str, bytes], binary: bool = False
) -> "Future[None]":
if binary:
opcode = 0x2
else:
opcode = 0x1
message = tornado.escape.utf8(message)
assert isinstance(mes... | [
"Sends the given message to the client of this Web Socket."
] |
Please provide a description of the function:def write_ping(self, data: bytes) -> None:
assert isinstance(data, bytes)
self._write_frame(True, 0x9, data) | [
"Send ping frame."
] |
Please provide a description of the function:def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]":
if self.client_terminated:
return None
if self._frame_compressed:
assert self._decompressor is not None
try:
data = ... | [
"Execute on_message, returning its Future if it is a coroutine."
] |
Please provide a description of the function:def close(self, code: int = None, reason: str = None) -> None:
if not self.server_terminated:
if not self.stream.closed():
if code is None and reason is not None:
code = 1000 # "normal closure" status code
... | [
"Closes the WebSocket connection."
] |
Please provide a description of the function:def is_closing(self) -> bool:
return self.stream.closed() or self.client_terminated or self.server_terminated | [
"Return ``True`` if this connection is closing.\n\n The connection is considered closing if either side has\n initiated its closing handshake or if the stream has been\n shut down uncleanly.\n "
] |
Please provide a description of the function:def start_pinging(self) -> None:
assert self.ping_interval is not None
if self.ping_interval > 0:
self.last_ping = self.last_pong = IOLoop.current().time()
self.ping_callback = PeriodicCallback(
self.periodic_p... | [
"Start sending periodic pings to keep the connection alive"
] |
Please provide a description of the function:def periodic_ping(self) -> None:
if self.is_closing() and self.ping_callback is not None:
self.ping_callback.stop()
return
# Check for timeout on pong. Make sure that we really have
# sent a recent ping in case the ma... | [
"Send a ping to keep the websocket alive\n\n Called periodically if the websocket_ping_interval is set and non-zero.\n "
] |
Please provide a description of the function:def close(self, code: int = None, reason: str = None) -> None:
if self.protocol is not None:
self.protocol.close(code, reason)
self.protocol = None | [
"Closes the websocket connection.\n\n ``code`` and ``reason`` are documented under\n `WebSocketHandler.close`.\n\n .. versionadded:: 3.2\n\n .. versionchanged:: 4.0\n\n Added the ``code`` and ``reason`` arguments.\n "
] |
Please provide a description of the function:def write_message(
self, message: Union[str, bytes], binary: bool = False
) -> "Future[None]":
return self.protocol.write_message(message, binary=binary) | [
"Sends a message to the WebSocket server.\n\n If the stream is closed, raises `WebSocketClosedError`.\n Returns a `.Future` which can be used for flow control.\n\n .. versionchanged:: 5.0\n Exception raised on a closed stream changed from `.StreamClosedError`\n to `WebSocket... |
Please provide a description of the function:def read_message(
self, callback: Callable[["Future[Union[None, str, bytes]]"], None] = None
) -> Awaitable[Union[None, str, bytes]]:
awaitable = self.read_queue.get()
if callback is not None:
self.io_loop.add_future(asyncio.... | [
"Reads a message from the WebSocket server.\n\n If on_message_callback was specified at WebSocket\n initialization, this function will never return messages\n\n Returns a future whose result is the message, or None\n if the connection is closed. If a callback argument\n is given ... |
Please provide a description of the function:def ping(self, data: bytes = b"") -> None:
data = utf8(data)
if self.protocol is None:
raise WebSocketClosedError()
self.protocol.write_ping(data) | [
"Send ping frame to the remote end.\n\n The data argument allows a small amount of data (up to 125\n bytes) to be sent as a part of the ping message. Note that not\n all websocket implementations expose this data to\n applications.\n\n Consider using the ``ping_interval`` argument... |
Please provide a description of the function:def define(
name: str,
default: Any = None,
type: type = None,
help: str = None,
metavar: str = None,
multiple: bool = False,
group: str = None,
callback: Callable[[Any], None] = None,
) -> None:
return options.define(
name,
... | [
"Defines an option in the global namespace.\n\n See `OptionParser.define`.\n "
] |
Please provide a description of the function:def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
return options.parse_command_line(args, final=final) | [
"Parses global options from the command line.\n\n See `OptionParser.parse_command_line`.\n "
] |
Please provide a description of the function:def parse_config_file(path: str, final: bool = True) -> None:
return options.parse_config_file(path, final=final) | [
"Parses global options from a config file.\n\n See `OptionParser.parse_config_file`.\n "
] |
Please provide a description of the function:def items(self) -> Iterable[Tuple[str, Any]]:
return [(opt.name, opt.value()) for name, opt in self._options.items()] | [
"An iterable of (name, value) pairs.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def groups(self) -> Set[str]:
return set(opt.group_name for opt in self._options.values()) | [
"The set of option-groups created by ``define``.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def group_dict(self, group: str) -> Dict[str, Any]:
return dict(
(opt.name, opt.value())
for name, opt in self._options.items()
if not group or group == opt.group_name
) | [
"The names and values of options in a group.\n\n Useful for copying options into Application settings::\n\n from tornado.options import define, parse_command_line, options\n\n define('template_path', group='application')\n define('static_path', group='application')\n\n ... |
Please provide a description of the function:def as_dict(self) -> Dict[str, Any]:
return dict((opt.name, opt.value()) for name, opt in self._options.items()) | [
"The names and values of all options.\n\n .. versionadded:: 3.1\n "
] |
Please provide a description of the function:def define(
self,
name: str,
default: Any = None,
type: type = None,
help: str = None,
metavar: str = None,
multiple: bool = False,
group: str = None,
callback: Callable[[Any], None] = None,
) -> Non... | [
"Defines a new command line option.\n\n ``type`` can be any of `str`, `int`, `float`, `bool`,\n `~datetime.datetime`, or `~datetime.timedelta`. If no ``type``\n is given but a ``default`` is, ``type`` is the type of\n ``default``. Otherwise, ``type`` defaults to `str`.\n\n If ``mu... |
Please provide a description of the function:def parse_command_line(
self, args: List[str] = None, final: bool = True
) -> List[str]:
if args is None:
args = sys.argv
remaining = [] # type: List[str]
for i in range(1, len(args)):
# All things after t... | [
"Parses all options given on the command line (defaults to\n `sys.argv`).\n\n Options look like ``--option=value`` and are parsed according\n to their ``type``. For boolean options, ``--option`` is\n equivalent to ``--option=true``\n\n If the option has ``multiple=True``, comma-se... |
Please provide a description of the function:def parse_config_file(self, path: str, final: bool = True) -> None:
config = {"__file__": os.path.abspath(path)}
with open(path, "rb") as f:
exec_in(native_str(f.read()), config, config)
for name in config:
normalized ... | [
"Parses and loads the config file at the given path.\n\n The config file contains Python code that will be executed (so\n it is **not safe** to use untrusted config files). Anything in\n the global namespace that matches a defined option will be\n used to set that option's value.\n\n ... |
Please provide a description of the function:def print_help(self, file: TextIO = None) -> None:
if file is None:
file = sys.stderr
print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
print("\nOptions:\n", file=file)
by_group = {} # type: Dict[str, List[_Option]]
... | [
"Prints all the command line options to stderr (or another file)."
] |
Please provide a description of the function:def row_to_obj(self, row, cur):
obj = tornado.util.ObjectDict()
for val, desc in zip(row, cur.description):
obj[desc.name] = val
return obj | [
"Convert a SQL row to an object supporting dict and attribute access."
] |
Please provide a description of the function:async def execute(self, stmt, *args):
with (await self.application.db.cursor()) as cur:
await cur.execute(stmt, args) | [
"Execute a SQL statement.\n\n Must be called with ``await self.execute(...)``\n "
] |
Please provide a description of the function:async def query(self, stmt, *args):
with (await self.application.db.cursor()) as cur:
await cur.execute(stmt, args)
return [self.row_to_obj(row, cur) for row in await cur.fetchall()] | [
"Query for a list of results.\n\n Typical usage::\n\n results = await self.query(...)\n\n Or::\n\n for row in await self.query(...)\n "
] |
Please provide a description of the function:async def queryone(self, stmt, *args):
results = await self.query(stmt, *args)
if len(results) == 0:
raise NoResultError()
elif len(results) > 1:
raise ValueError("Expected 1 result, got %d" % len(results))
ret... | [
"Query for exactly one result.\n\n Raises NoResultError if there are no results, or ValueError if\n there are more than one.\n "
] |
Please provide a description of the function:def listen(self, port: int, address: str = "") -> None:
sockets = bind_sockets(port, address=address)
self.add_sockets(sockets) | [
"Starts accepting connections on the given port.\n\n This method may be called more than once to listen on multiple ports.\n `listen` takes effect immediately; it is not necessary to call\n `TCPServer.start` afterwards. It is, however, necessary to start\n the `.IOLoop`.\n "
] |
Please provide a description of the function:def add_sockets(self, sockets: Iterable[socket.socket]) -> None:
for sock in sockets:
self._sockets[sock.fileno()] = sock
self._handlers[sock.fileno()] = add_accept_handler(
sock, self._handle_connection
) | [
"Makes this server start accepting connections on the given sockets.\n\n The ``sockets`` parameter is a list of socket objects such as\n those returned by `~tornado.netutil.bind_sockets`.\n `add_sockets` is typically used in combination with that\n method and `tornado.process.fork_proces... |
Please provide a description of the function:def bind(
self,
port: int,
address: str = None,
family: socket.AddressFamily = socket.AF_UNSPEC,
backlog: int = 128,
reuse_port: bool = False,
) -> None:
sockets = bind_sockets(
port, address=ad... | [
"Binds this server to the given port on the given address.\n\n To start the server, call `start`. If you want to run this server\n in a single process, you can call `listen` as a shortcut to the\n sequence of `bind` and `start` calls.\n\n Address may be either an IP address or hostname. ... |
Please provide a description of the function:def start(self, num_processes: Optional[int] = 1, max_restarts: int = None) -> None:
assert not self._started
self._started = True
if num_processes != 1:
process.fork_processes(num_processes, max_restarts)
sockets = self._... | [
"Starts this server in the `.IOLoop`.\n\n By default, we run the server in this process and do not fork any\n additional child process.\n\n If num_processes is ``None`` or <= 0, we detect the number of cores\n available on this machine and fork that number of child\n processes. If... |
Please provide a description of the function:def stop(self) -> None:
if self._stopped:
return
self._stopped = True
for fd, sock in self._sockets.items():
assert sock.fileno() == fd
# Unregister socket from IOLoop
self._handlers.pop(fd)()
... | [
"Stops listening for new connections.\n\n Requests currently in progress may still continue after the\n server is stopped.\n "
] |
Please provide a description of the function:def put(
self, item: _T, timeout: Union[float, datetime.timedelta] = None
) -> "Future[None]":
future = Future() # type: Future[None]
try:
self.put_nowait(item)
except QueueFull:
self._putters.append((item... | [
"Put an item into the queue, perhaps waiting until there is room.\n\n Returns a Future, which raises `tornado.util.TimeoutError` after a\n timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a\n `... |
Please provide a description of the function:def put_nowait(self, item: _T) -> None:
self._consume_expired()
if self._getters:
assert self.empty(), "queue non-empty, why are getters waiting?"
getter = self._getters.popleft()
self.__put_internal(item)
... | [
"Put an item into the queue without blocking.\n\n If no free slot is immediately available, raise `QueueFull`.\n "
] |
Please provide a description of the function:def get(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[_T]:
future = Future() # type: Future[_T]
try:
future.set_result(self.get_nowait())
except QueueEmpty:
self._getters.append(future)
... | [
"Remove and return an item from the queue.\n\n Returns an awaitable which resolves once an item is available, or raises\n `tornado.util.TimeoutError` after a timeout.\n\n ``timeout`` may be a number denoting a time (on the same\n scale as `tornado.ioloop.IOLoop.time`, normally `time.time... |
Please provide a description of the function:def get_nowait(self) -> _T:
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)
futu... | [
"Remove and return an item from the queue without blocking.\n\n Return an item if one is immediately available, else raise\n `QueueEmpty`.\n "
] |
Please provide a description of the function:def task_done(self) -> None:
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() | [
"Indicate that a formerly enqueued task is complete.\n\n Used by queue consumers. For each `.get` used to fetch a task, a\n subsequent call to `.task_done` tells the queue that the processing\n on the task is complete.\n\n If a `.join` is blocking, it resumes when all items have been\n ... |
Please provide a description of the function:def join(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
return self._finished.wait(timeout) | [
"Block until all items in the queue are processed.\n\n Returns an awaitable, which raises `tornado.util.TimeoutError` after a\n timeout.\n "
] |
Please provide a description of the function:def cpu_count() -> int:
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, ValueError):
... | [
"Returns the number of processors on this machine."
] |
Please provide a description of the function:def fork_processes(num_processes: Optional[int], max_restarts: int = None) -> int:
if max_restarts is None:
max_restarts = 100
global _task_id
assert _task_id is None
if num_processes is None or num_processes <= 0:
num_processes = cpu_co... | [
"Starts multiple worker processes.\n\n If ``num_processes`` is None or <= 0, we detect the number of cores\n available on this machine and fork that number of child\n processes. If ``num_processes`` is given and > 0, we fork that\n specific number of sub-processes.\n\n Since we use processes and not ... |
Please provide a description of the function:def set_exit_callback(self, callback: Callable[[int], None]) -> None:
self._exit_callback = callback
Subprocess.initialize()
Subprocess._waiting[self.pid] = self
Subprocess._try_cleanup_process(self.pid) | [
"Runs ``callback`` when this process exits.\n\n The callback takes one argument, the return code of the process.\n\n This method uses a ``SIGCHLD`` handler, which is a global setting\n and may conflict if you have other libraries trying to handle the\n same signal. If you are using more... |
Please provide a description of the function:def wait_for_exit(self, raise_error: bool = True) -> "Future[int]":
future = Future() # type: Future[int]
def callback(ret: int) -> None:
if ret != 0 and raise_error:
# Unfortunately we don't have the original args any m... | [
"Returns a `.Future` which resolves when the process exits.\n\n Usage::\n\n ret = yield proc.wait_for_exit()\n\n This is a coroutine-friendly alternative to `set_exit_callback`\n (and a replacement for the blocking `subprocess.Popen.wait`).\n\n By default, raises `subprocess.C... |
Please provide a description of the function:def initialize(cls) -> None:
if cls._initialized:
return
io_loop = ioloop.IOLoop.current()
cls._old_sigchld = signal.signal(
signal.SIGCHLD,
lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup)... | [
"Initializes the ``SIGCHLD`` handler.\n\n The signal handler is run on an `.IOLoop` to avoid locking issues.\n Note that the `.IOLoop` used for signal handling need not be the\n same one used by individual Subprocess objects (as long as the\n ``IOLoops`` are each running in separate thre... |
Please provide a description of the function:def uninitialize(cls) -> None:
if not cls._initialized:
return
signal.signal(signal.SIGCHLD, cls._old_sigchld)
cls._initialized = False | [
"Removes the ``SIGCHLD`` handler."
] |
Please provide a description of the function:def _handle_socket(self, event: int, fd: int, multi: Any, data: bytes) -> None:
event_map = {
pycurl.POLL_NONE: ioloop.IOLoop.NONE,
pycurl.POLL_IN: ioloop.IOLoop.READ,
pycurl.POLL_OUT: ioloop.IOLoop.WRITE,
pycu... | [
"Called by libcurl when it wants to change the file descriptors\n it cares about.\n "
] |
Please provide a description of the function:def _set_timeout(self, msecs: int) -> None:
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 libcurl to schedule a timeout."
] |
Please provide a description of the function:def _handle_events(self, fd: int, events: int) -> None:
action = 0
if events & ioloop.IOLoop.READ:
action |= pycurl.CSELECT_IN
if events & ioloop.IOLoop.WRITE:
action |= pycurl.CSELECT_OUT
while True:
... | [
"Called by IOLoop when there is activity on one of our\n file descriptors.\n "
] |
Please provide a description of the function:def _handle_timeout(self) -> None:
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]
... | [
"Called by IOLoop when the requested timeout has passed."
] |
Please provide a description of the function:def _handle_force_timeout(self) -> None:
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:
... | [
"Called by IOLoop periodically to ask libcurl to process any\n events it may have forgotten about.\n "
] |
Please provide a description of the function:def _finish_pending_requests(self) -> None:
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.... | [
"Process any requests that were completed by the last\n call to multi.socket_action.\n "
] |
Please provide a description of the function:def start(port, root_directory, bucket_depth):
application = S3Application(root_directory, bucket_depth)
http_server = httpserver.HTTPServer(application)
http_server.listen(port)
ioloop.IOLoop.current().start() | [
"Starts the mock S3 server on the given port at the given path."
] |
Please provide a description of the function:def close(self) -> None:
if not self._closed:
self._async_client.close()
self._io_loop.close()
self._closed = True | [
"Closes the HTTPClient, freeing any resources used."
] |
Please provide a description of the function:def fetch(
self, request: Union["HTTPRequest", str], **kwargs: Any
) -> "HTTPResponse":
response = self._io_loop.run_sync(
functools.partial(self._async_client.fetch, request, **kwargs)
)
return response | [
"Executes a request, returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n If an error occurs during the fetch, we raise ... |
Please provide a description of the function:def close(self) -> None:
if self._closed:
return
self._closed = True
if self._instance_cache is not None:
cached_val = self._instance_cache.pop(self.io_loop, None)
# If there's an object other than self in ... | [
"Destroys this HTTP client, freeing any file descriptors used.\n\n This method is **not needed in normal use** due to the way\n that `AsyncHTTPClient` objects are transparently reused.\n ``close()`` is generally only necessary when either the\n `.IOLoop` is also being closed, or the ``fo... |
Please provide a description of the function:def fetch(
self,
request: Union[str, "HTTPRequest"],
raise_error: bool = True,
**kwargs: Any
) -> Awaitable["HTTPResponse"]:
if self._closed:
raise RuntimeError("fetch() called on closed AsyncHTTPClient")
... | [
"Executes a request, asynchronously returning an `HTTPResponse`.\n\n The request may be either a string URL or an `HTTPRequest` object.\n If it is a string, we construct an `HTTPRequest` using any additional\n kwargs: ``HTTPRequest(request, **kwargs)``\n\n This method returns a `.Future`... |
Please provide a description of the function:def configure(
cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
) -> None:
super(AsyncHTTPClient, cls).configure(impl, **kwargs) | [
"Configures the `AsyncHTTPClient` subclass to use.\n\n ``AsyncHTTPClient()`` actually creates an instance of a subclass.\n This method may be called with either a class object or the\n fully-qualified name of such a class (or ``None`` to use the default,\n ``SimpleAsyncHTTPClient``)\n\n ... |
Please provide a description of the function:def _cleanup(self) -> None:
if self._cleanup_handle:
self._cleanup_handle.cancel()
now = self._loop.time()
timeout = self._keepalive_timeout
if self._conns:
connections = {}
deadline = now - timeo... | [
"Cleanup unused transports."
] |
Please provide a description of the function:def _cleanup_closed(self) -> None:
if self._cleanup_closed_handle:
self._cleanup_closed_handle.cancel()
for transport in self._cleanup_closed_transports:
if transport is not None:
transport.abort()
se... | [
"Double confirmation for transport close.\n Some broken ssl servers may leave socket open without proper close.\n "
] |
Please provide a description of the function:def _available_connections(self, key: 'ConnectionKey') -> int:
if self._limit:
# total calc available connections
available = self._limit - len(self._acquired)
# check limit per host
if (self._limit_per_host ... | [
"\n Return number of available connections taking into account\n the limit, limit_per_host and the connection key.\n\n If it returns less than 1 means that there is no connections\n availables.\n "
] |
Please provide a description of the function:async def connect(self, req: 'ClientRequest',
traces: List['Trace'],
timeout: 'ClientTimeout') -> Connection:
key = req.connection_key
available = self._available_connections(key)
# Wait if there a... | [
"Get from pool or create new connection."
] |
Please provide a description of the function:def _release_waiter(self) -> None:
if not self._waiters:
return
# Having the dict keys ordered this avoids to iterate
# at the same order at each call.
queues = list(self._waiters.keys())
random.shuffle(queues)
... | [
"\n Iterates over all waiters till found one that is not finsihed and\n belongs to a host that has available connections.\n "
] |
Please provide a description of the function:def close(self) -> Awaitable[None]:
for ev in self._throttle_dns_events.values():
ev.cancel()
return super().close() | [
"Close all ongoing DNS calls."
] |
Please provide a description of the function:def clear_dns_cache(self,
host: Optional[str]=None,
port: Optional[int]=None) -> None:
if host is not None and port is not None:
self._cached_hosts.remove((host, port))
elif host is not None... | [
"Remove specified host/port or clear all dns local cache."
] |
Please provide a description of the function:async def _create_connection(self, req: 'ClientRequest',
traces: List['Trace'],
timeout: 'ClientTimeout') -> ResponseHandler:
if req.proxy:
_, proto = await self._create_proxy_conn... | [
"Create connection.\n\n Has same keyword arguments as BaseEventLoop.create_connection.\n "
] |
Please provide a description of the function:def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]:
if req.is_ssl():
if ssl is None: # pragma: no cover
raise RuntimeError('SSL is not supported.')
sslcontext = req.ssl
if isinstance(... | [
"Logic to get the correct SSL context\n\n 0. if req.ssl is false, return None\n\n 1. if ssl_context is specified in req, use it\n 2. if _ssl_context is specified in self, use it\n 3. otherwise:\n 1. if verify_ssl is not specified in req, use self.ssl_context\n (w... |
Please provide a description of the function:def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
assert isinstance(data, bytearray), data
assert len(mask) == 4, mask
if data:
a, b, c, d = (_XOR_TABLE[n] for n in mask)
data[::4] = data[::4].translate(a)
data[1::4] ... | [
"Websocket masking function.\n\n `mask` is a `bytes` object of length 4; `data` is a `bytearray`\n object of any length. The contents of `data` are masked with `mask`,\n as specified in section 5.3 of RFC 6455.\n\n Note that this function mutates the `data` argument.\n\n This pure-python implementati... |
Please provide a description of the function:def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
return loads(self.data) | [
"Return parsed JSON data.\n\n .. versionadded:: 0.22\n "
] |
Please provide a description of the function:def parse_frame(self, buf: bytes) -> List[Tuple[bool, Optional[int],
bytearray,
Optional[bool]]]:
frames = []
if self._tail:
buf, self... | [
"Return the next frame from the socket."
] |
Please provide a description of the function:async def _send_frame(self, message: bytes, opcode: int,
compress: Optional[int]=None) -> None:
if self._closing:
ws_logger.warning('websocket connection is closing.')
rsv = 0
# Only compress larger pac... | [
"Send a frame over the websocket with message as its payload."
] |
Please provide a description of the function:async def pong(self, message: bytes=b'') -> None:
if isinstance(message, str):
message = message.encode('utf-8')
await self._send_frame(message, WSMsgType.PONG) | [
"Send pong message."
] |
Please provide a description of the function:async def ping(self, message: bytes=b'') -> None:
if isinstance(message, str):
message = message.encode('utf-8')
await self._send_frame(message, WSMsgType.PING) | [
"Send ping message."
] |
Please provide a description of the function:async def send(self, message: Union[str, bytes],
binary: bool=False,
compress: Optional[int]=None) -> None:
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
await ... | [
"Send a frame over the websocket with message as its payload."
] |
Please provide a description of the function:async def close(self, code: int=1000, message: bytes=b'') -> None:
if isinstance(message, str):
message = message.encode('utf-8')
try:
await self._send_frame(
PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.C... | [
"Close the websocket, sending the specified code and message."
] |
Please provide a description of the function:def update_cookies(self,
cookies: LooseCookies,
response_url: URL=URL()) -> None:
hostname = response_url.raw_host
if not self._unsafe and is_ip_address(hostname):
# Don't accept cookies from... | [
"Update cookies."
] |
Please provide a description of the function:def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]':
self._do_expiration()
request_url = URL(request_url)
filtered = SimpleCookie()
hostname = request_url.raw_host or ""
is_not_secure = request_url.scheme not... | [
"Returns this jar's cookies filtered by their attributes."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.