Python全棧 項目(HTTPServer、PiP使用)

 

pip是Python官方推薦的包管理工具    屬於python的一部分
 
 
       pip的使用 
 
pip的安裝
            sudo apt-get install python-pip
            sudo apt-get install python3-pip
 
安裝包
            pip3  install   package
 
升級
            pip3  install  --upgrade  package
 
查看python包清單
            pip3 list
 
卸載
            pip3 uninstall  package
 
查找軟件包
            pip3 search  package
 
顯示軟件包信息
            pip3 show  package
 
生成軟件環境文件
            pip3  freeze  >  requirements.txt
 
根據環境文件安裝第三方包
            pip3  install  -r  requirements.txt
 
 
from gevent import  monkey
           monkey.patch_all()
           功能 : 在socket導入以前使用後,用來修改套接字的阻塞行爲
 
基於協程併發服務器模型:
        
import gevent # 在socket導入以前使用 from gevent import monkey monkey.patch_all() from socket import * from time import ctime def server(port): s = socket() s.bind(('0.0.0.0',port)) s.listen(5) while True: c,addr = s.accept() print("Connect from",addr) gevent.spawn(handler,c) #處理客戶端請求 def handler(c): while True: data = c.recv(1024).decode() if not data: break print("Receive:",data) c.send(ctime().encode()) c.close() if __name__ == "__main__": server(8888)
 
 
            HTTPServer
 
前端  前臺  客戶端  用戶端
      功能 :
            1. 和用戶進行交互,獲取用戶請求
            2. 和後端進行通訊,整理用戶請求給後端
            3. 接受後端數據內容,展示給用戶
 
      要求:
            1. 良好的用戶體驗
            2. 較全面的交互能力
            3. 必要的前端優化
            4. 良好的跨平臺型
 
後端  後臺   服務端
      功能:
            1. 接受前端請求
            2. 進行邏輯處理和運算
            3. 和磁盤交互 (文件處理,數據庫處理)
            4. 進行數據整理,更好的向前端返回結果
 
      要求:
            1. 更好的併發性
            2. 更快速的處理速度
            3. 更好的健壯性
            4. 可維護和可擴展
            5. 數據的安全
 
HTTPServer + Frame 版本
 
    httpserver 功能 : 
            1. 接受HTTP請求 (socket通訊)
            2. 解析http請求 
               *  請求類型  GET,POST
               *  請求內容  
            3. 將具體的請求整理後給 web Frame
            4. 接受後端應用返回的數據內容
            5. 將數據組織爲HTTP response的格式發給客戶端
 
 
 
    什麼是框架?
               礦建即開發模板,經過根據框架規則填寫內容便可完成快速開發工做
   Frame 功能:
            1. 接收httpserver發送的request請求
            2. 進行邏輯處理或者數據整合
            3. 將結果發送給httpserver
                * 若是可以處理則返回結果和數據
                * 不能處理返回緣由
 
      結構 :
 
HTTPServer --- static目錄 
           --- HttpServer.py
   --- WebFrame.py
           --- setting.py
   --- views.py
 
 
m = __import__(module)
            功能 : 導入一個模塊
            參數:要導入的模塊
            返回值:模塊對象
 
getattr(obj,attr)
            功能:獲取一個對象的屬性
            參數: obj   對象
                       attr  屬性
            返回值: 返回屬性值
 
__call__() 魔法方法
            做用 : 讓實例對象能夠像函數同樣被調用執行
 
class CallTest(object): def __call__(self,a,b): print("This is call test") print("a =",a,"b =",b) test = CallTest() test(1,2)
 
 
HTTPServer完整代碼:
 
Server:

#coding=utf-8

'''
module: HTTPServer.py
name : Paris
time : 2018-8-28
功能 :httpserver部分
modules: 
    Python3.5 、socket、sys
    threading、re、setting
'''
from socket import  *
import sys 
from threading import Thread
import re
from setting import * 

