web框架-MVC和MTV

1、MVC
簡單地說,就是對文件夾的一個分類,職責的一個劃分。
Model: 數據庫操作
View: 模板文件
Controller: 業務邏輯的處理
將整個項目,劃分成上述三部分,這樣整個項目的結構看上去就非常清晰。
下面舉一個非常簡單的例子:
在這裏插入圖片描述
上面的圖片就是例子項目的所有構成,s3.py文件是主程序,來看看s3.py幹了什麼,

from wsgiref.simple_server import make_server

from Controller import account

url_l = {
    '/date': account.handle_date,
    '/index': account.handle_index,
}

def runServer(environ, start_response):
    # environ 客戶端發來的所有數據
    # start_response 封裝要返回給用戶的數據,相應頭狀態
    start_response('200 OK', [('Content-Type', 'text/html')])
    # current_url = environ['PATH_INFO']
    # if current_url == "/index":
    #     return ['<h1>Hello, index!</h1>'.encode('utf-8')]
    # elif current_url == "/date":
    #     return ['<h1>Hello, date!</h1>'.encode('utf-8')]
    # else:
    #     return ['<h1>404</h1>'.encode('utf-8')]
    current_url = None
    current_url = environ['PATH_INFO'] # 獲取url的後綴
    if current_url in url_l:
        func = url_l[current_url] # 根據後綴,調用不同的業務邏輯
        if func:
            return func()
        else:
            return ['<h1>404</h1>'.encode('utf-8')]
    else:
        return ['<h1>404</h1>'.encode('utf-8')]

if __name__ == "__main__":
    httpd = make_server('', 8000, runServer)
    print('Serving HTTP on port 8000...')
    httpd.serve_forever()

s3.py是所有web socket服務端最基本最簡單的實現方式,啓動服務,監聽客戶端有沒有請求。業務邏輯的實現通過導入Controller文件夾下的account.py文件,使得整個主函數看上去很簡潔。下面來看看account幹了什麼,

import time

def handle_date():
    v = str(time.time())
    f = open("/home/xue/python_learn/day18/View/index.html", mode="rb")
    data = f.read()
    f.close()
    data = data.replace(b'@uuuuu', v.encode('utf-8')) # 這裏我們就可以去數據庫裏提取數據,進行操作
    return [data, ]

def handle_index():
    return ['<h1>Hello, index!</h1>'.encode('utf-8')]

account.py只有兩個函數,分別處理網頁客戶端不同url後綴的請求,返回不同的網站,在這裏還可以去調用數據庫,這樣就實現了一個最簡單的MVC框架了。

2、MTV
和MVC類似,只不過文件夾的名字發生了變化。
Model: 數據庫操作
Template: 模板文件
View: 業務處理

發佈了49 篇原創文章 · 獲贊 41 · 訪問量 9350
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章