Session

class Session(**properties: Any)

Superclasses: Object

Soup session state object.

Session is the object that controls client-side HTTP. A Session encapsulates all of the state that libsoup is keeping on behalf of your program; cached HTTP connections, authentication information, etc. It also keeps track of various global options and features that you are using.

Most applications will only need a single Session; the primary reason you might need multiple sessions is if you need to have multiple independent authentication contexts. (Eg, you are connecting to a server and authenticating as two different users at different times; the easiest way to ensure that each Message is sent with the authentication information you intended is to use one session for the first user, and a second session for the other user.)

Additional Session functionality is provided by SessionFeature objects, which can be added to a session with add_feature or add_feature_by_type For example, Logger provides support for logging HTTP traffic, ContentDecoder provides support for compressed response handling, and ContentSniffer provides support for HTML5-style response body content sniffing. Additionally, subtypes of Auth can be added as features, to add support for additional authentication types.

All SoupSession’s are created with a AuthManager, and support for %SOUP_TYPE_AUTH_BASIC and %SOUP_TYPE_AUTH_DIGEST. Additionally, sessions using the plain Session class (rather than one of its deprecated subtypes) have a ContentDecoder by default.

Note that all async methods will invoke their callbacks on the thread-default context at the time of the function call.

Constructors

class Session
classmethod new() Session

Creates a Session with the default options.

Methods

class Session
abort() None

Cancels all pending requests in session and closes all idle persistent connections.

add_feature(feature: SessionFeature) None

Adds feature’s functionality to session. You cannot add multiple features of the same GLib.Type to a session.

See the main Session documentation for information on what features are present in sessions by default.

Parameters:

feature – an object that implements SessionFeature

add_feature_by_type(feature_type: type) None

If feature_type is the type of a class that implements SessionFeature, this creates a new feature of that type and adds it to session as with add_feature. You can use this when you don’t need to customize the new feature in any way. Adding multiple features of the same feature_type is not allowed.

If feature_type is not a SessionFeature type, this gives each existing feature on session the chance to accept feature_type as a “subfeature”. This can be used to add new Auth types, for instance.

See the main Session documentation for information on what features are present in sessions by default.

Parameters:

feature_type – a Type

get_accept_language() str | None

Get the value used by session for the “Accept-Language” header on new requests.

get_accept_language_auto() bool

Gets whether session automatically sets the “Accept-Language” header on new requests.

get_async_result_message(result: AsyncResult) Message | None

Gets the Message of the result asynchronous operation This is useful to get the Message of an asynchronous operation started by session from its Gio.AsyncReadyCallback.

Parameters:

result – the AsyncResult passed to your callback

get_feature(feature_type: type) SessionFeature | None

Gets the feature in session of type feature_type.

Parameters:

feature_type – the Type of the feature to get

get_feature_for_message(feature_type: type, msg: Message) SessionFeature | None

Gets the feature in session of type feature_type, provided that it is not disabled for msg.

Parameters:
  • feature_type – the Type of the feature to get

  • msg – a Message

get_idle_timeout() int

Get the timeout in seconds for idle connection lifetime currently used by session.

get_local_address() InetSocketAddress | None

Get the InetSocketAddress to use for the client side of connections in session.

get_max_conns() int

Get the maximum number of connections that session can open at once.

get_max_conns_per_host() int

Get the maximum number of connections that session can open at once to a given host.

get_proxy_resolver() ProxyResolver | None

Get the ProxyResolver currently used by session.

get_remote_connectable() SocketConnectable | None

Gets the remote connectable if one set.

get_timeout() int

Get the timeout in seconds for socket I/O operations currently used by session.

get_tls_database() TlsDatabase | None

Get the TlsDatabase currently used by session.

get_tls_interaction() TlsInteraction | None

Get the TlsInteraction currently used by session.

get_user_agent() str | None

Get the value used by session for the “User-Agent” header on new requests.

has_feature(feature_type: type) bool

Tests if session has at a feature of type feature_type (which can be the type of either a SessionFeature, or else a subtype of some class managed by another feature, such as Auth).

Parameters:

feature_type – the Type of the class of features to check for

preconnect_async(msg: Message, io_priority: int, cancellable: Cancellable | None = None, callback: Callable[[...], None] | None = None, *user_data: Any) None

Start a preconnection to msg.

Once the connection is done, it will remain in idle state so that it can be reused by future requests. If there’s already an idle connection for the given msg host, the operation finishes successfully without creating a new connection. If a new request for the given msg host is made while the preconnect is still ongoing, the request will take the ownership of the connection and the preconnect operation will finish successfully (if there’s a connection error it will be handled by the request).

The operation finishes when the connection is done or an error occurred.

Parameters:
  • msg – a Message

  • io_priority – the I/O priority of the request

  • cancellable – a Cancellable

  • callback – the callback to invoke when the operation finishes

  • user_data – data for progress_callback and callback

preconnect_finish(result: AsyncResult) bool

Complete a preconnect async operation started with preconnect_async.

Parameters:

result – the AsyncResult passed to your callback

remove_feature(feature: SessionFeature) None

Removes feature’s functionality from session.

Parameters:

feature – a feature that has previously been added to session

remove_feature_by_type(feature_type: type) None

Removes all features of type feature_type (or any subclass of feature_type) from session.

Parameters:

feature_type – a Type

send(msg: Message, cancellable: Cancellable | None = None) InputStream

Synchronously sends msg and waits for the beginning of a response.

On success, a InputStream will be returned which you can use to read the response body. (“Success” here means only that an HTTP response was received and understood; it does not necessarily mean that a 2xx class status code was received.)

If non-None, cancellable can be used to cancel the request; send will return a %G_IO_ERROR_CANCELLED error. Note that with requests that have side effects (eg, POST, PUT, DELETE) it is possible that you might cancel the request after the server acts on it, but before it returns a response, leaving the remote resource in an unknown state.

If msg is requeued due to a redirect or authentication, the initial (3xx/401/407) response body will be suppressed, and send will only return once a final response has been received.

Parameters:
send_and_read(msg: Message, cancellable: Cancellable | None = None) Bytes

Synchronously sends msg and reads the response body.

On success, a Bytes will be returned with the response body. This function should only be used when the resource to be retrieved is not too long and can be stored in memory.

See send for more details on the general semantics.

Parameters:
send_and_read_async(msg: Message, io_priority: int, cancellable: Cancellable | None = None, callback: Callable[[...], None] | None = None, *user_data: Any) None

Asynchronously sends msg and reads the response body.

When callback is called, then either msg has been sent, and its response body read, or else an error has occurred. This function should only be used when the resource to be retrieved is not too long and can be stored in memory. Call send_and_read_finish to get a Bytes with the response body.

See send for more details on the general semantics.

Parameters:
  • msg – a Message

  • io_priority – the I/O priority of the request

  • cancellable – a Cancellable

  • callback – the callback to invoke

  • user_data – data for callback

send_and_read_finish(result: AsyncResult) Bytes

Gets the response to a send_and_read_async.

If successful, returns a Bytes with the response body.

Parameters:

result – the AsyncResult passed to your callback

send_and_splice(msg: Message, out_stream: OutputStream, flags: OutputStreamSpliceFlags, cancellable: Cancellable | None = None) int

Synchronously sends msg and splices the response body stream into out_stream.

See send for more details on the general semantics.

Added in version 3.4.

Parameters:
send_and_splice_async(msg: Message, out_stream: OutputStream, flags: OutputStreamSpliceFlags, io_priority: int, cancellable: Cancellable | None = None, callback: Callable[[...], None] | None = None, *user_data: Any) None

Asynchronously sends msg and splices the response body stream into out_stream. When callback is called, then either msg has been sent and its response body spliced, or else an error has occurred.

See send for more details on the general semantics.

Added in version 3.4.

Parameters:
send_and_splice_finish(result: AsyncResult) int

Gets the response to a send_and_splice_async.

Added in version 3.4.

Parameters:

result – the AsyncResult passed to your callback

send_async(msg: Message, io_priority: int, cancellable: Cancellable | None = None, callback: Callable[[...], None] | None = None, *user_data: Any) None

Asynchronously sends msg and waits for the beginning of a response.

