QtWebKit:控制每个HTTP请求可以消耗的时间

3

QtWebKit中,是否有一种方法来控制每个HTTP请求的超时时间?例如,如果我为每个HTTP请求设置3秒钟,并且在3秒钟后请求没有完成,则该请求将被中止,其他请求将启动。

我查看了QNetworkAccessManager API参考文档,但没有找到合适的解决方案。


1
我不确定在这个上下文中“consume”的意思。您是否想设置自定义超时值,以便在一定时间后中止请求? - Avaris
@Avaris 是的。抱歉我的英语不好。如果在一定时间内没有收到回复,我想中止HTTP请求。 - flyer
1个回答

3

没有内置的方法来自定义超时时间。有一个已经开放多年的错误报告。解决这个问题的一种方法是使用自定义的QTimer启动您的请求,并将timeout信号连接到回复的abort方法。

一个简单的例子:

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_())

有没有可能使用QWebPage完成同样的操作?我的意思是我想在主窗口中使用page to mainFrame().load(request)。这个QNAM中止注入在那里会非常完美。我遇到了一个问题,它会卡在某些图像/文件加载上,一直卡住... - holms

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接