This article describes how to use Python to easily implement Raspberry Pi's WEB control. If you need it, you can refer to it to show you the effect. I feel very satisfied. Please continue to read the full text:
Knowledge used: Python Bottle HTML Javascript JQuery Bootstrap AJAX, of course, linux
I'm going, so many ...... Let me start ......
First paste the final source code:
#! /Usr/bin/env python3from bottle import get, post, run, request, template @ get ("/") def index (): return template ("index ") @ post ("/cmd") def cmd (): print ("press the button:" + request. body. read (). decode () return "OK" run (host = "0.0.0.0 ")
That's right. I just want to explain 10 sentences:
1 .#! /Usr/bin/env python3: Tell shell that the file is Python source code, and let bash call python3 to explain the code.
2. from bottle import get, post, run, request, template, the methods and objects I used are imported from the bottle framework.
The following sentence defines two routes, one is "/" and the other is "/cmd". The former is of the get type (decorated with @ get ), the latter is POST type (decorated with @ post)
The first route is very simple, that is, reading the index template (the template is html) and sending it to the client (browser), because the path is "/", that is, for example, the IP address of Raspberry Pi is 192.168.0.10.
Use http: // 192.168.0.10: 8080 to access our "/" route (the default port of the bottle is 8080)
Similarly, the second route path is "/cmd", that is, access http: // 192.168.0.10: 8080/cmd to access the second route.
The last sentence: run (host = "0.0.0.0") is to call the run method of bottle to create an http server so that we can access our interface through a browser.
Below I will explain in detail the functions of these codes:
The role of the first route is to throw the browser an HTML (index. tpl) document to display this interface:
The source code of this file is as follows:
Remote Control Raspberry Pi