Search code examples
pythonpython-3.xurllibeel

Eel urllib request function returns null to JS, but value to python


I have the following Python code for Eel

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)

Now when I call this from JavaScript with

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

    return result;
}

I always get null. When I call print(python_function()) from Python I get an HTML string as expected.

When testing, JavaScript returns null before the URL is reached. I thought Python blocked code. Do I need to reimplement a block? Returning a string from python_function will get the actual string in the jsFunction.


Solution

  • Try this:

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

    The difference is the response.decode('latin1') return.

    In the Python layer of Eel, you must return an object that is serializable according to the Python's JSON encoder, and the raw binary string returned by read() is not serializable.

    Take a look at the answer I provided to this question for a detailed explanation of the communication requirements between the Python and JavaScript layers of Eel.

    Also, a separate issue that you should address in your Python code is that eel.init('web') should appear before any @eel.expose. As it is currently written, you're probably seeing an error being displayed in the JavaScript console about not being able to load some resources.