基于python的前后端分離的模擬實現(xiàn)
前端只處理前端本身的邏輯,比如圖形展示、文字的格式化等,后端也只處理后端自己的業(yè)務代碼,前端和后盾通過某種機制來耦合。
我們通過 M-V-C 的概念來說明前后端分離的概念。M 指的是 Model-數(shù)據(jù)模型,V 指的是 View-視圖,C 指的是 Controller-控制器。視圖可以理解為前端,主要用于對數(shù)據(jù)的呈現(xiàn),模型可以理解為后端,主要負責對業(yè)務的處理,而控制器主要負責接收用戶的輸入并協(xié)調視圖和模型。M、V、C 三者之間的關系如下:

MVC 設計
Python 代碼的模擬實現(xiàn)如下:
class ProductInfo:
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
class ProductView:
def print_product(self):
product = ProductInfo() # 耦合點
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")- 類 ProductView 表示前端的功能,使用一些 print 語句來打印產(chǎn)品的信息,而類 ProductInfo 代表產(chǎn)品記錄。如果不采用前后端分離的方式,那么可以在 ProductView 中直接調用后端的數(shù)據(jù),產(chǎn)生耦合點。
然后,通過 MVC 的方法增加控制器并解耦,具體實現(xiàn)如下:
class ProductInfo:
def __init__(self):
self.product_name = None
self.id = None
self.price = None
self.manufacturer = None
class ProductView:
"""
Product 的展示
"""
def print_product(self, product):
print(f"Name: {product.product_name}")
print(f"Price: {product.price}")
print(f"Manufacturer: {product.manufacturer}")
class ProductController:
"""
控制器,控制用戶的輸入,選擇合適的 view 輸出
"""
def __init__(self, product, view):
self.product = product
self.product_view = view
def refresh_view(self):
self.product_view.print_product(self.product)
def update_model(self, product_name, price, manufacturer):
self.product.product_name = product_name
self.product.price = price
self.product.manufacturer = manufacturer
# 實際執(zhí)行代碼
if __name__ == '__main__':
controller = ProductController(ProductInfo(), ProductView())
controller.refresh_view()
controller.update_model("new name", 15, "ABC Inc")
controller.product_view.print_product(controller.product)
上述代碼中,我們通過引入 ProductController 類分離了視圖和模型,使得視圖和模型的耦合關系松開,通過控制器決定 View 的更新和模型的更新,而不是視圖直接調用模型或者模型去驅動視圖。今后如果需要視圖上的邏輯(比如想換一個視圖)就可以輕松地完成。
到此這篇關于基于python的前后端分離的模擬實現(xiàn)的文章就介紹到這了,更多相關python前后端分離的模擬內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python數(shù)據(jù)分析入門之教你怎么搭建環(huán)境
本篇文章要有一定的Python基礎,知道列表,字符串,函數(shù)等的用法. 文中有非常詳細的代碼示例,對正在入門python數(shù)據(jù)分析的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
Pytorch中torch.argmax()函數(shù)使用及說明
這篇文章主要介紹了Pytorch中torch.argmax()函數(shù)使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
django實現(xiàn)web接口 python3模擬Post請求方式
今天小編就為大家分享一篇django實現(xiàn)web接口 python3模擬Post請求方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
WINDOWS 同時安裝 python2 python3 后 pip 錯誤的解決方法
這篇文章主要給大家分享的是在WINDOWS下同時安裝 python2 python3 后 pip 錯誤的解決方法,非常的實用,有需要的小伙伴可以參考下2017-03-03

