[Fixed]-How to serve Django for an Electron app

8đź‘Ť

âś…

First of all, if you app slow to start you can create custom loading-animation template with node which you will serve until your server will be ready, in this case you BrowserWindow flag show should be setup to false, you will “show” your window with window.show() on your custom “server_ready” event. Overall logic of your app should fit in: 1) You start electron app and on load serve browser window with loading… animation, then you spawn child process in which your django app will run, here you have the “bridge” between your electron-node events and python logic, this done as follows:

let django=child_process.spawn('python', [__dirname+'/django_folder/start_server.py']); 

Now variable django is your handler for communication with you django app.
You can communicate as follows:

            let result_name = '';

            django.stdout.on(  
                'data',
                (data:Buffer) => {  
                    result_name+=data.toString('utf8'); 
                }
            );       

            django.stdout.on(
                'end', 
                (reasone) => { 
                   resolve(result); 
                }   
            );   

            django.stderr.on( //error in python will be directed here
                'data',   
                (buf : Buffer) => {
                   reject(buf.toString('utf8'));
                } 
            );  

django.stdin.write(JSON.stringify('notify your django app what you need from it'));

In python:

args=sys.stdin.readlines()[0] #your message in json from electron
args=json.loads(args)['data'] 
print result #send data back to electron

If your app is not very complex you probably can run in on localhost,
so then your python process will notify you through event that it is ready you can reload BrowserWindow with localhost url and start to coordinate interaction communicating with child process.

Leave a comment