基於python的web server有不少,好比:django、web.py、tornado、fastcgi等。通過一番比較我選擇使用tornado,使用tornado的緣由有以下幾個:一、tornado是輕量級的web server,二、異步I/O處理鏈接請求,三、tornado是facebook開源項目之一。因爲個人raspberry pi使用的是raspbian操做系統,而raspbian操做系統源上有python-tornado和python3-tornado二進制包,因此直接使用命令$sudo apt-get install python3-tornado python-tornado完成安裝。完成安裝後使用tornado官方網站上提供的測試代碼來測試web服務器是否好用。測試代碼以下:python
#!/usr/bin/env python3
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self, name):
self.write("Hello, world")
application = tornado.web.Application([
(r"/(.*)", MainHandler),
])
if __name__ == "__main__":
application.listen(9090)
tornado.ioloop.IOLoop.instance().start()web
其中web服務器監聽端口是9090,全部的web請求由MainHandler類進行處理。在MainHandler類中包含一個get()方法,在該方法中向發出請求的web客戶端輸出"Hello,world"字符串。django
在raspberry pi上運行該python腳本,以後經過命令netstat查看當前系統的監聽端口,發現9090端口被監聽。瀏覽器
pi@raspberrypi :~/test$ netstat -ltn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN
服務器
此時,在PC機上使用瀏覽器訪問raspberry pi上的9090端口,就能夠獲得"Hello,world"字符串顯示在瀏覽器頁面中。app