1. 程式人生 > >2、基於wsgiref模塊DIY一個web框架

2、基於wsgiref模塊DIY一個web框架

func code nag cti get 動態網站 port else inter

一 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()

三 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開始一行行碼代碼了!

2、基於wsgiref模塊DIY一個web框架