📀 Electron
Electron-Flask Integration Project #1
date
Jun 13, 2023
slug
electron-flask-integration-1
author
status
Public
tags
Electron
Flask
summary
type
Post
thumbnail
category
📀 Electron
updatedAt
Jun 21, 2023 07:43 AM
Key Components of the Electron-Flask Project
Electron is a framework for developing desktop applications with web technologies, such as JavaScript, HTML, and CSS. Flask, on the other hand, is a Python web framework that can be used to develop server-side or back-end services.
- Electron
Electron is a framework for creating desktop applications with web technologies. It was developed by GitHub and is used in many popular apps like Visual Studio Code and Slack. The key feature of Electron is that it allows you to build a "web page" with HTML, CSS, and JavaScript, and then package it into a standalone desktop application that runs independently of the user's web browser. This gives you the flexibility and ease-of-use of web development, combined with the ability to interact with the user's computer as a native app would.
- Flask
Flask is a lightweight web server framework written in Python. It's designed to make it easy to set up simple web servers with minimal code. You'd use Flask to create an API (Application Programming Interface) on your server. Each API endpoint corresponds to a specific URL (like
/api/data
), and when an HTTP request is made to that URL, Flask will run a specific function that you've defined, and return the result back to the client.- HTTP
HTTP stands for Hypertext Transfer Protocol, and it's the protocol that's used for communication on the web. When your Electron app wants to communicate with your Flask server, it does so by making HTTP requests. These are basically messages that are sent over the internet from the client (Electron app) to the server (Flask app). The server then responds with an HTTP response, which includes a status code and typically some data. This is often done in the JSON format, which is a common format for data interchange on the web.
Principle
The Electron app and Flask server communicate by sending HTTP requests and responses back and forth. The Electron app makes a request to a specific URL on your Flask server, the server processes the request and sends back a response, and then your Electron app can do something with the response data (like display it in the user interface).
One more point to note is the concept of localhost: This is a special hostname that refers to the current device used to run the application. It is used to access the network services that are running on the host via the loopback network interface. In this case, both the Electron and Flask apps are running on the same machine, so localhost is beging used as the server's hostname.
Set up the Electron front-end to communicate with a Flask backend
STEP 1. Setup your Flask Server and API
The server could be set up to run on your localhost on a specific port, like 5000. You would create various API endpoints that your Electron app can hit to fetch or send data. In your project directory, create a new directory for your Flask app (e.g.,
server
), then create a new Python file (e.g., app.py
). This file will be your Flask server.from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def home(): return jsonify({"message": "Hello from Flask!"}), 200 if __name__ == "__main__": app.run(port=5000)
This will start a server on
localhost:5000
and return a simple JSON response at the root route (/
).STEP 2. Setup your Electron App
In your project directory, you should also set up your Electron app. To start, you would typically have a
main.js
file that starts your Electron app. const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, } }) win.loadFile('index.html') } app.whenReady().then(createWindow)
STEP 3. Connect Flask API with Electron
On the front end, your Electron app can make HTTP requests to the Flask server running on your localhost. To call the Flask API from your Electron app, you could use the built-in
fetch
API (for Electron versions that support it) or use a library like axios
.Create a new HTML file called
index.html
in your Electron app. This is the file that will be loaded by your Electron app, and will call your Flask API<!DOCTYPE html> <html> <body> <h1>Electron Flask Integration</h1> <button id="fetchButton">Fetch Data from Flask API</button> <p id="message"></p> <script> document.getElementById('fetchButton').addEventListener('click', () => { fetch('http://localhost:5000/') .then(response => response.json()) .then(data => document.getElementById('message').innerText = data.message) .catch(error => console.error('Error:', error)); }); </script> </body> </html>
In this example, when the button with the id
fetchButton
is clicked, a GET request is made to the Flask API. The response from the Flask API is then displayed in the paragraph with the id message
.The header,
<h1>
, simply displays the text "Electron Flask Integration". The button, when clicked, will trigger a fetch request to the Flask API running on 'http://localhost:5000/'. The <p>
tag is where the message returned from the Flask API will be displayed. Both the button and the paragraph have unique id
s to allow them to be accessed from the JavaScript code.The JavaScript code is embedded into the HTML inside a
<script>
tag. This script adds an event listener to the button with the id fetchButton
. When the button is clicked ('click'
event), an anonymous arrow function is called. This function does the following:- It uses the
fetch()
function to send a GET request to the Flask server running at 'http://localhost:5000/'.fetch()
returns a Promise that resolves to the Response object representing the response to the request.
- The
then()
method is used to handle the Promise returned byfetch()
. It takes a callback function as a parameter. This function takes the Response object returned byfetch()
and converts it to JSON using thejson()
method. This operation itself returns another Promise, as the conversion to JSON is asynchronous.
- 1. A second
then()
method is used to handle the Promise returned byjson()
. It also takes a callback function as a parameter. This function takes the data returned from the previous Promise (the JSON response from the Flask server) and sets theinnerText
of the paragraph with the idmessage
to be themessage
property of the JSON response.
- Finally,
catch()
method is used to handle any errors that might occur during the fetch operation. If an error occurs, it's logged to the console.
In summary, 1) when the button is clicked, this page sends a GET request to 'http://localhost:5000/', 2) gets the response, converts the response to JSON, 3) then updates the text of the paragraph with the
message
property of the JSON response. If an error occurs at any point, it's logged to the console.Running the App:
- Start your Flask server by navigating to the Flask app directory in your terminal and running
python app.py
.
- Start your Electron app by navigating to the Electron app directory in your terminal and running
npm start
orelectron .
(depending on how your package.json is set up).
- Click the button in your Electron app to fetch data from the Flask API.