在QtWebKit
中,是否有一种方法来控制每个HTTP请求的超时时间?例如,如果我为每个HTTP请求设置3秒钟,并且在3秒钟后请求没有完成,则该请求将被中止,其他请求将启动。
我查看了QNetworkAccessManager
API参考文档,但没有找到合适的解决方案。
没有内置的方法来自定义超时时间。有一个已经开放多年的错误报告。解决这个问题的一种方法是使用自定义的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_())