PySide6.QtNetwork.QNetworkAccessManager¶
- class QNetworkAccessManager¶
- The - QNetworkAccessManagerclass allows the application to send network requests and receive replies.- Details- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - The Network Access API is constructed around one - QNetworkAccessManagerobject, which holds the common configuration and settings for the requests it sends. It contains the proxy and cache configuration, as well as the signals related to such issues, and reply signals that can be used to monitor the progress of a network operation. One- QNetworkAccessManagerinstance should be enough for the whole Qt application. Since- QNetworkAccessManageris based on QObject, it can only be used from the thread it belongs to.- Once a - QNetworkAccessManagerobject has been created, the application can use it to send requests over the network. A group of standard functions is supplied that take a request and optional data, and each returns a- QNetworkReplyobject. The returned object is used to obtain any data returned in response to the corresponding request.- A simple download off the network could be accomplished with: - manager = QNetworkAccessManager(self) manager.finished.connect( self.replyFinished) manager.get(QNetworkRequest(QUrl("http://qt-project.org"))) - QNetworkAccessManagerhas an asynchronous API. When the- replyFinishedslot above is called, the parameter it takes is the- QNetworkReplyobject containing the downloaded data as well as meta-data (headers, etc.).- Note - After the request has finished, it is the responsibility of the user to delete the - QNetworkReplyobject at an appropriate time. Do not directly delete it inside the slot connected to- finished(). You can use the deleteLater() function.- Note - QNetworkAccessManagerqueues the requests it receives. The number of requests executed in parallel is dependent on the protocol. Currently, for the HTTP protocol on desktop platforms, 6 requests are executed in parallel for one host/port combination.- Note - QNetworkAccessManagerdoesn’t handle RFC 2616 Section 8.2.2 properly, in that it doesn’t react to incoming data until it’s done writing. For example, the upload of a large file won’t stop even if the server returns a status code that instructs the client to not continue.- A more involved example, assuming the manager is already existent, can be: - request = QNetworkRequest() request.setUrl(QUrl("http://qt-project.org")) request.setRawHeader("User-Agent", "MyOwnBrowser 1.0") reply = manager.get(request) reply.readyRead.connect(self.slotReadyRead) reply.errorOccurred.connect( self.slotError) reply.sslErrors.connect( self.slotSslErrors) - See also - Synopsis¶- Methods¶- def - __init__()
- def - cache()
- def - connectToHost()
- def - cookieJar()
- def - deleteResource()
- def - get()
- def - head()
- def - post()
- def - proxy()
- def - proxyFactory()
- def - put()
- def - redirectPolicy()
- def - setCache()
- def - setCookieJar()
- def - setProxy()
 - Virtual methods¶- def - createRequest()
 - Slots¶- Signals¶- Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - class Operation¶
- Indicates the operation this reply is processing. - Constant - Description - QNetworkAccessManager.Operation.HeadOperation - retrieve headers operation (created with - head())- QNetworkAccessManager.Operation.GetOperation - retrieve headers and download contents (created with - get())- QNetworkAccessManager.Operation.PutOperation - upload contents operation (created with - put())- QNetworkAccessManager.Operation.PostOperation - send the contents of an HTML form for processing via HTTP POST (created with - post())- QNetworkAccessManager.Operation.DeleteOperation - delete contents operation (created with - deleteResource())- QNetworkAccessManager.Operation.CustomOperation - custom operation (created with - sendCustomRequest())- See also 
 - Constructs a - QNetworkAccessManagerobject that is the center of the Network Access API and sets- parentas the parent object.- addStrictTransportSecurityHosts(knownHosts)¶
- Parameters:
- knownHosts – .list of QHstsPolicy 
 
 - Adds HTTP Strict Transport Security policies into HSTS cache. - knownHostscontains the known hosts that have- QHstsPolicyinformation.- Note - An expired policy will remove a known host from the cache, if previously present. - Note - While processing HTTP responses, - QNetworkAccessManagercan also update the HSTS cache, removing or updating exitsting policies or introducing new- knownHosts. The current implementation thus is server-driven, client code can provide- QNetworkAccessManagerwith previously known or discovered policies, but this information can be overridden by “Strict-Transport-Security” response headers.- authenticationRequired(reply, authenticator)¶
