在开发使用 PyQt5 的特定系统期间,我需要继承 QNetworkAccessManager 以覆盖 createRequest 方法。我这样做是为了在 WebView 呈现它们并清理缓冲区(这是一个 QIODevice)之前保存 HTTP 资源。
我正在使用 peek() 所以缓冲区在到达 webview 时不会被清除。
但是,有时缓冲区一旦到达 WebView 就不会被清除,我注意到它发生在 WebKit/WebView 不支持内容时,但似乎也发生在其他时间。由于我将数据附加到我自己的变量中(基于缓冲区随后被清除的事实),这会导致数据重复。
例如:
<script>hello</script
如果数据没有被清除,我最终会收到的消息可能是:
<script<script>hello</script>
或其他重复的变体。
下面是产生上述错误的子类的片段。
from PyQt5.QtNetwork import QNetworkAccessManager
class NetworkAccessManager(QNetworkAccessManager):
def __init__(self, parent=None):
super().__init__(parent=parent)
def createRequest(self, op, req, outgoingData):
reply = QNetworkAccessManager.createRequest(self, op, req, outgoingData)
reply.data = b''
reply.readyRead.connect(lambda reply=reply: self._on_reply_ready_read(reply))
return reply
def _on_reply_ready_read(self, reply):
if reply.isReadable() and reply.isOpen() and reply.bytesAvailable():
reply_data = b''
bytes_available = reply.bytesAvailable()
# I put this attribute when the QWebFrame unsupportedContent event is fired.
if hasattr(reply, 'is_unsupported') and reply.is_unsupported:
# When content is unsupported, webview does not call read.
# We call read and clear the buffer instead.
# This works fine!
reply_data = bytes(reply.read(bytes_available))
else:
# The problem resides here.
# At certain times the buffer is not cleared, leading to duplication of data.
reply.data += reply_data