rnet (Main Module)
The main rnet module contains core classes and types used throughout the library.
Core Classes
rnet.Client
A client for making HTTP requests.
cookie_jar
instance-attribute
__init__
request
async
websocket
async
Sends a WebSocket request.
Examples
trace
async
options
async
patch
async
delete
async
put
async
post
async
head
async
rnet.Response
A response from a request.
Examples
import asyncio
import rnet
async def main():
response = await rnet.get("https://www.rust-lang.org")
print("Status Code: ", response.status)
print("Version: ", response.version)
print("Response URL: ", response.url)
print("Headers: ", response.headers)
print("Content-Length: ", response.content_length)
print("Encoding: ", response.encoding)
print("Remote Address: ", response.remote_addr)
text_content = await response.text()
print("Text: ", text_content)
if __name__ == "__main__":
asyncio.run(main())
text_with_charset
async
Get the full response text given a specific encoding.
HTTP Types
rnet.Method
Bases: Enum
An HTTP method.
rnet.Version
Bases: Enum
An HTTP version.
rnet.StatusCode
HTTP status code.
Request Types
rnet.Request
Bases: TypedDict
rnet.Multipart
rnet.Part
A part of a multipart form.
__init__
Creates a new part.
Arguments
name- The name of the part.value- The value of the part, either text, bytes, a file path, or a async or sync stream.filename- The filename of the part.mime- The MIME type of the part.length- The length of the part when value is a stream (e.g., for file uploads).headers- The custom headers for the part.
WebSocket
rnet.WebSocket
A WebSocket response.
rnet.WebSocketRequest
Bases: TypedDict
read_buffer_size
instance-attribute
Read buffer capacity. This buffer is eagerly allocated and used for receiving messages.
For high read load scenarios a larger buffer, e.g. 128 KiB, improves performance.
For scenarios where you expect a lot of connections and don't need high read load performance a smaller buffer, e.g. 4 KiB, would be appropriate to lower total memory usage.
The default value is 128 KiB.
write_buffer_size
instance-attribute
The target minimum size of the write buffer to reach before writing the data to the underlying stream. The default value is 128 KiB.
If set to 0 each message will be eagerly written to the underlying stream. It is often more optimal to allow them to buffer a little, hence the default value.
Note: flush() will always fully write the buffer regardless.
max_write_buffer_size
instance-attribute
The max size of the write buffer in bytes. Setting this can provide backpressure in the case the write buffer is filling up due to write errors. The default value is unlimited.
Note: The write buffer only builds up past write_buffer_size when writes to the underlying stream are failing. So the write buffer can not fill up if you are not observing write errors even if not flushing.
Note: Should always be at least write_buffer_size + 1 message and probably a little more depending on error handling strategy.
max_message_size
instance-attribute
The maximum size of an incoming message. None means no size limit. The default value is 64 MiB which should be reasonably big for all normal use-cases but small enough to prevent memory eating by a malicious user.
max_frame_size
instance-attribute
The maximum size of a single incoming message frame. None means no size limit. The limit is for frame payload NOT including the frame header. The default value is 16 MiB which should be reasonably big for all normal use-cases but small enough to prevent memory eating by a malicious user.
accept_unmasked_frames
instance-attribute
When set to True, the server will accept and handle unmasked frames from the client. According to RFC 6455, the server must close the connection to the client in such cases, however it seems like there are some popular libraries that are sending unmasked frames, ignoring the RFC. By default this option is set to False, i.e. according to RFC6455.
rnet.Message
A WebSocket message.
close
instance-attribute
Returns the close code and reason of the message if it is a close message.
text_from_json
staticmethod
Creates a new text message from the JSON representation.
Arguments
json- The JSON representation of the message.
binary_from_json
staticmethod
Creates a new binary message from the JSON representation.
Arguments
json- The JSON representation of the message.
from_text
staticmethod
Creates a new text message.
Arguments
text- The text content of the message.
from_binary
staticmethod
Creates a new binary message.
Arguments
data- The binary data of the message.
from_ping
staticmethod
Creates a new ping message.
Arguments
data- The ping data of the message.
from_pong
staticmethod
Creates a new pong message.
Arguments
data- The pong data of the message.
from_close
staticmethod
Creates a new close message.
Arguments
code- The close code.reason- An optional reason for closing.
Streaming
rnet.Streamer
A stream response.
An asynchronous iterator yielding data chunks (bytes) or HTTP trailers (HeaderMap) from the response stream.
Used to stream response content and receive HTTP trailers if present.
Implemented in the stream method of the Response class.
Can be used in an asynchronous for loop in Python.
When streaming a response, each iteration yields either a bytes object (for body data) or a HeaderMap (for HTTP trailers, if the server sends them). This allows you to access HTTP/1.1 or HTTP/2 trailers in addition to the main body.
Examples
import asyncio
import rnet
from rnet import Method, Emulation, HeaderMap
async def main():
resp = await rnet.get("https://example.com/stream-with-trailers")
async with resp.stream() as streamer:
async for chunk in streamer:
if isinstance(chunk, bytes):
print("Chunk: ", chunk)
elif isinstance(chunk, HeaderMap):
print("Trailers: ", chunk)
await asyncio.sleep(0.1)
if __name__ == "__main__":
asyncio.run(main())
Network Types
rnet.SocketAddr
Configuration
rnet.ClientConfig
Bases: TypedDict
cookie_provider
instance-attribute
Set the persistent cookie store for the client.
Cookies received in responses will be passed to this store, and additional requests will query this store for cookies.
By default, no cookie store is used.
timeout
instance-attribute
Enables a request timeout.
The timeout is applied from when the request starts connecting until the response body has finished.
Default is no timeout.
connect_timeout
instance-attribute
Set a timeout for only the connect phase of a Client.
tcp_keepalive
instance-attribute
Set that all sockets have SO_KEEPALIVE set with the supplied duration.
Default is 15 seconds.
tcp_keepalive_interval
instance-attribute
Set that all sockets have SO_KEEPALIVE set with the supplied interval.
Default is 15 seconds.
tcp_keepalive_retries
instance-attribute
Set that all sockets have SO_KEEPALIVE set with the supplied retry count.
Default is 3 retries.
tcp_user_timeout
instance-attribute
Set that all sockets have TCP_USER_TIMEOUT set with the supplied duration.
This option controls how long transmitted data may remain unacknowledged before the connection is force-closed.
Default is 30 seconds.
tcp_nodelay
instance-attribute
Set whether sockets have TCP_NODELAY enabled.
Default is True.
pool_idle_timeout
instance-attribute
Set an optional timeout for idle sockets being kept-alive.
pool_max_idle_per_host
instance-attribute
Sets the maximum idle connection per host allowed in the pool.
verify_hostname
instance-attribute
Configures the use of hostname verification when connecting.
identity
instance-attribute
Represents a private key and X509 cert as a client certificate.
no_proxy
instance-attribute
Clear all proxies, so Client will use no proxy anymore.
This also disables the automatic usage of the "system" proxy.
interface
instance-attribute
Bind connections only on the specified network interface.
This option is only available on the following operating systems:
- Android
- Fuchsia
- Linux
- macOS and macOS-like systems (iOS, tvOS, watchOS and visionOS)
- Solaris and illumos
On Android, Linux, and Fuchsia, this uses the
[SO_BINDTODEVICE][man-7-socket] socket option. On macOS and macOS-like
systems, Solaris, and illumos, this instead uses the [IP_BOUND_IF and
IPV6_BOUND_IF][man-7p-ip] socket options (as appropriate).
Note that connections will fail if the provided interface name is not a network interface that currently exists when a connection is established.
gzip
instance-attribute
Enable auto gzip decompression by checking the Content-Encoding response header.
brotli
instance-attribute
Enable auto brotli decompression by checking the Content-Encoding response header.
deflate
instance-attribute
Enable auto deflate decompression by checking the Content-Encoding response header.