- Parameters:
- reply – - QNetworkReply
- authenticator – - QAuthenticator
 
 
 - This signal is emitted whenever a final server requests authentication before it delivers the requested contents. The slot connected to this signal should fill the credentials for the contents (which can be determined by inspecting the - replyobject) in the- authenticatorobject.- QNetworkAccessManagerwill cache the credentials internally and will send the same values if the server requires authentication again, without emitting the authenticationRequired() signal. If it rejects the credentials, this signal will be emitted again.- Note - To have the request not send credentials you must not call setUser() or setPassword() on the - authenticatorobject. This will result in the- finished()signal being emitted with a- QNetworkReplywith error- AuthenticationRequiredError.- Note - It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns. - autoDeleteReplies()¶
- Return type:
- bool 
 
 - Returns the true if - QNetworkAccessManageris currently configured to automatically delete QNetworkReplies, false otherwise.- cache()¶
- Return type:
 
 - Returns the cache that is used to store data obtained from the network. - See also - clearAccessCache()¶
 - Flushes the internal cache of authentication data and network connections. - This function is useful for doing auto tests. - See also - clearConnectionCache()¶
 - Flushes the internal cache of network connections. In contrast to - clearAccessCache()the authentication data is preserved.- See also - connectToHost(hostName[, port=80])¶
- Parameters:
- hostName – str 
- port – int 
 
 
 - Initiates a connection to the host given by - hostNameat port- port. This function is useful to complete the TCP handshake to a host before the HTTP request is made, resulting in a lower network latency.- Note - This function has no possibility to report errors. - connectToHostEncrypted(hostName[, port=443[, sslConfiguration=QSslConfiguration.defaultConfiguration()]])¶
- Parameters:
- hostName – str 
- port – int 
- sslConfiguration – - QSslConfiguration
 
 
 - Initiates a connection to the host given by - hostNameat port- port, using- sslConfiguration. This function is useful to complete the TCP and SSL handshake to a host before the HTTPS request is made, resulting in a lower network latency.- Note - Preconnecting a HTTP/2 connection can be done by calling setAllowedNextProtocols() on - sslConfigurationwith QSslConfiguration::ALPNProtocolHTTP2 contained in the list of allowed protocols. When using HTTP/2, one single connection per host is enough, i.e. calling this method multiple times per host will not result in faster network transactions.- Note - This function has no possibility to report errors. - See also - connectToHostEncrypted(hostName, port, sslConfiguration, peerName)
- Parameters:
- hostName – str 
- port – int 
- sslConfiguration – - QSslConfiguration
- peerName – str 
 
 
 - Initiates a connection to the host given by - hostNameat port- port, using- sslConfigurationwith- peerNameset to be the hostName used for certificate validation. This function is useful to complete the TCP and SSL handshake to a host before the HTTPS request is made, resulting in a lower network latency.- Note - Preconnecting a HTTP/2 connection can be done by calling setAllowedNextProtocols() on - sslConfigurationwith QSslConfiguration::ALPNProtocolHTTP2 contained in the list of allowed protocols. When using HTTP/2, one single connection per host is enough, i.e. calling this method multiple times per host will not result in faster network transactions.- Note - This function has no possibility to report errors. - See also - cookieJar()¶
- Return type:
 
 - Returns the - QNetworkCookieJarthat is used to store cookies obtained from the network as well as cookies that are about to be sent.- See also - createRequest(op, request[, outgoingData=None])¶
- Parameters:
- op – - Operation
- request – - QNetworkRequest
- outgoingData – - QIODevice
 
- Return type:
 
 - Returns a new - QNetworkReplyobject to handle the operation- opand request- originalReq. The device- outgoingDatais always 0 for Get and Head requests, but is the value passed to- post()and- put()in those operations (the QByteArray variants will pass a QBuffer object).- The default implementation calls - cookiesForUrl()on the cookie jar set with- setCookieJar()to obtain the cookies to be sent to the remote server.- The returned object must be in an open state. - deleteResource(request)¶
