flyer
flyer

Reputation: 9816

QtWebKit: Control the time that each http request could consume

In QtWebKit, is there a method to control the timeout for each HTTP request? For example, if I set 3 seconds for each HTTP request, and after 3 seconds if the request isn't finished, then the request is aborted and the other requests would start.

I checked the QNetworkAccessManager API reference, but couldn't find a proper solution.

Upvotes: 3

Views: 666

Answers (1)

Avaris
Avaris

Reputation: 36725

There is no built-in way to customize timeouts. There is a bug report that's been open for years. One way to solve this is starting a custom QTimer with your request and connecting the timeout signal to abort method of the reply.

A simple example:

import sys
from PyQt4 import QtGui, QtCore, QtNetwork

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.output = QtGui.QPlainTextEdit()
        # google won't respond to port 81, so it's a way to get timeout
        self.url = QtGui.QLineEdit('http://www.google.com:81')
        self.button = QtGui.QPushButton('Get')
        self.button.clicked.connect(self.getPage)

        navigateLayout = QtGui.QHBoxLayout()
        navigateLayout.addWidget(self.url)
        navigateLayout.addWidget(self.button)
        layout = QtGui.QVBoxLayout()
        layout.addLayout(navigateLayout)
        layout.addWidget(self.output)
        self.setLayout(layout)

        self.manager = QtNetwork.QNetworkAccessManager(self)
        # slot to process finished requests
        self.manager.finished.connect(self.finished)

        self.timeoutTimer = QtCore.QTimer()
        # it only needs to fire once
        self.timeoutTimer.setSingleShot(True)
        # just to see that we aborted
        self.timeoutTimer.timeout.connect(self.aborted)

    def getPage(self):
        url = QtCore.QUrl(self.url.text())
        # request that page
        # `reply` will be the QNetworkReply we'll get our data
        reply = self.manager.get(QtNetwork.QNetworkRequest(url))

        # set our timeout to abort request
        self.timeoutTimer.timeout.connect(reply.abort)
        # start timer (3000ms = 3s)
        self.timeoutTimer.start(3000)

    def finished(self, reply):
        # everything went smoothly and we got our reply before timeout
        # no need to abort now. so stop the timer
        self.timeoutTimer.stop()

        # do something interesting with the result
        status = reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute).toString()
        self.output.appendPlainText('finished (status code %s)' % status)

    def aborted(self):
        # timed out :(
        self.output.appendPlainText('aborted')

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

Upvotes: 3

Related Questions