一、web框架本質
1.基于socket,自己處理請求
#!/usr/bin/env python3#coding:utf8import socketdef handle_request(client): #接收請求 buf = client.recv(1024) print(buf) #返回信息 client.send(bytes('<h1>welcome liuyao webserver</h1>','utf8'))def main(): #創建sock對象 sock = socket.socket() #監聽80端口 sock.bind(('localhost',8000)) #最大連接數 sock.listen(5) print('welcome nginx') #循環 while True: #等待用戶的連接,默認accept阻塞當有請求的時候往下執行 connection,address = sock.accept() #把連接交給handle_request函數 handle_request(connection) #關閉連接 connection.close()if __name__ == '__main__': main() 2.基于wsgi
WSGI,全稱 Web Server Gateway Interface,或者 Python Web Server Gateway Interface ,是為 Python 語言定義的 Web 服務器和 Web 應用程序或框架之間的一種簡單而通用的接口。自從 WSGI 被開發出來以后,許多其它語言中也出現了類似接口。
WSGI 的官方定義是,the Python Web Server Gateway Interface。從名字就可以看出來,這東西是一個Gateway,也就是網關。網關的作用就是在協議之間進行轉換。
WSGI 是作為 Web 服務器與 Web 應用程序或應用框架之間的一種低級別的接口,以提升可移植 Web 應用開發的共同點。WSGI 是基于現存的 CGI 標準而設計的。
很多框架都自帶了 WSGI server ,比如 Flask,webpy,Django、CherryPy等等。當然性能都不好,自帶的 web server 更多的是測試用途,發布時則使用生產環境的 WSGI server或者是聯合 nginx 做 uwsgi 。
python標準庫提供的獨立WSGI服務器稱為wsgiref。
#!/usr/bin/env python#coding:utf-8#導入wsgi模塊from wsgiref.simple_server import make_serverdef RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [bytes("welcome webserver".encode('utf8'))]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever() #接收請求 #預處理請求(封裝了很多http請求的東西) 請求過來后就執行RunServer這個函數。
原理圖:
當用戶發送請求,socket將請求交給函數處理,之后再返回給用戶。
二、自定義web框架
python標準庫提供的wsgiref模塊開發一個自己的Web框架
之前的使用wsgiref只能訪問一個url
下面這個可以根據你訪問的不同url請求進行處理并且返回給用戶
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef RunServer(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) #根據url的不同,返回不同的字符串 #1 獲取URL[URL從哪里獲取?當請求過來之后執行RunServer, #wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這里可以通過斷點來查看它都封裝了什么數據 if request_url == '/login': return [bytes("welcome login",'utf8')] elif request_url == '/reg': return [bytes("welcome reg",'utf8')] else: return [bytes('<h1>404! no found</h1>','utf8')]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever() 當然 以上雖然根據不同url來進行處理,但是如果大量url的話,那么代碼寫起來就很繁瑣。
所以使用下面方法進行處理
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef index(): return [bytes('<h1>index</h1>','utf8')]def login(): return [bytes('<h1>login</h1>','utf8')]def reg(): return [bytes('<h1>reg</h1>','utf8')]def layout(): return [bytes('<h1>layout</h1>','utf8')]#定義一個列表 把url和上面的函數做一個對應urllist = [ ('/index',index), ('/login',login), ('/reg',reg), ('/layout',layout),]def RunServer(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) #根據url的不同,返回不同的字符串 #1 獲取URL[URL從哪里獲取?當請求過來之后執行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這里可以通過斷點來查看它都封裝了什么數據 #循環這個列表 找到你打開的url 返回url對應的函數 for url in urllist: if request_url == url[0]: return url[1]() else: #url_list列表里都沒有返回404 return [bytes('<h1>404 not found</h1>','utf8')] if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever() 三、模板引擎
對應上面的操作 都是根據用戶訪問的url返回給用戶一個字符串的 比如return xxx
案例:
首先寫一個index.html頁面
內容:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>index</title></head><body><h1>welcome index</h1></body></html>
login.html頁面
內容:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>login</title></head><body> <h1>welcome login</h1> <form> user:<input type="text"/> pass:<input type="password"/> <button type="button">login in</button> </form></body></html>
python代碼:
#!/usr/bin/env python #coding:utf-8from wsgiref.simple_server import make_serverdef index(): #把index頁面讀進來返回給用戶 indexfile = open('index.html','r+').read() return [bytes(indexfile,'utf8')]def login(): loginfile = open('login.html','r+').read() return [bytes(loginfile,'utf8')]urllist = [ ('/login',login), ('/index',index),]def RunServer(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) #根據url的不同,返回不同的字符串 #1 獲取URL[URL從哪里獲取?當請求過來之后執行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這里可以通過斷點來查看它都封裝了什么數據 for url in urllist: #如果用戶請求的url和咱們定義的rul匹配 if request_url == url[0]: #執行 return url[1]() else: #url_list列表里都沒有返回404 return [bytes('<h1>404 not found</h1>','utf8')]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever() 但是以上內容只能返回給靜態內容,不能返回動態內容
那么如何返回動態內容呢
自定義一套特殊的語法,進行替換
使用開源工具jinja2,遵循其指定語法
index.html 遵循jinja語法進行替換、循環、判斷
先展示大概效果,具體jinja2會在下章django筆記來進行詳細說明
index.html頁面
內容:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <!--general replace--> <h1>{{ name }}</h1> <h1>{{ age }}</h1> <h1>{{ time }}</h1> <!--for circular replace--> <ul> {% for item in user_list %} <li>{{ item }}</li> {% endfor %} </ul> <!--if else judge--> {% if num == 1 %} <h1>num == 1</h1> {% else %} <h1>num == 2</h1> {% endif %}</body></html> python代碼:
#!/usr/bin/env python#-*- coding:utf-8 -*-import time #導入wsgi模塊from wsgiref.simple_server import make_server#導入jinja模塊from jinja2 import Templatedef index(): #打開index.html data = open('index.html').read() #使用jinja2渲染 template = Template(data) result = template.render( name = 'yaoyao', age = '18', time = str(time.time()), user_list = ['linux','python','bootstarp'], num = 1 ) #同樣是替換為什么用jinja,因為他不僅僅是文本的他還支持if判斷 & for循環 操作 #這里需要注意因為默認是的unicode的編碼所以設置為utf-8 return [bytes(result,'utf8')]urllist = [ ('/index',index),]def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) #根據url的不同,返回不同的字符串 #1 獲取URL[URL從哪里獲取?當請求過來之后執行RunServer, # wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print(request_url) #2 根據URL做不同的相應 #循環這個列表 for url in urllist: #如果用戶請求的url和咱們定義的rul匹配 if request_url == url[0]: print (url) return url[1]() else: #urllist列表里都沒有返回404 return [bytes('<h1>404 not found</h1>','utf8')]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever() 四、MVC和MTV
1.MVC
全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設計典范,用一種業務邏輯、數據、界面顯示分離的方法組織代碼,將業務邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業務邏輯。MVC被獨特的發展起來用于映射傳統的輸入、處理和輸出功能在一個邏輯的圖形化用戶界面的結構中。
將路由規則放入urls.py
操作urls的放入controller里的func函數
將數據庫操作黨風model里的db.py里
將html頁面等放入views里
原理圖:
2.MTV
Models 處理DB操作
Templates html模板
Views 處理函數請求
原理圖:
以上就是本文的全部內容,希望對大家的學習有所幫助。
