- Parameters:
- request – - QNetworkRequest
- Return type:
 
 - Sends a request to delete the resource identified by the URL of - request.- Note - This feature is currently available for HTTP only, performing an HTTP DELETE request. - See also - enableStrictTransportSecurityStore(enabled[, storeDir=""])¶
- Parameters:
- enabled – bool 
- storeDir – str 
 
 
 - If - enabledis- true, the internal HSTS cache will use a persistent store to read and write HSTS policies.- storeDirdefines where this store will be located. The default location is defined by QStandardPaths::CacheLocation. If there is no writable QStandartPaths::CacheLocation and- storeDiris an empty string, the store will be located in the program’s working directory.- Note - If HSTS cache already contains HSTS policies by the time persistent store is enabled, these policies will be preserved in the store. In case both cache and store contain the same known hosts, policies from cache are considered to be more up-to-date (and thus will overwrite the previous values in the store). If this behavior is undesired, enable HSTS store before enabling Strict Transport Security. By default, the persistent store of HSTS policies is disabled. - encrypted(reply)¶
- Parameters:
- reply – - QNetworkReply
 
 - This signal is emitted when an SSL/TLS session has successfully completed the initial handshake. At this point, no user data has been transmitted. The signal can be used to perform additional checks on the certificate chain, for example to notify users when the certificate for a website has changed. The - replyparameter specifies which network reply is responsible. If the reply does not match the expected criteria then it should be aborted by calling- abort()by a slot connected to this signal. The SSL configuration in use can be inspected using the- sslConfiguration()method.- Internally, - QNetworkAccessManagermay open multiple connections to a server, in order to allow it process requests in parallel. These connections may be reused, which means that the encrypted() signal would not be emitted. This means that you are only guaranteed to receive this signal for the first connection to a site in the lifespan of the- QNetworkAccessManager.- See also - finished(reply)¶
- Parameters:
- reply – - QNetworkReply
 
 - This signal is emitted whenever a pending network reply is finished. The - replyparameter will contain a pointer to the reply that has just finished. This signal is emitted in tandem with the- finished()signal.- See - finished()for information on the status that the object will be in.- Note - Do not delete the - replyobject in the slot connected to this signal. Use deleteLater().- See also - get(request)¶
- Parameters:
- request – - QNetworkRequest
- Return type:
 
 - Posts a request to obtain the contents of the target - requestand returns a new- QNetworkReplyobject opened for reading which emits the readyRead() signal whenever new data arrives.- The contents as well as associated headers will be downloaded. - See also - get(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QIODevice
 
- Return type:
 
 - Note - A GET request with a message body is not cached. - Note - If the request is redirected, the message body will be kept only if the status code is 308. - get(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QByteArray
 
- Return type:
 
 - Note - A GET request with a message body is not cached. - Note - If the request is redirected, the message body will be kept only if the status code is 308. - head(request)¶
- Parameters:
- request – - QNetworkRequest
- Return type:
 
 - Posts a request to obtain the network headers for - requestand returns a new- QNetworkReplyobject which will contain such headers.- The function is named after the HTTP request associated (HEAD). - isStrictTransportSecurityEnabled()¶
- Return type:
- bool 
 
 - Returns true if HTTP Strict Transport Security (HSTS) was enabled. By default HSTS is disabled. - See also - isStrictTransportSecurityStoreEnabled()¶
- Return type:
- bool 
 
 - Returns true if HSTS cache uses a permanent store to load and store HSTS policies. - See also - post(request, multiPart)¶
- Parameters:
- request – - QNetworkRequest
- multiPart – - QHttpMultiPart
 
- Return type:
 
 - Sends the contents of the - multiPartmessage to the destination specified by- request.- This can be used for sending MIME multipart messages over HTTP. - See also - post(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QIODevice
 
- Return type:
 
 - Sends an HTTP POST request to the destination specified by - requestand returns a new- QNetworkReplyobject opened for reading that will contain the reply sent by the server. The contents of the- datadevice will be uploaded to the server.- datamust be open for reading and must remain valid until the- finished()signal is emitted for this reply.- Note - Sending a POST request on protocols other than HTTP and HTTPS is undefined and will probably fail. - See also - post(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QByteArray
 
- Return type:
 
 - Sends the contents of the - databyte array to the destination specified by- request.- Parameters:
- reply – - QNetworkReply
- authenticator – - QSslPreSharedKeyAuthenticator
 
 
 - This signal is emitted if the SSL/TLS handshake negotiates a PSK ciphersuite, and therefore a PSK authentication is then required. The - replyobject is the- QNetworkReplythat is negotiating such ciphersuites.- When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the SSL handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed - authenticatorobject according to their needs.- Note - Ignoring this signal, or failing to provide the required credentials, will cause the handshake to fail, and therefore the connection to be aborted. - Note - The - authenticatorobject is owned by the reply and must not be deleted by the application.- See also - proxy()¶
- Return type:
 
 - Returns the - QNetworkProxythat the requests sent using this- QNetworkAccessManagerobject will use. The default value for the proxy is- DefaultProxy.- proxyAuthenticationRequired(proxy, authenticator)¶
- Parameters:
- proxy – - QNetworkProxy
- authenticator – - QAuthenticator
 
 
 - This signal is emitted whenever a proxy requests authentication and - QNetworkAccessManagercannot find a valid, cached credential. The slot connected to this signal should fill in the credentials for the proxy- proxyin the- authenticatorobject.- QNetworkAccessManagerwill cache the credentials internally. The next time the proxy requests authentication,- QNetworkAccessManagerwill automatically send the same credential without emitting the proxyAuthenticationRequired signal again.- If the proxy rejects the credentials, - QNetworkAccessManagerwill emit the signal again.- See also - proxyFactory()¶
- Return type:
 
 - Returns the proxy factory that this - QNetworkAccessManagerobject is using to determine the proxies to be used for requests.- Note that the pointer returned by this function is managed by - QNetworkAccessManagerand could be deleted at any time.- See also - put(request, multiPart)¶
- Parameters:
- request – - QNetworkRequest
- multiPart – - QHttpMultiPart
 
- Return type:
 
 - Sends the contents of the - multiPartmessage to the destination specified by- request.- This can be used for sending MIME multipart messages over HTTP. - See also - put(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QIODevice
 
- Return type:
 
 - Uploads the contents of - datato the destination- requestand returns a new- QNetworkReplyobject that will be open for reply.- datamust be opened for reading when this function is called and must remain valid until the- finished()signal is emitted for this reply.- Whether anything will be available for reading from the returned object is protocol dependent. For HTTP, the server may send a small HTML page indicating the upload was successful (or not). Other protocols will probably have content in their replies. - Note - For HTTP, this request will send a PUT request, which most servers do not allow. Form upload mechanisms, including that of uploading files through HTML forms, use the POST mechanism. - See also - put(request, data)
- Parameters:
- request – - QNetworkRequest
- data – - QByteArray
 
- Return type:
 
 - Sends the contents of the - databyte array to the destination specified by- request.- redirectPolicy()¶
- Return type:
 
 - Returns the redirect policy that is used when creating new requests. - See also - sendCustomRequest(request, verb, multiPart)¶
- Parameters:
- request – - QNetworkRequest
- verb – - QByteArray
- multiPart – - QHttpMultiPart
 
- Return type:
 
 - Sends a custom request to the server identified by the URL of - request.- Sends the contents of the - multiPartmessage to the destination specified by- request.- This can be used for sending MIME multipart messages for custom verbs. - See also - sendCustomRequest(request, verb[, data=None])
- Parameters:
- request – - QNetworkRequest
- verb – - QByteArray
- data – - QIODevice
 
- Return type:
 
 - Sends a custom request to the server identified by the URL of - request.- It is the user’s responsibility to send a - verbto the server that is valid according to the HTTP specification.- This method provides means to send verbs other than the common ones provided via - get()or- post()etc., for instance sending an HTTP OPTIONS command.- If - datais not empty, the contents of the- datadevice will be uploaded to the server; in that case, data must be open for reading and must remain valid until the- finished()signal is emitted for this reply.- Note - This feature is currently available for HTTP(S) only. - See also - sendCustomRequest(request, verb, data)
- Parameters:
- request – - QNetworkRequest
- verb – - QByteArray
- data – - QByteArray
 
- Return type:
 
 - Sends the contents of the - databyte array to the destination specified by- request.- setAutoDeleteReplies(autoDelete)¶
- Parameters:
- autoDelete – bool 
 
 - Enables or disables automatic deletion of - QNetworkReplies.- Setting - shouldAutoDeleteto true is the same as setting the- AutoDeleteReplyOnFinishAttributeattribute to true on all future- QNetworkRequestspassed to this instance of- QNetworkAccessManagerunless the attribute was already explicitly set on the- QNetworkRequest.- setCache(cache)¶
- Parameters:
- cache – - QAbstractNetworkCache
 
 - Sets the manager’s network cache to be the - cachespecified. The cache is used for all requests dispatched by the manager.- Use this function to set the network cache object to a class that implements additional features, like saving the cookies to permanent storage. - Note - QNetworkAccessManagertakes ownership of the- cacheobject.- QNetworkAccessManagerby default does not have a set cache. Qt provides a simple disk cache,- QNetworkDiskCache, which can be used.- See also - setCookieJar(cookieJar)¶
- Parameters:
- cookieJar – - QNetworkCookieJar
 
 - Sets the manager’s cookie jar to be the - cookieJarspecified. The cookie jar is used by all requests dispatched by the manager.- Use this function to set the cookie jar object to a class that implements additional features, like saving the cookies to permanent storage. - Note - QNetworkAccessManagertakes ownership of the- cookieJarobject.- If - cookieJaris in the same thread as this- QNetworkAccessManager, it will set the parent of the- cookieJarso that the cookie jar is deleted when this object is deleted as well. If you want to share cookie jars between different- QNetworkAccessManagerobjects, you may want to set the cookie jar’s parent to 0 after calling this function.- QNetworkAccessManagerby default does not implement any cookie policy of its own: it accepts all cookies sent by the server, as long as they are well formed and meet the minimum security requirements (cookie domain matches the request’s and cookie path matches the request’s). In order to implement your own security policy, override the- cookiesForUrl()and- setCookiesFromUrl()virtual functions. Those functions are called by- QNetworkAccessManagerwhen it detects a new cookie.- setProxy(proxy)¶
- Parameters:
- proxy – - QNetworkProxy
 
 - Sets the proxy to be used in future requests to be - proxy. This does not affect requests that have already been sent. The- proxyAuthenticationRequired()signal will be emitted if the proxy requests authentication.- A proxy set with this function will be used for all requests issued by - QNetworkAccessManager. In some cases, it might be necessary to select different proxies depending on the type of request being sent or the destination host. If that’s the case, you should consider using- setProxyFactory().- See also - setProxyFactory(factory)¶
- Parameters:
- factory – - QNetworkProxyFactory
 
 - Sets the proxy factory for this class to be - factory. A proxy factory is used to determine a more specific list of proxies to be used for a given request, instead of trying to use the same proxy value for all requests.- All queries sent by - QNetworkAccessManagerwill have type- UrlRequest.- For example, a proxy factory could apply the following rules: - if the target address is in the local network (for example, if the hostname contains no dots or if it’s an IP address in the organization’s range), return - NoProxy
- if the request is FTP, return an FTP proxy 
- if the request is HTTP or HTTPS, then return an HTTP proxy 
- otherwise, return a SOCKSv5 proxy server 
 - The lifetime of the object - factorywill be managed by- QNetworkAccessManager. It will delete the object when necessary.- setRedirectPolicy(policy)¶
- Parameters:
- policy – - RedirectPolicy
 
 - Sets the manager’s redirect policy to be the - policyspecified. This policy will affect all subsequent requests created by the manager.- Use this function to enable or disable HTTP redirects on the manager’s level. - Note - When creating a request QNetworkRequest::RedirectAttributePolicy has the highest priority, next by priority the manager’s policy. - The default value is - NoLessSafeRedirectPolicy. Clients relying on manual redirect handling are encouraged to set this policy explicitly in their code.- See also - setStrictTransportSecurityEnabled(enabled)¶
- Parameters:
- enabled – bool 
 
 - If - enabledis- true,- QNetworkAccessManagerfollows the HTTP Strict Transport Security policy (HSTS, RFC6797). When processing a request,- QNetworkAccessManagerautomatically replaces the “http” scheme with “https” and uses a secure transport for HSTS hosts. If it’s set explicitly, port 80 is replaced by port 443.- When HSTS is enabled, for each HTTP response containing HSTS header and received over a secure transport, - QNetworkAccessManagerwill update its HSTS cache, either remembering a host with a valid policy or removing a host with an expired or disabled HSTS policy.- See also - setTransferTimeout(timeout)¶
- Parameters:
- timeout – int 
 
 - Sets - timeoutas the transfer timeout in milliseconds.- See also - milliseconds)- transferTimeout()- transferTimeoutAsDuration()- setTransferTimeout([duration=QNetworkRequest.DefaultTransferTimeout])
- Parameters:
- duration – - std::chrono::milliseconds
 
 - Sets the timeout - durationto abort the transfer if no data is exchanged.- Transfers are aborted if no bytes are transferred before the timeout expires. Zero means no timer is set. If no argument is provided, the timeout is QNetworkRequest::DefaultTransferTimeout . If this function is not called, the timeout is disabled and has the value zero. The request-specific non-zero timeouts set for the requests that are executed override this value. This means that if - QNetworkAccessManagerhas an enabled timeout, it needs to be disabled to execute a request without a timeout.- See also - sslErrors(reply, errors)¶
- Parameters:
- reply – - QNetworkReply
- errors – .list of QSslError 
 
 
 - This signal is emitted if the SSL/TLS session encountered errors during the set up, including certificate verification errors. The - errorsparameter contains the list of errors and- replyis the- QNetworkReplythat is encountering these errors.- To indicate that the errors are not fatal and that the connection should proceed, the - ignoreSslErrors()function should be called from the slot connected to this signal. If it is not called, the SSL session will be torn down before any data is exchanged (including the URL).- This signal can be used to display an error message to the user indicating that security may be compromised and display the SSL settings (see sslConfiguration() to obtain it). If the user decides to proceed after analyzing the remote certificate, the slot should call ignoreSslErrors(). - strictTransportSecurityHosts()¶
- Return type:
- .list of QHstsPolicy 
 
 - Returns the list of HTTP Strict Transport Security policies. This list can differ from what was initially set via - addStrictTransportSecurityHosts()if HSTS cache was updated from a “Strict-Transport-Security” response header.- supportedSchemes()¶
- Return type:
- list of strings 
 
 - Lists all the URL schemes supported by the access manager. - Reimplement this method to provide your own supported schemes in a - QNetworkAccessManagersubclass. It is for instance necessary when your subclass provides support for new protocols.- supportedSchemesImplementation()¶
- Return type:
- list of strings 
 
 - Lists all the URL schemes supported by the access manager. - You should not call this function directly; use - supportedSchemes()instead.- Because of binary compatibility constraints, the - supportedSchemes()method (introduced in Qt 5.2) was not virtual in Qt 5, but now it is. Override the- supportedSchemesmethod rather than this one.- See also - transferTimeout()¶
- Return type:
- int 
 
 - Returns the timeout used for transfers, in milliseconds. - See also - transferTimeoutAsDuration()¶
- Return type:
- std::chrono::milliseconds
 
 - Returns the timeout duration after which the transfer is aborted if no data is exchanged. - The default duration is zero, which means that the timeout is not used. - See also - milliseconds)