How to Call a Python Script from HTML
Integrating Python scripts with HTML allows you to create dynamic web applications. Whether you're building a data dashboard, processing form submissions, or automating tasks, calling Python from HTML is a powerful technique. In this guide, we'll explore the most popular and efficient methods using Flask, a lightweight Python web framework.
Method 1: Using Flask for Web Integration
Flask is a widely used micro-framework for Python that simplifies web development. Here’s how to set it up:
Step 1: Install Flask
First, install Flask using pip:
pip install flask
Step 2: Create a Basic Flask App
Create a Python file (e.g., app.py
) with the following code:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/run_script', methods=['POST'])
def run_script():
# Your Python logic here
result = "Script executed successfully!"
return result
if __name__ == '__main__':
app.run(debug=True)
Step 3: Create an HTML File
In a templates
folder, create index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Call Python from HTML</title>
</head>
<body>
<h1>Run Python Script</h1>
<button onclick="fetch('/run_script', {method: 'POST'})
.then(response => response.text())
.then(data => alert(data))">
Execute Script
</button>
</body>
</html>
Method 2: Using CGI (Common Gateway Interface)
For simpler setups, CGI can be used to call Python scripts from HTML forms.
Step 1: Configure Your Web Server
Ensure your server supports CGI. For Apache, enable mod_cgi
and set up a cgi-bin
directory.
Step 2: Write a Python CGI Script
#!/usr/bin/env python3
print("Content-Type: text/html\n")
print("<h1>Hello from Python CGI!</h1>")
Step 3: Call the Script from HTML
<form action="/cgi-bin/script.py" method="POST">
<input type="submit" value="Run Python Script">
</form>
Best Practices
- Security: Always sanitise inputs when processing form data.
- Error Handling: Use try-except blocks in Python to manage errors gracefully.
- Performance: For heavy computations, consider background tasks with Celery.
- How to call Python script from HTML button
- Best way to run Python code from a webpage
- Flask Python HTML integration tutorial
- Execute Python script on button click HTML
- How to connect HTML form to Python script
- Python CGI script example for web
- Run Python backend from frontend HTML
- How to pass data from HTML to Python
- Web development with Python and HTML
- Simple Flask app to call Python function
No comments:
Post a Comment