tornado.netutil — Miscellaneous network utilities¶
Miscellaneous network utility code.
- tornado.netutil.bind_sockets(port: int, address: Optional[str] = None, family: AddressFamily = AddressFamily.AF_UNSPEC, backlog: int = 128, flags: Optional[int] = None, reuse_port: bool = False) List[socket][source]¶
Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use).
Address may be either an IP address or hostname. If it’s a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either
socket.AF_INETorsocket.AF_INET6to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available.The
backlogargument has the same meaning as forsocket.listen().flagsis a bitmask of AI_* flags togetaddrinfo, likesocket.AI_PASSIVE | socket.AI_NUMERICHOST.reuse_portoption setsSO_REUSEPORToption for every socket in the list. If your platform doesn’t support this option ValueError will be raised.
- tornado.netutil.bind_unix_socket(file: str, mode: int = 384, backlog: int = 128) socket[source]¶
Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised.
Returns a socket object (not a list of socket objects like
bind_sockets)
- tornado.netutil.add_accept_handler(sock: socket, callback: Callable[[socket, Any], None]) Callable[[], None][source]¶
Adds an
IOLoopevent handler to accept new connections onsock.When a connection is accepted,
callback(connection, address)will be run (connectionis a socket object, andaddressis the address of the other end of the connection). Note that this signature is different from thecallback(fd, events)signature used forIOLoophandlers.A callable is returned which, when called, will remove the
IOLoopevent handler and stop processing further incoming connections.Changed in version 5.0: The
io_loopargument (deprecated since version 4.1) has been removed.Changed in version 5.0: A callable is returned (
Nonewas returned before).
- tornado.netutil.is_valid_ip(ip: str) bool[source]¶
Returns
Trueif the given string is a well-formed IP address.Supports IPv4 and IPv6.
- class tornado.netutil.Resolver(*args: Any, **kwargs: Any)[source]¶
Configurable asynchronous DNS resolver interface.
By default, a blocking implementation is used (which simply calls
socket.getaddrinfo). An alternative implementation can be chosen with theResolver.configureclass method:Resolver.configure('tornado.netutil.ThreadedResolver')
The implementations of this interface included with Tornado are
tornado.netutil.DefaultExecutorResolver(deprecated)tornado.netutil.BlockingResolver(deprecated)tornado.netutil.ThreadedResolver(deprecated)tornado.platform.twisted.TwistedResolver(deprecated)tornado.platform.caresresolver.CaresResolver(deprecated)
Changed in version 5.0: The default implementation has changed from
BlockingResolvertoDefaultExecutorResolver.Changed in version 6.2: The default implementation has changed from
DefaultExecutorResolvertoDefaultLoopResolver.- resolve(host: str, port: int, family: AddressFamily = AddressFamily.AF_UNSPEC) Awaitable[List[Tuple[int, Any]]][source]¶
Resolves an address.
The
hostargument is a string which may be a hostname or a literal IP address.Returns a
Futurewhose result is a list of (family, address) pairs, where address is a tuple suitable to pass tosocket.connect(i.e. a(host, port)pair for IPv4; additional fields may be present for IPv6). If acallbackis passed, it will be run with the result as an argument when it is complete.- Raises
IOError – if the address cannot be resolved.
Changed in version 4.4: Standardized all implementations to raise
IOError.Changed in version 6.0: The
callbackargument was removed. Use the returned awaitable object instead.
- class tornado.netutil.DefaultExecutorResolver(*args: Any, **kwargs: Any)[source]¶
Resolver implementation using
IOLoop.run_in_executor.New in version 5.0.
Deprecated since version 6.2: Use
DefaultLoopResolverinstead.
- class tornado.netutil.DefaultLoopResolver(*args: Any, **kwargs: Any)[source]¶
Resolver implementation using
asyncio.loop.getaddrinfo.
- class tornado.netutil.ExecutorResolver(*args: Any, **kwargs: Any)[source]¶
Resolver implementation using a
concurrent.futures.Executor.Use this instead of
ThreadedResolverwhen you require additional control over the executor being used.The executor will be shut down when the resolver is closed unless
close_resolver=False; use this if you want to reuse the same executor elsewhere.Changed in version 5.0: The
io_loopargument (deprecated since version 4.1) has been removed.Deprecated since version 5.0: The default
Resolvernow usesasyncio.loop.getaddrinfo; use that instead of this class.
- class tornado.netutil.BlockingResolver(*args: Any, **kwargs: Any)[source]¶
Default
Resolverimplementation, usingsocket.getaddrinfo.The
IOLoopwill be blocked during the resolution, although the callback will not be run until the nextIOLoopiteration.Deprecated since version 5.0: The default
Resolvernow usesIOLoop.run_in_executor; use that instead of this class.
- class tornado.netutil.ThreadedResolver(*args: Any, **kwargs: Any)[source]¶
Multithreaded non-blocking
Resolverimplementation.Requires the
concurrent.futurespackage to be installed (available in the standard library since Python 3.2, installable withpip install futuresin older versions).The thread pool size can be configured with:
Resolver.configure('tornado.netutil.ThreadedResolver', num_threads=10)
Changed in version 3.1: All
ThreadedResolversshare a single thread pool, whose size is set by the first one to be created.Deprecated since version 5.0: The default
Resolvernow usesIOLoop.run_in_executor; use that instead of this class.
- class tornado.netutil.OverrideResolver(*args: Any, **kwargs: Any)[source]¶
Wraps a resolver with a mapping of overrides.
This can be used to make local DNS changes (e.g. for testing) without modifying system-wide settings.
The mapping can be in three formats:
{ # Hostname to host or ip "example.com": "127.0.1.1", # Host+port to host+port ("login.example.com", 443): ("localhost", 1443), # Host+port+address family to host+port ("login.example.com", 443, socket.AF_INET6): ("::1", 1443), }
Changed in version 5.0: Added support for host-port-family triplets.
- tornado.netutil.ssl_options_to_context(ssl_options: Union[Dict[str, Any], SSLContext], server_side: Optional[bool] = None) SSLContext[source]¶
Try to convert an
ssl_optionsdictionary to anSSLContextobject.The
ssl_optionsdictionary contains keywords to be passed tossl.wrap_socket. In Python 2.7.9+,ssl.SSLContextobjects can be used instead. This function converts the dict form to itsSSLContextequivalent, and may be used when a component which accepts both forms needs to upgrade to theSSLContextversion to use features like SNI or NPN.Changed in version 6.2: Added server_side argument. Omitting this argument will result in a DeprecationWarning on Python 3.10.
- tornado.netutil.ssl_wrap_socket(socket: socket, ssl_options: Union[Dict[str, Any], SSLContext], server_hostname: Optional[str] = None, server_side: Optional[bool] = None, **kwargs: Any) SSLSocket[source]¶
Returns an
ssl.SSLSocketwrapping the given socket.ssl_optionsmay be either anssl.SSLContextobject or a dictionary (as accepted byssl_options_to_context). Additional keyword arguments are passed towrap_socket(either theSSLContextmethod or thesslmodule function as appropriate).Changed in version 6.2: Added server_side argument. Omitting this argument will result in a DeprecationWarning on Python 3.10.