Kaveh Shahbazian Kaveh Shahbazian - 1 month ago 22
Python Question

Serving resource to QWebView of PyQT5

How can serve resource (files like html, css, js, fonts) for a desktop app to QWebView (in PyQT5)?

What I want is:


  1. If possible handling requested resource by Webkit engine of PyQT5
    with a custom scheme like say
    custom://app/jquery.js
    and returning the file.

  2. If possible handling standard http verbs (GET, POST, ...) for that
    custom scheme.



If these 2 are not possible (at least not possible in a pure Pythonic way):


  • How can I intercept requests coming from the embedded Webkit and
    provide resource (html, css, js) based on a pattern in url (like say
    some regex
    (?<controller>[^/])/(?<action>[^/])
    )?


Answer

You need to create your own subclass of QNetworkAccessManager, which returns a custom QNetworkReply for the desired protocol, and then set this as network access manager for you QWebView's page.

This article shows a good example how this can be done - applied to PyQt5, this is how it could look:

from PyQt5.QtCore import QUrl, QTimer, QIODevice
from PyQt5.QtWidgets import QApplication
from PyQt5.QtNetwork import (QNetworkAccessManager,
                             QNetworkReply,
                             QNetworkRequest)
from PyQt5.QtWebKitWidgets import QWebView

import sys

class ExampleNetworkAccessManager(QNetworkAccessManager):

    def __init__(self, parent=None):
        super().__init__(parent=parent)

    def createRequest(self, operation, request, device):
        if request.url().scheme() == 'example':
            return ExampleReply(self, operation, request, device)
        return super().createRequest(operation, request, device)


class ExampleReply(QNetworkReply):

    def __init__(self, parent, operation, request, device):
        super().__init__(parent=parent)
        self.setRequest(request)
        self.setOperation(operation)
        self.setUrl(request.url())
        self.bytes_read = 0
        self.content = b''

        # give webkit time to connect to the finished and readyRead signals
        QTimer.singleShot(200, self.load_content)

    def load_content(self):
        if self.operation() == QNetworkAccessManager.PostOperation:
            # handle operations ...
            pass
        # some dummy content for this example
        self.content = b'''<html>
            <h1>hello world!</h1>
            <p>...</p>
            </html>'''
        self.open(QIODevice.ReadOnly | QIODevice.Unbuffered)
        self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.content))
        self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html")
        self.readyRead.emit()
        self.finished.emit()

    def abort(self):
        pass

    def isSequential(self):
        return True

    def bytesAvailable(self):
        ba = len(self.content) - self.bytes_read + super().bytesAvailable()
        return ba

    def readData(self, size):
        if self.bytes_read >= len(self.content):
            return None
        data = self.content[self.bytes_read:self.bytes_read + size]
        self.bytes_read += len(data)
        return data

    def manager(self):
        return self.parent()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    wv = QWebView()
    enam = ExampleNetworkAccessManager()
    wv.page().setNetworkAccessManager(enam)
    wv.show()
    wv.setUrl(QUrl("example://test.html"))
    app.exec()
Comments