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