我是 Python 开发的新手。我有一个程序用于控制在循环中运行的一些传感器 (I/O) While True:。
我想创建一个网页,在那里我可以看到一些值,一些来 self 的程序的变量。在网上搜索,我找到了很多信息,但我不明白该怎么做:我看到很多允许监听 html 请求的网络框架,当我尝试时,它们基本上可以工作。
我想念如何在监听网络请求的脚本 python 和我的 python 程序之间进行交互。我应该将 Web 监听器创建为主程序启动的线程吗?使用某种全局变量?
请您参考如下方法:
从 Web 界面与 Python 脚本进行交互的一种简单的 Web 服务器方法是使用 Python bottle。
这是一个基本的 Python bottle您可以用于您的目的的程序:
from bottle import route, run
@route('/')
def hello():
#using jquery
return """<script> poll get_temp with JavaScript here</script><div id="temp">temp will update here</div>"""
@route('/get_temp')
def getTemp():
temp = readDataBaseForTemp()
return temp
run(host='localhost', port=8080, debug=True)
当你启动这个程序时,你可以使用浏览器在 http://localhost:8080/ 上与它交互 <--- 这将触发 JavaScript 来轮询服务器的温度.显然它并不完整,但这是总体思路。
这里的想法是,JavaScript 只是调用 Python 网络服务器(使用 URL http://localhost:8080/get_temp),这会触发您的 Python myTemperatureControl 脚本。当您的脚本执行并返回一个温度值时,它会将数据发送回请求它的 JavaScript,以便相应地更新网页。
对于您的 myTemperatureControl.py 脚本,您可以将温度读数的输出发送到网络服务器可以访问的公共(public)位置。通常,您会为此目的设置数据库。
while True:
if temperature > 30:
output = 1
else:
output = 0
#update database or file with output
