基於wsgiref模組DIY一個web框架
一 web框架
Web框架(Web framework)是一種開發框架,用來支援動態網站、網路應用和網路服務的開發。這大多數的web框架提供了一套開發和部署網站的方式,也為web行為提供了一套通用的方法。web框架已經實現了很多功能,開發人員使用框架提供的方法並且完成自己的業務邏輯,就能快速開發web應用了。瀏覽器和伺服器的是基於HTTP協議進行通訊的。也可以說web框架就是在以上十幾行程式碼基礎張擴展出來的,有很多簡單方便使用的方法,大大提高了開發的效率。
二 wsgiref模組
最簡單的Web應用就是先把html用檔案儲存好,用一個現成的HTTP伺服器軟體,接收使用者請求,從檔案中讀取html,返回。如果要動態生成HTML,就需要把上述步驟自己來實現。不過,接受HTTP請求、解析HTTP請求、傳送HTTP響應都是苦力活,如果我們自己來寫這些底層程式碼,還沒開始寫動態HTML呢,就得花個把月去讀HTTP規範。正確的做法是底層程式碼由專門的伺服器軟體實現,我們用Python專注於業務邏輯。因為我們不希望接觸到TCP連線、HTTP原始請求和響應格式,所以,需要一個統一的介面協議來實現這樣的伺服器軟體,讓我們專心用Python編寫Web業務。這個介面就是WSGI:Web Server Gateway Interface。而wsgiref模組就是python基於wsgi協議開發的服務模組。
from wsgiref.simple_server import make_server
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'<h1>Hello, web!</h1>']
httpd = make_server('', 8080, application)
print('Serving HTTP on port 8000...')
# 開始監聽HTTP請求:
httpd.serve_forever()
廣州vi設計http://www.maiqicn.com 辦公資源網站大全 https://www.wode007.com
三 DIY一個web框架
為了做出一個動態網站,我們需要擴充套件功能,比如使用者訪問url的路徑是login時提供一個登入頁面,路徑是index時響應一個首頁面。
3.1 啟動檔案:manage.py
from wsgiref.simple_server import make_server
from views import *
from urls import urlpatterns
def application(environ, start_response):
#print("environ",environ)
start_response('200 OK', [('Content-Type', 'text/html')])
# 獲取當前請求路徑
print("PATH_INFO",environ.get("PATH_INFO"))
path=environ.get("PATH_INFO")
# 分支
func=None
for item in urlpatterns:
if path == item[0]:
func=item[1]
break
if not func:
ret=notFound(environ)
else:
ret=func(environ)
return [ret]
httpd = make_server('', 8080, application)
# 開始監聽HTTP請求:
httpd.serve_forever()
3.2 url控制檔案:urls.py
from views import *
urlpatterns = [
("/login", login),
("/index", home),
]
3.3 檢視檔案:views.py
# 檢視函式
def home(environ):
with open("templates/home.html", "rb") as f:
data = f.read()
return data
def login(environ):
with open("templates/login.html", "rb") as f:
data = f.read()
return data
def notFound(environ):
return b"<h1>404...</h1>"
3.4 模板檔案Templates
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8800" method="post">
使用者名稱 <input type="text" name="user">
密碼 <input type="text" name="pwd">
<input type="submit">
</form>
</body>
</html>
home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>This is index!</h3>
</body>
</html>
到這裡,pyyuan這個包就是一個web框架,當這個框架的基礎上,新增業務功能就很簡單了,比如,我們新增一個檢視時間的頁面,只需要完成兩部即可:
(1) 在urls.py中新增:
("/timer", timer),
(2) 在views.py中新增:
def timer(request):
import datetime
now=datetime.datetime.now().strftime("%Y-%m-%d")
return now.encode()
是不是很簡單,有了web框架,你就不用再從建立socket開始一行行碼程式碼了!