鳗鱼函数 returns 空

Eel function returns null

我正在用 Eel 模块开发 python 程序。 但是有问题。就是 eel.getImgSrc(path) 函数中的 return null 来获取图像的字节数据。 看看这段代码。

-----web/main.js------

async function run(path) {
    let n = await eel.getImgSrc(path)() //path is correct. but n is null.
    console.log(n);
}

-----app.py-----

@eel.expose
def getImgSrc(path):
    f =  open(path, 'rb')
    return f.read()

在 Eel 中,Python 和 JavaScript 层通过来回传递 JSON 进行通信。在内部,Python 端通过定义如下的函数传递您的 Python return 值: jsn.dumps(obj, default=lambda o: None) 在您的情况下会产生字符串 null 。您可以通过将代码更新为仅用于 调试目的 来确认此行为:

@eel.expose
def getImgSrc(path):
    f =  open(path, 'rb')

    data = f.read()
    print(json.dumps(data, default=lambda o: None))

    return data

您会看到它打印出来 null。这就是为什么您在 JavaScript 一侧看到 null

我不是 Eel 项目的开发人员,所以我无法解释为什么会发生这种情况(我只是在源代码中看到它)。但现在您知道它正在发生,您可以通过找到一种方法来对您的数据进行编码,以便它可以通过 JSON 传递来解决问题。 (您可以使用我在上面发布的示例代码来检查它是否正确编码。)

在网络上搜索如何使用 Python 将二进制数据编码为 JSON 并使用 JavaScript 解码会产生很多结果...所以选择一个适合您的特定结果需要。一种常见的方法(也是 discussed in an issue on the Eel project website)是在 Python 端对数据进行 base64 编码,然后在 JavaScript 端对其进行解码。这并不理想,但它是我过去使用过的可行解决方案。你的代码应该是这样的...

-----web/main.js------

async function run(path) {
    let n = await eel.getImgSrc(path)() // should no longer be null    
    console.log(atob(n));
}

-----app.py-----

@eel.expose
def getImgSrc(path):
    f =  open(path, 'rb')

    data = f.read()
    data = base64.b64encode(data).decode("utf-8")

    return data

此外,HTML 图片标签可以接受 base64 编码数据,因此您可以执行以下操作:

async function run(path) {
    let n = await eel.getImgSrc(path)() // should no longer be null    
    let imageEl = document.getElementById('image');
    imageEl.src = "data:image/jpeg;base64," + n;
    // any other processing...

}

您可能需要调整这些示例以满足您的具体需要。