前端只处理前端本身的逻辑,比如图形展示、文字的格式化等,后端也只处理后端自己的业务代码,前端和后盾通过某种机制来耦合。
我们通过 m-v-c 的概念来说明前后端分离的概念。m 指的是 model-数据模型,v 指的是 view-视图,c 指的是 controller-控制器。视图可以理解为前端,主要用于对数据的呈现,模型可以理解为后端,主要负责对业务的处理,而控制器主要负责接收用户的输入并协调视图和模型。m、v、c 三者之间的关系如下:
mvc 设计
python 代码的模拟实现如下:
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 语句来打印产品的信息,而类 productinfo 代表产品记录。如果不采用前后端分离的方式,那么可以在 productview 中直接调用后端的数据,产生耦合点。
然后,通过 mvc 的方法增加控制器并解耦,具体实现如下:
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 # 实际执行代码 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的前后端分离的模拟实现的文章就介绍到这了,更多相关python前后端分离的模拟内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论