基于Python使用EEL发起API请求及Flask与EEL协同运行可行性问询
1. Making API Requests in Python with EEL
EEL’s core strength is bridging JavaScript and Python, so handling API calls is straightforward—you can write the API logic in Python (using a library like requests) and expose that function to your frontend JS. Here’s a practical example:
Step 1: Install Dependencies
First, grab the required packages:
pip install eel requests
Step 2: Python Code (main.py)
Write a Python function to handle API requests, then expose it to EEL so JS can trigger it:
import eel import requests # Point EEL to your assets directory where index.html lives eel.init('assets') @eel.expose # Marks this function as callable from JavaScript def fetch_api_data(api_url): try: # Make the API request using requests response = requests.get(api_url) response.raise_for_status() # Throw an error for HTTP status codes >=400 return response.json() # Send the JSON response back to JS except Exception as e: # Return error details if something goes wrong return {"error": str(e)} # Launch the EEL app if __name__ == '__main__': eel.start('index.html', port=8000)
Step 3: Frontend Code (assets/index.html)
Add a button to trigger the API call and display results:
<!DOCTYPE html> <html> <head> <title>EEL API Demo</title> </head> <body> <button onclick="getExternalData()">Fetch Sample API Data</button> <pre id="result"></pre> <script type="text/javascript" src="/eel.js"></script> <script> async function getExternalData() { // Call the exposed Python function const data = await eel.fetch_api_data('https://jsonplaceholder.typicode.com/todos/1')(); // Display the formatted result document.getElementById('result').textContent = JSON.stringify(data, null, 2); } </script> </body> </html>
Click the button, and your JS will trigger the Python function to make the API request, then display the response in the browser.
2. Running Flask and EEL Simultaneously
Absolutely! You can run both EEL (for frontend-Python interaction) and Flask (for API endpoints) at the same time by running Flask in a separate background thread. This way, EEL’s main loop doesn’t block Flask’s server. Here’s how to adapt your existing project:
Step 1: Install Flask
Add Flask to your dependencies:
pip install flask
Step 2: Updated Python Code (main.py)
Combine EEL setup with Flask, running Flask in a daemon thread:
import eel import requests from flask import Flask, jsonify import threading # Initialize Flask for API endpoints app = Flask(__name__) # Example Flask API route @app.route('/api/greet', methods=['GET']) def greet_api(): return jsonify({"message": "Hello from Flask!", "status": "success"}) # Function to run Flask in a separate thread def run_flask_server(): # Disable debug mode and auto-reloader to avoid thread conflicts app.run(port=5000, debug=False, use_reloader=False) # Initialize EEL eel.init('assets') @eel.expose def fetch_api_data(api_url): try: response = requests.get(api_url) response.raise_for_status() return response.json() except Exception as e: return {"error": str(e)} if __name__ == '__main__': # Start Flask in a daemon thread (exits when EEL app closes) flask_thread = threading.Thread(target=run_flask_server) flask_thread.daemon = True flask_thread.start() # Launch EEL on a different port than Flask to avoid conflicts eel.start('index.html', port=8000)
Step 3: Test Flask API from EEL
Update your index.html to call your Flask API:
<!DOCTYPE html> <html> <head> <title>EEL + Flask Demo</title> </head> <body> <button onclick="getFlaskData()">Fetch Flask API Data</button> <pre id="flask-result"></pre> <script type="text/javascript" src="/eel.js"></script> <script> async function getFlaskData() { // Call your Flask API via the exposed Python function const data = await eel.fetch_api_data('http://localhost:5000/api/greet')(); document.getElementById('flask-result').textContent = JSON.stringify(data, null, 2); } </script> </body> </html>
Key Tips:
- Use different ports for EEL and Flask (we used 8000 for EEL, 5000 for Flask) to avoid port conflicts.
- Disable Flask’s debug mode when running in a thread—its auto-reloader creates extra threads that can cause unexpected behavior.
- Daemon threads ensure Flask shuts down automatically when you close the EEL app.
内容的提问来源于stack exchange,提问作者CoderButBeginner

