简体   繁体   English

有什么方法可以从网页运行内部 python 脚本?

[英]Any way to run an internal python script from a webpage?

I finally made a project that I wanted to make since a long time:终于做了一个想做很久的项目:

I'm using an Arduino Uno to replace my PC power button (with a simple relay) and that Arduino Board is connected to a Raspi 3 for network connection purposes我正在使用 Arduino Uno 来替换我的 PC 电源按钮(带有一个简单的继电器),并且 Arduino 板连接到 Raspi 3 以用于网络连接

My wish is to do a webpage (or a API-Like request) that at a touch of a button (preferably in a password-protected page) It'll power the PC on我的愿望是做一个网页(或类似 API 的请求),只需按一下按钮(最好是在受密码保护的页面中),它就会打开电脑

I know how to code in Python, and my script to control the Arduino is already done but I can't find a way to run, only server-side, a Python Script from a button in a webpage我知道如何在 Python 中编码,并且我的控制 Arduino 的脚本已经完成,但我找不到运行方法,只能在服务器端运行,Python 网页中的按钮脚本

I found that CherryPy framework but I don't think it'll suit my needs我发现了CherryPy框架,但我认为它不适合我的需要

Can someone give me any ideas about that please?有人可以给我任何想法吗?

As already mentioned by @ForceBru, you need a python webserver.正如@ForceBru 已经提到的,您需要一个 python 网络服务器。

If this can be useful to you, this is a possible unsecure implementation using flask:如果这对您有用,这可能是使用 flask 的不安全实现:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/turnOn')
def hello_world():
    k = request.args.get('key')
    if k == "superSecretKey":
        # Do something ..
        return 'Ok'
    else:
        return 'Nope'

If you put this in an app.py name file and, after having installed flask ( pip install flask ), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=superSecretKey . If you put this in an app.py name file and, after having installed flask ( pip install flask ), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=超级密钥

You could write a brief html gui with a button and a key field in a form but I leaves that to you (you need to have fun too.).您可以编写一个简短的 html gui,其中包含一个按钮和一个表单中的关键字段,但我将其留给您(您也需要玩得开心。)。 To avoid potential security issues you could use a POST method and https.为避免潜在的安全问题,您可以使用 POST 方法和 https。 Look at the flask documentation for more infos.查看flask 文档了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM