在QtWebKit
中,是否有控制每个HTTP请求超时的方法?例如,如果我为每个HTTP请求设置3秒,如果请求未完成则在3秒后设置,则请求将中止,其他请求将启动。
我检查了QNetworkAccessManager
API参考,但找不到合适的解决方案。
答案 0 :(得分:3)
没有内置方法来自定义超时。有一个bug report已经开放多年了。解决此问题的一种方法是根据您的请求启动自定义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_())