Skip to content
Advertisement

update elements in electron with python (and flask?)

I am trying to use a python script to update elements on electron. I have read many tutorials but most of them didn’t work and the one that did work I couldn’t understand how to change it to use it in my program. For this reason I have created an electron app that updates a <p> element with javascript and another <p> element that should be updated by python. From what I have read I need to use flask which I don’t know and that’s why I need someone to explain to me how to call the python functions with javascript and what flask code I need in the .py file. Here are the files of my project:

main.js (the one generated automatically by electron forge normally named index.js just renamed)

const { app, BrowserWindow } = require('electron');
const path = require('path');

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 700 
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

index.html (the html file of the page that will be updated with python)

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Test</title>

</head>

<body>
  
  <p id="loadedByJavascript">Loading current value from Javascript</p>
  <p id="loadedByPython">Loading current value from python</p>


  <script src="index.js">
  </script>

</body>

</html>

index.js (the .js file of the page that will be updated with python)

var printFromJs = document.getElementById("loadedByJavascript")
var printFromPython = document.getElementById("loadedByPython")
var count = 0

function updateWithJavascript() {
    printFromJs.innerHTML = count;
    count +=1;
}
updateWithJavascript()

function updateWithPython() {
    //I dont know how to call the function hello from hello.py
}
updateWithPython()

//call them every 3 seconds
setInterval(updateWithJavascript, 3000)
setInterval(updateWithPython, 3000)

hello.py (the python file whose hello() function I would like to call)

from datetime import datetime

def hello():
    return str(datetime.now())

Also should the python function always return a string or can it return more complex things like a list or a dataframe and use each value in a different html element? Thank you for your time

Advertisement

Answer

You can use JQuery to make a GET request to a Flask route.

JS:

function updateWithPython() {
    $.get('url + /hello', function(data) {
        printFromPython.innerHTML = data;
    });
}

Python:

from flask import Flask
from datetime import datetime

app = Flask(__name__)

@app.route("/hello")
def hello():
    return str(datetime.now())

if __name__ == "__main__":
    app.run()
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement