Session
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
Methods
- class Session
-
- add_feature(feature: SessionFeature) None
Adds
feature
’s functionality tosession
. You cannot add multiple features of the sameGLib.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 implementsSessionFeature
, this creates a new feature of that type and adds it tosession
as withadd_feature
. You can use this when you don’t need to customize the new feature in any way. Adding multiple features of the samefeature_type
is not allowed.If
feature_type
is not aSessionFeature
type, this gives each existing feature onsession
the chance to acceptfeature_type
as a “subfeature”. This can be used to add newAuth
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 theresult
asynchronous operation This is useful to get theMessage
of an asynchronous operation started bysession
from itsGio.AsyncReadyCallback
.- Parameters:
result – the
AsyncResult
passed to your callback
- get_feature(feature_type: type) SessionFeature | None
Gets the feature in
session
of typefeature_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 typefeature_type
, provided that it is not disabled formsg
.- Parameters:
feature_type – the
Type
of the feature to getmsg – 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 insession
.
- 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 bysession
.
- get_remote_connectable() SocketConnectable | None
Gets the remote connectable if one set.
- get_tls_database() TlsDatabase | None
Get the
TlsDatabase
currently used bysession
.
- get_tls_interaction() TlsInteraction | None
Get the
TlsInteraction
currently used bysession
.
- 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 typefeature_type
(which can be the type of either aSessionFeature
, or else a subtype of some class managed by another feature, such asAuth
).- 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 givenmsg
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
andcallback
- 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 fromsession
.- 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 offeature_type
) fromsession
.- 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, andsend
will only return once a final response has been received.- Parameters:
msg – a
Message
cancellable – a
Cancellable
- 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:
msg – a
Message
cancellable – a
Cancellable
- 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 eithermsg
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. Callsend_and_read_finish
to get aBytes
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 intoout_stream
.See
send
for more details on the general semantics.Added in version 3.4.
- Parameters:
msg – a
Message
out_stream – a
OutputStream
flags – a set of
OutputStreamSpliceFlags
cancellable – a
Cancellable
- 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 intoout_stream
. Whencallback
is called, then eithermsg
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:
msg – a
Message
out_stream – a
OutputStream
flags – a set of
OutputStreamSpliceFlags
io_priority – the I/O priority of the request
cancellable – a
Cancellable
callback – the callback to invoke
user_data – data for
callback
- 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 eithermsg
has been sent, and its response headers received, or else an error has occurred. Callsend_finish
to get aInputStream
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 fromsession
.If
accept_language
isNone
then no “Accept-Language” will be included in requests. Seeaccept_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 onget_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 bysession
on new connections.If
proxy_resolver
isNone
then no proxies will be used. Seeproxy_resolver
for more information.- Parameters:
proxy_resolver – a
ProxyResolver
orNone
- 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 bysession
on new connections.If
tls_database
isNone
then certificate validation will always fail. Seetls_database
for more information.- Parameters:
tls_database – a
TlsDatabase
- set_tls_interaction(tls_interaction: TlsInteraction | None = None) None
Set a
TlsInteraction
to be used bysession
on new connections.If
tls_interaction
isNone
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 fromsession
.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. Ifuser_agent
isNone
then no “User-Agent” will be included in requests. Seeuser_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 newWebsocketConnection
. On failure it will return aError
.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, andwebsocket_connect_finish
will returnNOT_WEBSOCKET
.- Parameters:
msg –
Message
indicating the WebSocket server to connect toorigin – origin of the connection
protocols – a
None
-terminated array of protocols supportedio_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 awebsocket_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 onMessage
’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 everyMessage
sent, based on the return value ofget_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_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 toNone
if you don’t want to use proxies, or set it to your ownProxyResolver
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 anyTlsConnection
’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 onMessage
’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 emitrestarted
, which will then be followed by otherMessage
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
andrequest_unqueued
are guaranteed to be emitted exactly once, butfinished
(and all of the otherMessage
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 thatsession
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
Fields
- class Session
- parent_instance