def requestStarted(self, job: QWebEngineUrlRequestJob) -> None: path = job.requestUrl().path() path = os.path.realpath(path) print(path) if not path: job.fail(QWebEngineUrlRequestJob.UrlInvalid) return if not os.path.exists(path): job.fail(QWebEngineUrlRequestJob.UrlNotFound) return try: with open(path, 'rb') as file: content_type = mimetypes.guess_type(path) buffer = QBuffer(parent=self) buffer.open(QIODevice.WriteOnly) buffer.write(file.read()) buffer.seek(0) buffer.close() job.reply(content_type[0].encode(), buffer) except Exception as err: raise err
def opBuffer(self): memfile = QBuffer() #创建内存文件 memfile.open(QIODevice.WriteOnly) memfile.write(QByteArray(1024, "121121121121221222121221212")) memfile.write(QByteArray("787887878787878878787878778")) memfile.close() print(memfile.close())
def requestStarted(self, job): """Handle a request for a qute: scheme. This method must be reimplemented by all custom URL scheme handlers. The request is asynchronous and does not need to be handled right away. Args: job: QWebEngineUrlRequestJob """ url = job.requestUrl() if url.scheme() in ['chrome-error', 'chrome-extension']: # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378 job.fail(QWebEngineUrlRequestJob.UrlInvalid) return if not self._check_initiator(job): return if job.requestMethod() != b'GET': job.fail(QWebEngineUrlRequestJob.RequestDenied) return assert url.scheme() == 'qute' log.misc.debug("Got request for {}".format(url.toDisplayString())) try: mimetype, data = qutescheme.data_for_url(url) except qutescheme.Error as e: errors = { qutescheme.NotFoundError: QWebEngineUrlRequestJob.UrlNotFound, qutescheme.UrlInvalidError: QWebEngineUrlRequestJob.UrlInvalid, qutescheme.RequestDeniedError: QWebEngineUrlRequestJob.RequestDenied, qutescheme.SchemeOSError: QWebEngineUrlRequestJob.UrlNotFound, qutescheme.Error: QWebEngineUrlRequestJob.RequestFailed, } exctype = type(e) log.misc.error("{} while handling qute://* URL".format( exctype.__name__)) job.fail(errors[exctype]) except qutescheme.Redirect as e: qtutils.ensure_valid(e.url) job.redirect(e.url) else: log.misc.debug("Returning {} data".format(mimetype)) # We can't just use the QBuffer constructor taking a QByteArray, # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(data) buf.seek(0) buf.close() job.reply(mimetype.encode('ascii'), buf)
def pngbinary2Qlabel(databinary): buff = QBuffer() buff.open(QIODevice.WriteOnly) buff.write(databinary) dat = buff.data() pixmap = QtGui.QPixmap() pixmap.loadFromData(dat, 'PNG') label = QtWidgets.QLabel() label.setPixmap(pixmap) return label
def requestStarted(self, job: QWebEngineUrlRequestJob): url = job.requestUrl() scheme = url.scheme() mime = "text/html" data = b"" if scheme == "dict": try: path = url.path().split("#", 1)[0] (data, mime) = self._ldoce5.get_content(path) mime = "text/html" except NotFoundError: data = b"<h2>Content Not Found</h2>" mime = "text/html" except FilemapError: data = b"<h2>File-Location Map Not Available</h2>" mime = "text/html" except ArchiveError: data = b"<h2>Dictionary Data Not Available</h2>" mime = "text/html" elif scheme == "static": try: data = _load_static_data(url.path().lstrip("/")) mime = "" except EnvironmentError: data = b"<h2>Static File Not Found</h2>" mime = "text/html" elif scheme == "search": searcher_hp = self._searcher_hp searcher_de = self._searcher_de if searcher_hp and searcher_de: try: data = enc_utf8( search_and_render(url, searcher_hp, searcher_de)) mime = "text/html" except Exception: s = u"<h2>Error</h2><div>{0}</div>".format("<br>".join( traceback.format_exc().splitlines())) data = enc_utf8(s) mime = "text/html" else: mime = "text/html" data = b"<p>The full-text search index has not been created yet or broken.</p>" else: job.fail(QWebEngineUrlRequestJob.Error.RequestAborted) buffer = QBuffer(job) buffer.open(QBuffer.OpenModeFlag.ReadWrite) buffer.write(data or b"") buffer.seek(0) job.reply(mime.encode("ascii"), buffer)
def sendDeleteRequest(self, endpoint, data={}, params={}, headers={}): buff = QBuffer() buff.open(QBuffer.ReadWrite) d = json.dumps(data).encode('utf-8') buff.write(d) buff.seek(0) headers.update({"Content-Type":"application/json"}) content = self.sendRequest( endpoint, params, 'delete', buff, headers=headers ) buff.close() return content
def requestStarted(self, job): """Handle a request for a qute: scheme. This method must be reimplemented by all custom URL scheme handlers. The request is asynchronous and does not need to be handled right away. Args: job: QWebEngineUrlRequestJob """ url = job.requestUrl() if url.scheme() == 'chrome-error': # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378 job.fail(QWebEngineUrlRequestJob.UrlInvalid) return assert job.requestMethod() == b'GET' assert url.scheme() == 'qute' log.misc.debug("Got request for {}".format(url.toDisplayString())) try: mimetype, data = qutescheme.data_for_url(url) except qutescheme.NoHandlerFound: log.misc.debug("No handler found for {}".format( url.toDisplayString())) job.fail(QWebEngineUrlRequestJob.UrlNotFound) except qutescheme.QuteSchemeOSError: # FIXME:qtwebengine how do we show a better error here? log.misc.exception("OSError while handling qute://* URL") job.fail(QWebEngineUrlRequestJob.UrlNotFound) except qutescheme.QuteSchemeError: # FIXME:qtwebengine how do we show a better error here? log.misc.exception("Error while handling qute://* URL") job.fail(QWebEngineUrlRequestJob.RequestFailed) except qutescheme.Redirect as e: qtutils.ensure_valid(e.url) job.redirect(e.url) else: log.misc.debug("Returning {} data".format(mimetype)) # We can't just use the QBuffer constructor taking a QByteArray, # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(data) buf.seek(0) buf.close() job.reply(mimetype.encode('ascii'), buf)
class Buffer: def __init__(self): self._data = QByteArray() self.buf = QBuffer(self._data) self.buf.open(QIODevice.ReadWrite) # self.write = self.buf.write #TODO: use QTextStream def data(self): return self._data.data() def dataSize(self): return self._data.size() def write(self, data): self.buf.write(data.encode("utf-8") if type(data) == str else data)
def requestStarted(self, job): """Handle a request for a qute: scheme. This method must be reimplemented by all custom URL scheme handlers. The request is asynchronous and does not need to be handled right away. Args: job: QWebEngineUrlRequestJob """ url = job.requestUrl() assert job.requestMethod() == b'GET' assert url.scheme() == 'qute' log.misc.debug("Got request for {}".format(url.toDisplayString())) try: mimetype, data = qutescheme.data_for_url(url) except qutescheme.NoHandlerFound: log.misc.debug("No handler found for {}".format( url.toDisplayString())) job.fail(QWebEngineUrlRequestJob.UrlNotFound) except qutescheme.QuteSchemeOSError: # FIXME:qtwebengine how do we show a better error here? log.misc.exception("OSError while handling qute://* URL") job.fail(QWebEngineUrlRequestJob.UrlNotFound) except qutescheme.QuteSchemeError: # FIXME:qtwebengine how do we show a better error here? log.misc.exception("Error while handling qute://* URL") job.fail(QWebEngineUrlRequestJob.RequestFailed) except qutescheme.Redirect as e: qtutils.ensure_valid(e.url) job.redirect(e.url) else: log.misc.debug("Returning {} data".format(mimetype)) # We can't just use the QBuffer constructor taking a QByteArray, # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(data) buf.seek(0) buf.close() job.reply(mimetype.encode('ascii'), buf)
def requestStarted(self, job: QWebEngineUrlRequestJob) -> None: # pylint: disable=invalid-name,missing-function-docstring path = job.requestUrl().path() path = os.path.realpath(path) # print("PATH", job.requestUrl().path()) if not path: # print("JOB FAIL", path) job.fail(QWebEngineUrlRequestJob.UrlInvalid) return if not os.path.exists(path): # print("NOT FOUND", path) job.fail(QWebEngineUrlRequestJob.UrlNotFound) return try: with open(path, 'rb') as file: content_type = mimetypes.guess_type(path) if content_type[0] is None: content_type = ("text/plain", None) buffer = QBuffer(parent=self) buffer.open(QIODevice.WriteOnly) buffer.write(file.read()) buffer.seek(0) buffer.close() if content_type[0] is None: job.reply("text/plain", "") else: job.reply(content_type[0].encode(), buffer) except Exception as err: raise err
class SendStream: def __init__(self, data : bytes = b''): self.byteArray = QByteArray(data) self.buffer = QBuffer(self.byteArray) self.buffer.open(QBuffer.ReadOnly if data else QBuffer.WriteOnly) self.stream = QDataStream(self.buffer) def atEnd(self): return self.stream.atEnd() def data(self): return self.byteArray.data() def clear(self): self.buffer.reset() self.byteArray.resize(0) def send(self, tcpSocket : QTcpSocket): writeInt(tcpSocket, len(self.byteArray)) tcpSocket.write(self.byteArray) def writeBytes(self, data: bytes): self.buffer.write(b'\xFE') self.stream.writeBytes(data) def readBytes(self): controlByte = self.buffer.read(1) if controlByte != b'\xFE': raise Exception('Failed to read bytes from stream') return self.stream.readBytes() def writeString(self, s: str): self.buffer.write(b'\xFD') self.stream.writeBytes(s.encode()) def readString(self): controlByte = self.buffer.read(1) if controlByte != b'\xFD': raise Exception('Failed to read string from stream.') return self.stream.readBytes().decode() def writeInt(self, i: int): self.buffer.write(b'\xFC') self.stream.writeInt(i) def readInt(self): controlByte = self.buffer.read(1) if controlByte != b'\xFC': raise Exception('Failed to read int from stream.') return self.stream.readInt() def writeBool(self, b: bool): self.buffer.write(b'\xFB' if b else b'\xFA') def readBool(self): b = self.buffer.read(1) if b == b'\xFB': return True elif b == b'\xFA': return False else: raise Exception('Failed to read bool from stream')
print(1) isOpen = file.open(QIODevice.ReadOnly) print(2) buffer = QBuffer() buffer.open(QIODevice.ReadWrite) print(3) player.setMedia(QMediaContent(), buffer) print(4) if isOpen: while not file.atEnd(): temp = file.readLine() # temp = QByteArray.fromBase64(temp) buffer.write(temp) print(5) videoWidget = QVideoWidget() print(6) player.setVideoOutput(videoWidget) print(7) videoWidget.show() print(8) player.play() while(player.MediaStatus()==QMediaPlayer.UnknownMediaStatus): print("a") print(9) sys.exit(app.exec_())
def requestStarted(self, job: QWebEngineUrlRequestJob): """Handle a request for all scheme. This method must be reimplemented by all custom URL scheme handlers. The request is asynchronous and does not need to be handled right away. Args: job: QWebEngineUrlRequestJob """ url: QUrl = job.requestUrl() if url.scheme() in ["chrome-error", "chrome-extension"]: # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-63378 job.fail(QWebEngineUrlRequestJob.UrlInvalid) return # if not self._check_initiator(job): # return if job.requestMethod() != b"GET": job.fail(QWebEngineUrlRequestJob.RequestDenied) return log.webview.debug("Got request for {}".format(url.toDisplayString())) if url.scheme() == "luminos": try: mimetype, data = Scheme.data_for_url(url) except Scheme.Error as e: errors = { Scheme.NotFoundError: QWebEngineUrlRequestJob.UrlNotFound, Scheme.UrlInvalidError: QWebEngineUrlRequestJob.UrlInvalid, Scheme.RequestDeniedError: QWebEngineUrlRequestJob.RequestDenied, Scheme.SchemeOSError: QWebEngineUrlRequestJob.UrlNotFound, Scheme.Error: QWebEngineUrlRequestJob.RequestFailed, } exctype = type(e) log.webview.error("{} while handling luminos://* URL".format( exctype.__name__)) job.fail(errors[exctype]) except Scheme.Redirect as e: qtutils.ensure_valid(e.url) job.redirect(e.url) else: log.webview.debug("Returning {} data".format(mimetype)) # We can't just use the QBuffer constructor taking a QByteArray, # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(data) buf.seek(0) buf.close() job.reply(mimetype.encode("ascii"), buf) else: """ If it's not our internal scheme then this probably user defined scheme """ try: mimetype, data = Scheme.data_for_custom_scheme(url) except Scheme.NotFoundError: log.webview.debug("handling custom uri scheme for : {}".format( url.toDisplayString())) """ If it's throw error it can mean that user doesn't add their own handler, we will try to handle it ourselves here. """ scheme = url.scheme() if self.schemes is None or not scheme in self.schemes.keys(): job.fail(QWebEngineUrlRequestJob.UrlNotFound) return base_path = self.schemes[scheme] path = os.path.join(base_path, url.host(), url.path()[1:]) if not os.path.exists(path): job.fail(QWebEngineUrlRequestJob.UrlNotFound) return try: with open(path, 'rb') as file: content_type = mimetypes.guess_type(path) buff = QBuffer(parent=self) buff.open(QIODevice.WriteOnly) buff.write(file.read()) buff.seek(0) buff.close() job.reply(content_type[0].encode(), buff) except Exception as e: raise e else: log.webview.debug("Returning {} data".format(mimetype)) # We can't just use the QBuffer constructor taking a QByteArray, # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) buf.open(QIODevice.WriteOnly) buf.write(data) buf.seek(0) buf.close() job.reply(mimetype.encode("ascii"), buf)