Python內置了支持HTTP協議的模塊,咱們能夠用來開發單機版功能較少的Web服務器。Python支持該功能的實現模塊是BaseFTTPServer, 咱們只須要在項目中引入就能夠了:javascript
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
Let’s start with the first basic example. It just return 「Hello World !」 on the web browser.
讓咱們來看第一個基本例子,在瀏覽器上輸出」Hello World 」
example1.pycss
#!/usr/bin/python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer PORT_NUMBER = 8080 #This class will handles any incoming request from #the browser class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # Send the html message self.wfile.write("Hello World !") return try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', PORT_NUMBER), myHandler) print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
執行如下命令運行:html
python example1.pyjava
用你的瀏覽器打開這個地址http://your_ip:8080
瀏覽器上將會顯示」Hello World !」 同時在終端上將會出現兩條日誌信息:python
Started httpserver on port 8080
10.55.98.7 - - [30/Jan/2012 15:40:52] 「GET / HTTP/1.1」 200 -
10.55.98.7 - - [30/Jan/2012 15:40:52] 「GET /favicon.ico HTTP/1.1」 200 -web
讓咱們來嘗試下提供靜態文件的例子,像index.html, style.css, javascript和images:瀏覽器
example2.py服務器
#!/usr/bin/python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer from os import curdir, sep PORT_NUMBER = 8080 #This class will handles any incoming request from #the browser class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): if self.path=="/": self.path="/index_example2.html" try: #Check the file extension required and #set the right mime type sendReply = False if self.path.endswith(".html"): mimetype='text/html' sendReply = True if self.path.endswith(".jpg"): mimetype='image/jpg' sendReply = True if self.path.endswith(".gif"): mimetype='image/gif' sendReply = True if self.path.endswith(".js"): mimetype='application/javascript' sendReply = True if self.path.endswith(".css"): mimetype='text/css' sendReply = True if sendReply == True: #Open the static file requested and send it f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type',mimetype) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', PORT_NUMBER), myHandler) print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
這個新樣例實現功能:app
輸入以下命令運行它:socket
python example2.py
而後用你的瀏覽器打開 http://your_ip:8080
一個首頁會出如今你的瀏覽器上
如今探索下如何從html表格中讀取數據
example3.py
#!/usr/bin/python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer from os import curdir, sep import cgi PORT_NUMBER = 8080 #This class will handles any incoming request from #the browser class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): if self.path=="/": self.path="/index_example3.html" try: #Check the file extension required and #set the right mime type sendReply = False if self.path.endswith(".html"): mimetype='text/html' sendReply = True if self.path.endswith(".jpg"): mimetype='image/jpg' sendReply = True if self.path.endswith(".gif"): mimetype='image/gif' sendReply = True if self.path.endswith(".js"): mimetype='application/javascript' sendReply = True if self.path.endswith(".css"): mimetype='text/css' sendReply = True if sendReply == True: #Open the static file requested and send it f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type',mimetype) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) #Handler for the POST requests def do_POST(self): if self.path=="/send": form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) print "Your name is: %s" % form["your_name"].value self.send_response(200) self.end_headers() self.wfile.write("Thanks %s !" % form["your_name"].value) return try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', PORT_NUMBER), myHandler) print 'Started httpserver on port ' , PORT_NUMBER #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
運行這個例子:
python example3.py
在 「Your name」 標籤旁邊輸入你的名字