:right-sidebar: True Server =================================================================== .. currentmodule:: gi.repository.Soup .. class:: Server(**properties: ~typing.Any) :no-contents-entry: Superclasses: :class:`~gi.repository.GObject.Object` :obj:`~gi.repository.Soup.Server` provides a basic implementation of an HTTP server. The recommended usage of this server is for internal use, tasks like a mock server for tests, a private service for IPC, etc. It is not recommended to be exposed to untrusted clients as it may be vulnerable to denial of service attacks or other exploits. To begin, create a server using :obj:`~gi.repository.Server.new`\. Add at least one handler by calling :obj:`~gi.repository.Server.add_handler` or :obj:`~gi.repository.Server.add_early_handler`\; the handler will be called to process any requests underneath the path you pass. (If you want all requests to go to the same handler, just pass "/" (or :const:`None`) for the path.) When a new connection is accepted (or a new request is started on an existing persistent connection), the :obj:`~gi.repository.Soup.Server` will emit :obj:`~gi.repository.Soup.Server.signals.request_started` and then begin processing the request as described below, but note that once the message is assigned a status-code, then callbacks after that point will be skipped. Note also that it is not defined when the callbacks happen relative to various :obj:`~gi.repository.Soup.ServerMessage` signals. Once the headers have been read, :obj:`~gi.repository.Soup.Server` will check if there is a :obj:`~gi.repository.Soup.AuthDomain` ``(qv)`` covering the Request-URI; if so, and if the message does not contain suitable authorization, then the :obj:`~gi.repository.Soup.AuthDomain` will set a status of :const:`~gi.repository.Soup.Status.UNAUTHORIZED` on the message. After checking for authorization, :obj:`~gi.repository.Soup.Server` will look for "early" handlers (added with :obj:`~gi.repository.Server.add_early_handler`\) matching the Request-URI. If one is found, it will be run; in particular, this can be used to connect to signals to do a streaming read of the request body. (At this point, if the request headers contain ``Expect: 100-continue``\, and a status code has been set, then :obj:`~gi.repository.Soup.Server` will skip the remaining steps and return the response. If the request headers contain ``Expect: 100-continue`` and no status code has been set, :obj:`~gi.repository.Soup.Server` will return a :const:`~gi.repository.Soup.Status.CONTINUE` status before continuing.) The server will then read in the response body (if present). At this point, if there are no handlers at all defined for the Request-URI, then the server will return :const:`~gi.repository.Soup.Status.NOT_FOUND` to the client. Otherwise (assuming no previous step assigned a status to the message) any "normal" handlers (added with :obj:`~gi.repository.Server.add_handler`\) for the message's Request-URI will be run. Then, if the path has a WebSocket handler registered (and has not yet been assigned a status), :obj:`~gi.repository.Soup.Server` will attempt to validate the WebSocket handshake, filling in the response and setting a status of :const:`~gi.repository.Soup.Status.SWITCHING_PROTOCOLS` or :const:`~gi.repository.Soup.Status.BAD_REQUEST` accordingly. If the message still has no status code at this point (and has not been paused with :obj:`~gi.repository.ServerMessage.pause`\), then it will be given a status of :const:`~gi.repository.Soup.Status.INTERNAL_SERVER_ERROR` (because at least one handler ran, but returned without assigning a status). Finally, the server will emit :obj:`~gi.repository.Soup.Server.signals.request_finished` (or :obj:`~gi.repository.Soup.Server.signals.request_aborted` if an I/O error occurred before handling was completed). If you want to handle the special "*" URI (eg, "OPTIONS *\"), you must explicitly register a handler for "\*"; the default handler will not be used for that case. If you want to process https connections in addition to (or instead of) http connections, you can set the :obj:`~gi.repository.Soup.Server.props.tls_certificate` property. Once the server is set up, make one or more calls to :obj:`~gi.repository.Server.listen`\, :obj:`~gi.repository.Server.listen_local`\, or :obj:`~gi.repository.Server.listen_all` to tell it where to listen for connections. (All ports on a :obj:`~gi.repository.Soup.Server` use the same handlers; if you need to handle some ports differently, such as returning different data for http and https, you'll need to create multiple ``SoupServer``\s, or else check the passed-in URI in the handler function.). :obj:`~gi.repository.Soup.Server` will begin processing connections as soon as you return to (or start) the main loop for the current thread-default :obj:`~gi.repository.GLib.MainContext`\. Methods ------- .. rst-class:: interim-class .. class:: Server :no-index: .. method:: accept_iostream(stream: ~gi.repository.Gio.IOStream, local_addr: ~gi.repository.Gio.SocketAddress | None = None, remote_addr: ~gi.repository.Gio.SocketAddress | None = None) -> bool Adds a new client stream to the ``server``\. :param stream: a :obj:`~gi.repository.Gio.IOStream` :param local_addr: the local :obj:`~gi.repository.Gio.SocketAddress` associated with the ``stream`` :param remote_addr: the remote :obj:`~gi.repository.Gio.SocketAddress` associated with the ``stream`` .. method:: add_auth_domain(auth_domain: ~gi.repository.Soup.AuthDomain) -> None Adds an authentication domain to ``server``\. Each auth domain will have the chance to require authentication for each request that comes in; normally auth domains will require authentication for requests on certain paths that they have been set up to watch, or that meet other criteria set by the caller. If an auth domain determines that a request requires authentication (and the request doesn't contain authentication), ``server`` will automatically reject the request with an appropriate status (401 Unauthorized or 407 Proxy Authentication Required). If the request used the SoupServer:100-continue Expectation, ``server`` will reject it before the request body is sent. :param auth_domain: a :obj:`~gi.repository.Soup.AuthDomain` .. method:: add_early_handler(path: str | None, callback: ~typing.Callable[[~gi.repository.Soup.Server, ~gi.repository.Soup.ServerMessage, str, dict[str, str] | None, ~typing.Any], None], user_data: ~typing.Any = None) -> None Adds an "early" handler to ``server`` for requests prefixed by ``path``\. Note that "normal" and "early" handlers are matched up together, so if you add a normal handler for "/foo" and an early handler for "/foo/bar", then a request to "/foo/bar" (or any path below it) will run only the early handler. (But if you add both handlers at the same path, then both will get run.) For requests under ``path`` (that have not already been assigned a status code by a :obj:`~gi.repository.Soup.AuthDomain` or a signal handler), ``callback`` will be invoked after receiving the request headers, but before receiving the request body; the message's method and request-headers properties will be set. Early handlers are generally used for processing requests with request bodies in a streaming fashion. If you determine that the request will contain a message body, normally you would call :obj:`~gi.repository.MessageBody.set_accumulate` on the message's request-body to turn off request-body accumulation, and connect to the message's :obj:`~gi.repository.Soup.ServerMessage.signals.got_chunk` signal to process each chunk as it comes in. To complete the message processing after the full message body has been read, you can either also connect to :obj:`~gi.repository.Soup.ServerMessage.signals.got_body`\, or else you can register a non-early handler for ``path`` as well. As long as you have not set the status-code by the time :obj:`~gi.repository.Soup.ServerMessage.signals.got_body` is emitted, the non-early handler will be run as well. :param path: the toplevel path for the handler :param callback: callback to invoke for requests under ``path`` :param user_data: data for ``callback`` .. method:: add_handler(path: str | None, callback: ~typing.Callable[[~gi.repository.Soup.Server, ~gi.repository.Soup.ServerMessage, str, dict[str, str] | None, ~typing.Any], None], user_data: ~typing.Any = None) -> None Adds a handler to ``server`` for requests prefixed by ``path``\. If ``path`` is :const:`None` or "/", then this will be the default handler for all requests that don't have a more specific handler. (Note though that if you want to handle requests to the special "*" URI, you must explicitly register a handler for "*\"; the default handler will not be used for that case.) For requests under ``path`` (that have not already been assigned a status code by a :obj:`~gi.repository.Soup.AuthDomain`\, an early server handler, or a signal handler), ``callback`` will be invoked after receiving the request body; the :obj:`~gi.repository.Soup.ServerMessage`\'s method, request-headers, and request-body properties will be set. After determining what to do with the request, the callback must at a minimum call :obj:`~gi.repository.ServerMessage.set_status` on the message to set the response status code. Additionally, it may set response headers and/or fill in the response body. If the callback cannot fully fill in the response before returning (eg, if it needs to wait for information from a database, or another network server), it should call :obj:`~gi.repository.ServerMessage.pause` to tell ``server`` to not send the response right away. When the response is ready, call :obj:`~gi.repository.ServerMessage.unpause` to cause it to be sent. To send the response body a bit at a time using "chunked" encoding, first call :obj:`~gi.repository.MessageHeaders.set_encoding` to set :const:`~gi.repository.Soup.Encoding.CHUNKED` on the response-headers. Then call :obj:`~gi.repository.MessageBody.append` (or :obj:`~gi.repository.MessageBody.append_bytes`\)) to append each chunk as it becomes ready, and :obj:`~gi.repository.ServerMessage.unpause` to make sure it's running. (The server will automatically pause the message if it is using chunked encoding but no more chunks are available.) When you are done, call :obj:`~gi.repository.MessageBody.complete` to indicate that no more chunks are coming. :param path: the toplevel path for the handler :param callback: callback to invoke for requests under ``path`` :param user_data: data for ``callback`` .. method:: add_websocket_extension(extension_type: ~gobject.GType) -> None Add support for a WebSocket extension of the given ``extension_type``\. When a WebSocket client requests an extension of ``extension_type``\, a new :obj:`~gi.repository.Soup.WebsocketExtension` of type ``extension_type`` will be created to handle the request. Note that :obj:`~gi.repository.Soup.WebsocketExtensionDeflate` is supported by default, use :obj:`~gi.repository.Server.remove_websocket_extension` if you want to disable it. :param extension_type: a :obj:`~gi.repository.GObject.Type` .. method:: add_websocket_handler(path: str | None, origin: str | None, protocols: list[str] | None, callback: ~typing.Callable[[~gi.repository.Soup.Server, ~gi.repository.Soup.ServerMessage, str, ~gi.repository.Soup.WebsocketConnection, ~typing.Any], None], user_data: ~typing.Any = None) -> None Adds a WebSocket handler to ``server`` for requests prefixed by ``path``\. If ``path`` is :const:`None` or "/", then this will be the default handler for all requests that don't have a more specific handler. When a path has a WebSocket handler registered, ``server`` will check incoming requests for WebSocket handshakes after all other handlers have run (unless some earlier handler has already set a status code on the message), and update the request's status, response headers, and response body accordingly. If ``origin`` is non-:const:`None`, then only requests containing a matching "Origin" header will be accepted. If ``protocols`` is non-:const:`None`, then only requests containing a compatible "Sec-WebSocket-Protocols" header will be accepted. More complicated requirements can be handled by adding a normal handler to ``path``\, and having it perform whatever checks are needed and setting a failure status code if the handshake should be rejected. :param path: the toplevel path for the handler :param origin: the origin of the connection :param protocols: the protocols supported by this handler :param callback: callback to invoke for successful WebSocket requests under ``path`` :param user_data: data for ``callback`` .. method:: disconnect() -> None Closes and frees ``server``\'s listening sockets. Note that if there are currently requests in progress on ``server``\, that they will continue to be processed if ``server``\'s :obj:`~gi.repository.GLib.MainContext` is still running. You can call :obj:`~gi.repository.Server.listen`\, etc, after calling this function if you want to start listening again. .. method:: do_request_aborted(self, msg: ~gi.repository.Soup.ServerMessage) -> None :param msg: .. method:: do_request_finished(self, msg: ~gi.repository.Soup.ServerMessage) -> None :param msg: .. method:: do_request_read(self, msg: ~gi.repository.Soup.ServerMessage) -> None :param msg: .. method:: do_request_started(self, msg: ~gi.repository.Soup.ServerMessage) -> None :param msg: .. method:: get_listeners() -> list[~gi.repository.Gio.Socket] Gets ``server``\'s list of listening sockets. You should treat these sockets as read-only; writing to or modifiying any of these sockets may cause ``server`` to malfunction. .. method:: get_tls_auth_mode() -> ~gi.repository.Gio.TlsAuthenticationMode Gets the ``server`` SSL/TLS client authentication mode. .. method:: get_tls_certificate() -> ~gi.repository.Gio.TlsCertificate | None Gets the ``server`` SSL/TLS certificate. .. method:: get_tls_database() -> ~gi.repository.Gio.TlsDatabase | None Gets the ``server`` SSL/TLS database. .. method:: get_uris() -> list[~gi.repository.GLib.Uri] Gets a list of URIs corresponding to the interfaces ``server`` is listening on. These will contain IP addresses, not hostnames, and will also indicate whether the given listener is http or https. Note that if you used :obj:`~gi.repository.Server.listen_all` the returned URIs will use the addresses ``0.0.0.0`` and ``::``\, rather than actually returning separate URIs for each interface on the system. .. method:: is_https() -> bool Checks whether ``server`` is capable of https. In order for a server to run https, you must call :obj:`~gi.repository.Server.set_tls_certificate`\, or set the :obj:`~gi.repository.Soup.Server.props.tls_certificate` property, to provide it with a certificate to use. If you are using the deprecated single-listener APIs, then a return value of :const:`True` indicates that the :obj:`~gi.repository.Soup.Server` serves https exclusively. If you are using :obj:`~gi.repository.Server.listen`\, etc, then a :const:`True` return value merely indicates that the server is *able* to do https, regardless of whether it actually currently is or not. Use :obj:`~gi.repository.Server.get_uris` to see if it currently has any https listeners. .. method:: listen(address: ~gi.repository.Gio.SocketAddress, options: ~gi.repository.Soup.ServerListenOptions) -> bool Attempts to set up ``server`` to listen for connections on ``address``\. If ``options`` includes :const:`~gi.repository.Soup.ServerListenOptions.HTTPS`, and ``server`` has been configured for TLS, then ``server`` will listen for https connections on this port. Otherwise it will listen for plain http. You may call this method (along with the other "listen" methods) any number of times on a server, if you want to listen on multiple ports, or set up both http and https service. After calling this method, ``server`` will begin accepting and processing connections as soon as the appropriate :obj:`~gi.repository.GLib.MainContext` is run. Note that this API does not make use of dual IPv4/IPv6 sockets; if ``address`` is an IPv6 address, it will only accept IPv6 connections. You must configure IPv4 listening separately. :param address: the address of the interface to listen on :param options: listening options for this server .. method:: listen_all(port: int, options: ~gi.repository.Soup.ServerListenOptions) -> bool Attempts to set up ``server`` to listen for connections on all interfaces on the system. That is, it listens on the addresses ``0.0.0.0`` and/or ``::``\, depending on whether ``options`` includes :const:`~gi.repository.Soup.ServerListenOptions.IPV4_ONLY`, :const:`~gi.repository.Soup.ServerListenOptions.IPV6_ONLY`, or neither.) If ``port`` is specified, ``server`` will listen on that port. If it is 0, ``server`` will find an unused port to listen on. (In that case, you can use :obj:`~gi.repository.Server.get_uris` to find out what port it ended up choosing. See :obj:`~gi.repository.Server.listen` for more details. :param port: the port to listen on, or 0 :param options: listening options for this server .. method:: listen_local(port: int, options: ~gi.repository.Soup.ServerListenOptions) -> bool Attempts to set up ``server`` to listen for connections on "localhost". That is, ``127.0.0.1`` and/or ``::1``\, depending on whether ``options`` includes :const:`~gi.repository.Soup.ServerListenOptions.IPV4_ONLY`, :const:`~gi.repository.Soup.ServerListenOptions.IPV6_ONLY`, or neither). If ``port`` is specified, ``server`` will listen on that port. If it is 0, ``server`` will find an unused port to listen on. (In that case, you can use :obj:`~gi.repository.Server.get_uris` to find out what port it ended up choosing. See :obj:`~gi.repository.Server.listen` for more details. :param port: the port to listen on, or 0 :param options: listening options for this server .. method:: listen_socket(socket: ~gi.repository.Gio.Socket, options: ~gi.repository.Soup.ServerListenOptions) -> bool Attempts to set up ``server`` to listen for connections on ``socket``\. See :obj:`~gi.repository.Server.listen` for more details. :param socket: a listening :obj:`~gi.repository.Gio.Socket` :param options: listening options for this server .. method:: pause_message(msg: ~gi.repository.Soup.ServerMessage) -> None Pauses I/O on ``msg``\. This can be used when you need to return from the server handler without having the full response ready yet. Use :obj:`~gi.repository.Server.unpause_message` to resume I/O. This must only be called on a :obj:`~gi.repository.Soup.ServerMessage` which was created by the :obj:`~gi.repository.Soup.Server` and are currently doing I/O, such as those passed into a [callback``ServerCallback``\] or emitted in a :obj:`~gi.repository.Soup.Server.signals.request_read` signal. .. deprecated:: 3.2 Use :func:`~gi.repository.Soup.ServerMessage.pause` instead. :param msg: a :obj:`~gi.repository.Soup.ServerMessage` associated with ``server``\. .. method:: remove_auth_domain(auth_domain: ~gi.repository.Soup.AuthDomain) -> None Removes ``auth_domain`` from ``server``\. :param auth_domain: a :obj:`~gi.repository.Soup.AuthDomain` .. method:: remove_handler(path: str) -> None Removes all handlers (early and normal) registered at ``path``\. :param path: the toplevel path for the handler .. method:: remove_websocket_extension(extension_type: ~gobject.GType) -> None Removes support for WebSocket extension of type ``extension_type`` (or any subclass of ``extension_type``\) from ``server``\. :param extension_type: a :obj:`~gi.repository.GObject.Type` .. method:: set_tls_auth_mode(mode: ~gi.repository.Gio.TlsAuthenticationMode) -> None Sets ``server``\'s :obj:`~gi.repository.Gio.TlsAuthenticationMode` to use for SSL/TLS client authentication. :param mode: a :obj:`~gi.repository.Gio.TlsAuthenticationMode` .. method:: set_tls_certificate(certificate: ~gi.repository.Gio.TlsCertificate) -> None Sets ``server`` up to do https, using the given SSL/TLS ``certificate``\. :param certificate: a :obj:`~gi.repository.Gio.TlsCertificate` .. method:: set_tls_database(tls_database: ~gi.repository.Gio.TlsDatabase) -> None Sets ``server``\'s :obj:`~gi.repository.Gio.TlsDatabase` to use for validating SSL/TLS client certificates. :param tls_database: a :obj:`~gi.repository.Gio.TlsDatabase` .. method:: unpause_message(msg: ~gi.repository.Soup.ServerMessage) -> None Resumes I/O on ``msg``\. Use this to resume after calling :obj:`~gi.repository.Server.pause_message`\, or after adding a new chunk to a chunked response. I/O won't actually resume until you return to the main loop. This must only be called on a :obj:`~gi.repository.Soup.ServerMessage` which was created by the :obj:`~gi.repository.Soup.Server` and are currently doing I/O, such as those passed into a [callback``ServerCallback``\] or emitted in a :obj:`~gi.repository.Soup.Server.signals.request_read` signal. .. deprecated:: 3.2 Use :func:`~gi.repository.Soup.ServerMessage.unpause` instead. :param msg: a :obj:`~gi.repository.Soup.ServerMessage` associated with ``server``\. Properties ---------- .. rst-class:: interim-class .. class:: Server :no-index: .. attribute:: props.raw_paths :type: bool The type of the None singleton. .. attribute:: props.server_header :type: str The type of the None singleton. .. attribute:: props.tls_auth_mode :type: ~gi.repository.Gio.TlsAuthenticationMode The type of the None singleton. .. attribute:: props.tls_certificate :type: ~gi.repository.Gio.TlsCertificate The type of the None singleton. .. attribute:: props.tls_database :type: ~gi.repository.Gio.TlsDatabase The type of the None singleton. Signals ------- .. rst-class:: interim-class .. class:: Server.signals :no-index: .. method:: request_aborted(message: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param message: the message .. method:: request_finished(message: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param message: the message .. method:: request_read(message: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param message: the message .. method:: request_started(message: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param message: the new message Virtual Methods --------------- .. rst-class:: interim-class .. class:: Server :no-index: .. method:: do_request_aborted(msg: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param msg: .. method:: do_request_finished(msg: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param msg: .. method:: do_request_read(msg: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param msg: .. method:: do_request_started(msg: ~gi.repository.Soup.ServerMessage) -> None The type of the None singleton. :param msg: Fields ------ .. rst-class:: interim-class .. class:: Server :no-index: .. attribute:: parent_instance