When callback is called, then either msg has been sent, and its response headers received, or else an error has occurred. Call send_finish to get a InputStream for reading the response body.

See send for more details on the general semantics.

Parameters:
  • msg – a Message

  • io_priority – the I/O priority of the request

  • cancellable – a Cancellable

  • callback – the callback to invoke

  • user_data – data for callback

send_finish(result: AsyncResult) InputStream

Gets the response to a send_async call.

If successful returns a InputStream that can be used to read the response body.

Parameters:

result – the AsyncResult passed to your callback

set_accept_language(accept_language: str) None

Set the value to use for the “Accept-Language” header on Message’s sent from session.

If accept_language is None then no “Accept-Language” will be included in requests. See accept_language for more information.

Parameters:

accept_language – the languages string

set_accept_language_auto(accept_language_auto: bool) None

Set whether session will automatically set the “Accept-Language” header on requests using a value generated from system languages based on get_language_names.

See accept_language_auto for more information.

Parameters:

accept_language_auto – the value to set

set_idle_timeout(timeout: int) None

Set a timeout in seconds for idle connection lifetime to be used by session on new connections.

See idle_timeout for more information.

Parameters:

timeout – a timeout in seconds

set_proxy_resolver(proxy_resolver: ProxyResolver | None = None) None

Set a ProxyResolver to be used by session on new connections.

If proxy_resolver is None then no proxies will be used. See proxy_resolver for more information.

Parameters:

proxy_resolver – a ProxyResolver or None

set_timeout(timeout: int) None

Set a timeout in seconds for socket I/O operations to be used by session on new connections.

See timeout for more information.

Parameters:

timeout – a timeout in seconds

set_tls_database(tls_database: TlsDatabase | None = None) None

Set a TlsDatabase to be used by session on new connections.

If tls_database is None then certificate validation will always fail. See tls_database for more information.

Parameters:

tls_database – a TlsDatabase

set_tls_interaction(tls_interaction: TlsInteraction | None = None) None

Set a TlsInteraction to be used by session on new connections.

If tls_interaction is None then client certificate validation will always fail.

See tls_interaction for more information.

Parameters:

tls_interaction – a TlsInteraction

set_user_agent(user_agent: str) None

Set the value to use for the “User-Agent” header on Message’s sent from session.

If user_agent has trailing whitespace, session will append its own product token (eg, libsoup/3.0.0) to the end of the header for you. If user_agent is None then no “User-Agent” will be included in requests. See user_agent for more information.

Parameters:

user_agent – the user agent string

websocket_connect_async(msg: Message, origin: str | None, protocols: Sequence[str] | None, io_priority: int, cancellable: Cancellable | None = None, callback: Callable[[...], None] | None = None, *user_data: Any) None

Asynchronously creates a WebsocketConnection to communicate with a remote server.

All necessary WebSocket-related headers will be added to msg, and it will then be sent and asynchronously processed normally (including handling of redirection and HTTP authentication).

If the server returns “101 Switching Protocols”, then msg’s status code and response headers will be updated, and then the WebSocket handshake will be completed. On success, websocket_connect_finish will return a new WebsocketConnection. On failure it will return a Error.

If the server returns a status other than “101 Switching Protocols”, then msg will contain the complete response headers and body from the server’s response, and websocket_connect_finish will return NOT_WEBSOCKET.

Parameters:
  • msgMessage indicating the WebSocket server to connect to

  • origin – origin of the connection

  • protocols – a None-terminated array of protocols supported

  • io_priority – the I/O priority of the request

  • cancellable – a Cancellable

  • callback – the callback to invoke

  • user_data – data for callback

websocket_connect_finish(result: AsyncResult) WebsocketConnection

Gets the WebsocketConnection response to a websocket_connect_async call.

If successful, returns a WebsocketConnection that can be used to communicate with the server.

Parameters:

result – the AsyncResult passed to your callback

Properties

class Session
props.accept_language: str

If non-None, the value to use for the “Accept-Language” header on Message’s sent from this session.

Setting this will disable accept_language_auto.

props.accept_language_auto: bool

