Eel urllib请求函数将null返回给JS,但将值返回给python

2024-10-02 22:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下针对Eel的Python代码

import eel, urllib.request

@eel.expose
def python_function():
    response = urllib.request.urlopen('http://google.com').read()
    return(response)

eel.init('web')
eel.start('index.html', port=0)

现在当我用JavaScript调用它时

async function jsFunction() {
    let result = await eel.python_function()();

    return result;
}

我总是得到null。当我从Python调用print(python_function())时,我得到了一个预期的HTML字符串

测试时,JavaScript在到达URL之前返回null。我认为Python阻止了代码。我需要重新实现一个区块吗?从python_function返回字符串将得到jsFunction中的实际字符串


Tags: 字符串代码importreturnresponserequestfunctionresult
1条回答
网友
1楼 · 发布于 2024-10-02 22:29:15

试试这个:

@eel.expose
def python_function():
    response = urllib.request.urlopen('http://google.com').read()

    return response.decode('latin1')

不同之处在于response.decode('latin1')返回

在Eel的Python层中,必须返回可根据Python's JSON encoder进行序列化的对象,并且read()返回的原始二进制字符串不可序列化

看看我给this question的答案,它详细解释了Eel的Python和JavaScript层之间的通信需求

另外,您应该在Python代码中解决的另一个问题是eel.init('web')应该出现在any@eel.expose之前。正如目前编写的,您可能会看到JavaScript控制台中显示了一个错误,即无法加载某些资源

相关问题 更多 >