#處理http請求類
class HTTPServer(object):
    def __init__(self,application):
        self.sockfd = socket()
        self.sockfd.setsockopt\
        (SOL_SOCKET,SO_REUSEADDR,1)
        #獲取模塊接口
        self.application = application

    def bind(self,host,port):
        self.host = host
        self.port = port 
        self.sockfd.bind((self.host,self.port))
    #啓動服務器
    def serve_forever(self):
        self.sockfd.listen(10)
        print("Listen the port %d..."%self.port)
        while True:
            connfd,addr = self.sockfd.accept()
            print("Connect from",addr)
            handle_client = Thread\
            (target = self.client_handler,\
                args = (connfd,))
            handle_client.setDaemon(True)
            handle_client.start()

    def client_handler(self,connfd):
        #接收瀏覽器request
        request = connfd.recv(4096)
        #能夠分析請求頭和請求體
        request_lines = request.splitlines()
        #獲取請求行
        request_line = request_lines[0].decode('utf-8')
        
        #獲取請求方法和請求內容
        pattern = r'(?P<METHOD>[A-Z]+)\s+(?P<PATH_INFO>/\S*)'
        try:
            env = re.match(pattern,request_line).groupdict()
        except:
            response_headlers =  "HTTP/1.1 500 SERVER ERROR\r\n"
            response_headlers += "\r\n"
            response_body = "server error"
            response = response_headlers + response_body
            connfd.send(response.encode())

        # method,filename = \
        # re.findall(r'^([A-Z]+)\s+(/\S*)', request_line)[0]

        #將解析內容合成字典給web frame使用
        # env = {'METHOD':method,'PATH_INFO':filename}
        # print(env)

        #將env給Frame處理,獲得返回內容
        response = self.application(env)

        #發送給客戶端
        if response:
            connfd.send(response.encode())
            connfd.close()


if __name__ == "__main__":
    #將要使用的模塊導入進來
    sys.path.insert(1,MODULE_PATH)
    m = __import__(MODULE)
    application = getattr(m,APP)

    httpd = HTTPServer(application)
    httpd.bind(HOST,PORT)
    httpd.serve_forever()

 

setting:

# setting.py

#httpserver配置文件
HOST = '0.0.0.0'
PORT = 8000

#設置要使用的模塊和應用
MODULE_PATH = "."  #設置Frame模塊路徑
MODULE = 'WebFrame'  #設置模塊名稱
APP = 'app'  #使用的應用

 


WebFrame:

#coding=utf-8 
from views import *
'''
WebFrame.py
WebFrame 框架
用於處理server解析請求
'''


#設置靜態文件夾路徑
STATIC_DIR = "./static"

#應用
class Application(object):
    def __init__(self,urls):
        self.urls = urls

    def __call__(self,env):
        method = env.get("METHOD",'GET')
        path = env.get("PATH_INFO",'/') #請求內容

        if method == 'GET':
            if path == '/' or path[-5:] == '.html':
                response = self.get_html(path)
            else:
                response = self.get_data(path)
        elif method == 'POST':
            pass

        return response

    def get_html(self,path):
        if path == '/':
            get_file = STATIC_DIR + "/index.html"
        else:
            get_file = STATIC_DIR + path
        try:
            fd = open(get_file)
        except IOError :
            #沒有找到請求網頁
            responseHeaders = "HTTP/1.1 404 not found\r\n"
            responseHeaders += '\r\n'
            response_body = "Sorry,the page not found"
        else:
            responseHeaders = "HTTP/1.1 200 OK\r\n"
            responseHeaders += '\r\n'
            response_body = fd.read()
        finally:
            response = responseHeaders + response_body
            return response

    def get_data(self,path):
        for url,handler in self.urls:
            if path == url:
                response_headers = "HTTP/1.1 200 OK\r\n"
                response_headers += '\r\n'
                response_body = handler()
                return response_headers + response_body 

        response_headers = "HTTP/1.1 404 not found\r\n"
        response_headers += '\r\n'
        response_body = "Sorry ,not found the data" 
        return response_headers + response_body

urls = [
    ('/time',show_time),
    ('/hello',say_hello),
    ('/bye',say_bye),
]

app = Application(urls)

 



views:
 

# views.py # 具體處理模塊
import time

def show_time():
    return time.ctime()

def say_hello():
    return "hello world"

def say_bye():
    return "Good Bye"

 

 

 
python 的 httpserver模塊
            python2 BaseHTTPServer
            python3 http.server
示例:
     
try:
    from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
except ImportError:
    from http.server import BaseHTTPRequestHandler,HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print(self.headers) #請求頭
        print(self.path)  #請求內容
        fd = open('test.html','rb')
        content = fd.read()
        #組織response
        self.send_response(200)
        self.send_header('Content-Type','text/html')
        self.end_headers()
        self.wfile.write(content)

    def do_POST(self): 
        pass


address = ('0.0.0.0',8080)
#生成httpserver對象
httpd = HTTPServer(address,RequestHandler)
httpd.serve_forever() #啓動服務器
相關文章
相關標籤/搜索