You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在树莓派上通过Nginx从HTML页面运行Python脚本?

Got it, let’s get your web interface to trigger that motor script—here’s a couple of solid approaches tailored to your existing Raspberry Pi Zero setup:

1. Quick & Simple: CGI with Nginx

Since you already have Nginx up and running, using CGI is the easiest way to bridge your static HTML page to your Python motor script.

  • First, install fcgiwrap (Nginx doesn’t handle CGI directly, so this tool acts as a middleman):

    sudo apt-get update && sudo apt-get install fcgiwrap
    
  • Edit your Nginx config (usually at /etc/nginx/sites-available/default) to enable CGI support. Add this block inside your existing server section:

    location /cgi-bin/ {
        root /var/www;
        fastcgi_pass unix:/var/run/fcgiwrap.socket;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    

    Restart Nginx to apply changes:

    sudo systemctl restart nginx
    
  • Create a CGI script to trigger your motor code. Make a /var/www/cgi-bin/ directory if it doesn’t exist, then add a file named run_motor.cgi:

    #!/usr/bin/env python3
    print("Content-Type: text/html\n")
    print("<html><body>")
    
    import subprocess
    try:
        # Replace with the actual path to your motor script
        subprocess.run(["python3", "/home/pi/motor_run.py"], check=True)
        print("<p>Motor started successfully!</p>")
    except subprocess.CalledProcessError as e:
        print(f"<p>Error running motor: {str(e)}</p>")
    
    print("<a href='/'>Back to control page</a>")
    print("</body></html>")
    
  • Fix permissions so the Nginx user (www-data) can run the script:

    sudo chmod +x /var/www/cgi-bin/run_motor.cgi
    # Give www-data access to GPIO (critical for motor control)
    sudo usermod -aG gpio www-data
    
  • Update your /var/www/html/index.html to add a trigger button:

    <!DOCTYPE html>
    <html>
    <body>
        <h1>Motor Control</h1>
        <button onclick="window.location.href='/cgi-bin/run_motor.cgi'">Start Motor</button>
        <!-- Alternative: Use a POST form to avoid browser caching issues -->
        <form action="/cgi-bin/run_motor.cgi" method="post" style="margin-top:10px;">
            <input type="submit" value="Start Motor (POST)">
        </form>
    </body>
    </html>
    
2. More Flexible: Flask for Custom Parameters

Since you mentioned wanting to let users customize parameters (like run time or schedule), a lightweight Flask app is perfect for this—it lets you build interactive forms easily.

  • Install Flask:

    sudo pip3 install flask
    
  • Create a Flask app file (e.g., /home/pi/motor_app.py):

    from flask import Flask, render_template, request
    import subprocess
    
    app = Flask(__name__)
    
    # Main page with parameter form
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # Handle motor trigger with custom params
    @app.route('/trigger_motor', methods=['POST'])
    def trigger_motor():
        # Get user input from form (default to 5 seconds if not specified)
        run_seconds = request.form.get('run_seconds', default=5, type=int)
        
        try:
            # Pass the custom run time to your motor script
            subprocess.run(["python3", "/home/pi/motor_run.py", str(run_seconds)], check=True)
            return f"<p>Motor running for {run_seconds} seconds! <a href='/'>Back to control</a></p>"
        except subprocess.CalledProcessError as e:
            return f"<p>Error: {str(e)} <a href='/'>Back to control</a></p>"
    
    if __name__ == '__main__':
        # Run the app on all network interfaces (so your phone can reach it)
        app.run(host='0.0.0.0', port=80, debug=True)
    
  • Create a templates folder next to your Flask app, and add index.html inside it:

    <!DOCTYPE html>
    <html>
    <body>
        <h1>Custom Motor Control</h1>
        <form action="/trigger_motor" method="post">
            <label>Run time (seconds):</label>
            <input type="number" name="run_seconds" min="1" max="60" value="5">
            <br><br>
            <input type="submit" value="Start Motor">
        </form>
    </body>
    </html>
    
  • Run the Flask app (to keep it running in the background, use nohup or set up a systemd service):

    nohup python3 /home/pi/motor_app.py &
    
Testing & Troubleshooting
  • Connect your phone to the Pi’s AP, visit 192.168.4.1, and click the button—your motor should run!
  • If it doesn’t work, check logs:
    # Nginx error logs
    sudo tail -f /var/log/nginx/error.log
    # Flask logs (if using that approach)
    cat nohup.out
    
  • Double-check that www-data is in the gpio group (you may need to reboot the Pi for this to take full effect).

内容的提问来源于stack exchange,提问作者Bradderz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:19:25