0

我正在尝试从 Qt 资源系统加载一些 Jinja2 模板。我正在使用 Python 3.8.3、Jinja 2.11.2 和 PyQt 5.15。

问题是我什至无法检测到加载模板的 qrc 路径。QRC 仅适用于 Qt 类?

Python代码:

from jinja2 import Environment, FileSystemLoader

file_loader = FileSystemLoader(":/plantillas/")  # Here is my problem, how I should detect the qrc path?
env = Environment(loader=file_loader)
plantilla = env.get_template("base.md")

二维码:

<!DOCTYPE RCC>
<RCC version="1.0">
    <qresource prefix="plantillas">
        <file alias="base.md">plantillas/base.md</file>
    </qresource>
</RCC>
4

1 回答 1

1

QResource 仅适用于 Qt 世界,因此可能的解决方案是使用 Qt 类创建一个加载器:

qloader.py

import os
from collections import abc

from jinja2.loaders import BaseLoader, split_template_path
from jinja2.exceptions import TemplateNotFound

from PyQt5.QtCore import QDir, QDirIterator, QFile, QFileInfo, QIODevice


class QFileSystemLoader(BaseLoader):
    def __init__(self, searchpath, encoding="utf-8", followlinks=False):
        if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
            searchpath = [searchpath]

        self.searchpath = list(searchpath)
        self.encoding = encoding
        self.followlinks = followlinks

    def get_source(self, environment, template):
        pieces = split_template_path(template)
        for searchpath in self.searchpath:
            filename = os.path.join(searchpath, *pieces)

            f = QFile(filename)
            if not f.exists():
                continue
            if not f.open(QIODevice.ReadOnly):
                continue
            contents = f.readAll().data().decode(self.encoding)
            f.close()

            dt = QFileInfo(f).fileTime(QFile.FileModificationTime)

            def uptodate():
                return QFileInfo(filename).fileTime(QFile.FileModificationTime) == dt

            return contents, filename, uptodate
        raise TemplateNotFound(template)

    def list_templates(self):
        found = set()
        for searchpath in self.searchpath:
            d = QDir(searchpath)
            it_flag = QDirIterator.Subdirectories
            if self.followlinks:
                it_flag |= QDirIterator.FollowSymlinks
            it_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Hidden | QDir.Readable
            if not self.followlinks:
                it_filter |= QDir.NoSymLinks
            it = QDirIterator(searchpath, it_filter, it_flag)
            while it.hasNext():
                it.next()
                found.add(d.relativeFilePath(it.filePath()))
        return sorted(found)
from qloader import QFileSystemLoader


qfile_loader = QFileSystemLoader(":/plantillas/")
env = Environment(loader=qfile_loader)
plantilla = env.get_template("base.md")
于 2020-09-09T03:54:51.850 回答