If True, Session will automatically set the string for the “Accept-Language” header on every Message sent, based on the return value of get_language_names.

Setting this will override any previous value of accept_language.

props.idle_timeout: int

Connection lifetime (in seconds) when idle. Any connection left idle longer than this will be closed.

Although you can change this property at any time, it will only affect newly-created connections, not currently-open ones. You can call abort after setting this if you want to ensure that all future connections will have this timeout value.

props.local_address: InetSocketAddress

Sets the InetSocketAddress to use for the client side of the connection.

Use this property if you want for instance to bind the local socket to a specific IP address.

props.max_conns: int

The maximum number of connections that the session can open at once.

props.max_conns_per_host: int

The maximum number of connections that the session can open at once to a given host.

props.proxy_resolver: ProxyResolver

A ProxyResolver to use with this session.

If no proxy resolver is set, then the default proxy resolver will be used. See get_default. You can set it to None if you don’t want to use proxies, or set it to your own ProxyResolver if you want to control what proxies get used.

props.remote_connectable: SocketConnectable

Sets a socket to make outgoing connections on. This will override the default behaviour of opening TCP/IP sockets to the hosts specified in the URIs.

This function is not required for common HTTP usage, but only when connecting to a HTTP service that is not using standard TCP/IP sockets. An example of this is a local service that uses HTTP over UNIX-domain sockets, in that case a UnixSocketAddress can be passed to this function.

props.timeout: int

The timeout (in seconds) for socket I/O operations (including connecting to a server, and waiting for a reply to an HTTP request).

Although you can change this property at any time, it will only affect newly-created connections, not currently-open ones. You can call abort after setting this if you want to ensure that all future connections will have this timeout value.

Not to be confused with idle_timeout (which is the length of time that idle persistent connections will be kept open).

props.tls_database: TlsDatabase

Sets the TlsDatabase to use for validating SSL/TLS certificates.

If no certificate database is set, then the default database will be used. See get_default_database.

props.tls_interaction: TlsInteraction

A TlsInteraction object that will be passed on to any TlsConnection’s created by the session.

This can be used to provide client-side certificates, for example.

props.user_agent: str

User-Agent string.

If non-None, the value to use for the “User-Agent” header on Message’s sent from this session.

RFC 2616 says: “The User-Agent request-header field contains information about the user agent originating the request. This is for statistical purposes, the tracing of protocol violations, and automated recognition of user agents for the sake of tailoring responses to avoid particular user agent limitations. User agents SHOULD include this field with requests.”

The User-Agent header contains a list of one or more product tokens, separated by whitespace, with the most significant product token coming first. The tokens must be brief, ASCII, and mostly alphanumeric (although “-”, “_”, and “.” are also allowed), and may optionally include a “/” followed by a version string. You may also put comments, enclosed in parentheses, between or after the tokens.

If you set a user_agent property that has trailing whitespace, Session will append its own product token (eg, libsoup/2.3.2) to the end of the header for you.

Signals

class Session.signals
request_queued(msg: Message) None

Emitted when a request is queued on session.

When sending a request, first request_queued is emitted, indicating that the session has become aware of the request.

After a connection is available to send the request various Message signals are emitted as the message is processed. If the message is requeued, it will emit restarted, which will then be followed by other Message signals when the message is re-sent.

Eventually, the message will emit finished. Normally, this signals the completion of message processing. However, it is possible that the application will requeue the message from the “finished” handler. In that case the process will loop back.

Eventually, a message will reach “finished” and not be requeued. At that point, the session will emit request_unqueued to indicate that it is done with the message.

To sum up: request_queued and request_unqueued are guaranteed to be emitted exactly once, but finished (and all of the other Message signals) may be invoked multiple times for a given message.

Parameters:

msg – the request that was queued

request_unqueued(msg: Message) None

Emitted when a request is removed from session’s queue, indicating that session is done with it.

See request_queued for a detailed description of the message lifecycle within a session.

Parameters:

msg – the request that was unqueued

Virtual Methods

class Session
do_request_queued(msg: Message) None
Parameters:

msg

do_request_unqueued(msg: Message) None
Parameters:

msg

Fields

class Session
parent_instance