先給大家展示下效果如圖,感覺還很滿意請繼續閱讀全文:
用到的知識:Python Bottle HTML Javascript JQuery Bootstrap AJAX 當然還有 linux
我去,這么多……我還是一點一點說起吧……
先貼最終的源代碼:
#!/usr/bin/env python3from bottle import get,post,run,request,template@get("/")def index():return template("index")@post("/cmd")def cmd():print("按下了按鈕: "+request.body.read().decode())return "OK"run(host="0.0.0.0")
沒錯,就10句,我一句一句解釋:
1. # !/usr/bin/env python3 ,告訴shell這個文件是Python源代碼,讓bash調用python3來解釋這段代碼
2. from bottle import get,post,run,request,template ,從bottle框架導入了我用到的方法、對象
下邊幾句是定義了2個路由,一個是“/”一個是“/cmd”,前者是get類型(用@get裝飾),后者是POST類型(用的@post裝飾)
第一個路由很簡單,就是讀取index模版(模版就是個html啦)并發送到客戶端(瀏覽器),因為路徑是“/”也就是比如樹莓派的IP地址是:192.168.0.10
那用 http://192.168.0.10:8080 就訪問到了我們的"/”路由(bottle默認端口是8080)
同理,第二個路由的路徑是“/cmd”也就是訪問 http://192.168.0.10:8080/cmd 就訪問到了第二個路由
最后一句: run(host = " 0.0.0.0 " )就是調用bottle的run方法,建立一個http服務器,讓我們能通過瀏覽器訪問我們的界面。
下邊我詳細的解釋一下這些代碼的作用:
第一個路由的作用就是扔給瀏覽器一個HTML(index.tpl)文檔,顯示這個界面:
這個文件的源代碼如下:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>遙控樹莓派</title><link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen"><script src="http://code.jquery.com/jquery.js"></script><style type="text/css">#up {margin-left: 55px;margin-bottom: 3px;}#down {margin-top: 3px;margin-left: 55px;}</style><script>$(function(){$("button").click(function(){$.post("/cmd",this.id,function(data,status){});});});</script></head><body><div id="container" class="container"><div><button id="up" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up"></button></div><div><button id='left' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left"></button><button id='stop' class="btn btn-lg btn-primary glyphicon glyphicon-stop"></button><button id='right' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right"></button></div><div><button id='down' class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down"></button></div></div><script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script></body></html>
這個內容有點多,不過很簡單,就是引用了jquery bootstrap這兩個前端框架,加了5個按鈕(<body></body>之間的代碼)。當然我用了bootstrap內置的上下左右停止這幾個圖標,這5個按鈕的id分辨定義成up,down,left,right,stop,然后寫了如下的關鍵代碼:
$(function(){$("button").click(function(){$.post("/cmd",this.id,function(data,status){});});});
沒錯,就這三句代碼……
第1,2行給所有的按鈕(button)綁定了一個點擊的事件,第三行調用jquery的post方法把this.id(被單擊按鈕的id),發送到“/cmd”這個路徑下,這時,我們python代碼的第二個路由起作用了,接收到了網頁上被單擊按鈕的id,并打印出了“按下了按鈕: XXX”
當然,在這里寫幾個if語句判斷,就可以按照實際的需求做一些實際的控制了,嗯,比如調用wiringpi2 for python控制樹莓派的GPIO。
關于使用Python簡單的實現樹莓派的WEB控制的相關內容就給大家介紹這么多,希望對大家有所幫助!