Python httpServer服務器(初級)


使用原生的python開發的web服務器,入門級!

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os   #Python的標准庫中的os模塊包含普遍的操作系統功能  
import re   #引入正則表達式對象  
import urllib   #用於對URL進行編解碼  
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler  #導入HTTP處理相關的模塊  


#自定義處理程序,用於處理HTTP請求  
class TestHTTPHandler(BaseHTTPRequestHandler):
    #處理GET請求  
    def do_GET(self):
        #獲取URL
        print 'URL=',self.path
        #頁面輸出模板字符串  
        templateStr = '''
        <html>   
        <head>   
        <title>QR Link Generator</title>   
        </head>   
        <body>   
        hello Python!
        </body>   
        </html>
        '''

        self.protocal_version = 'HTTP/1.1'  #設置協議版本  
        self.send_response(200) #設置響應狀態碼  
        self.send_header("Welcome", "Contect")  #設置響應頭  
        self.end_headers()
        self.wfile.write(templateStr)   #輸出響應內容  

        #啟動服務函數  
def start_server(port):
        http_server = HTTPServer(('', int(port)), TestHTTPHandler)
        http_server.serve_forever() #設置一直監聽並接收請求  

#os.chdir('static')  #改變工作目錄到 static 目錄  
start_server(8000)  #啟動服務,監聽8000端口

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM