2012-10-25 28 views
3

QtWebKit的時間,是否有一個來控制爲每個HTTP請求的超時的方法?例如,如果設置了3秒每個HTTP請求,和3秒後,如果請求還沒有完成,則該請求被中止,其他請求將開始。QtWebKit的:控制每個HTTP請求可能消耗

我查了QNetworkAccessManager API參考,但無法找到一個妥善的解決辦法。

+1

我不知道什麼consume'在這裏指。你想設置一個自定義超時值,以便在一定時間後中止請求嗎? – Avaris

+0

@Avaris是的。對不起,我英文很差。如果我在一定時間後沒有收到回覆,我想中止HTTP請求。 – flyer

回答

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

是否有機會做同樣的事情,但使用QWebPage?我的意思是我想要頁面mainFrame()。在主窗口中加載(請求)。此次QNAM中止注資將是完美的。我有一個問題,它在一些圖像/文件加載時出現問題。永遠喋喋不休 – holms