目次前端只处置处罚前端自己的逻辑,比如图形展示、笔墨的格式化等,后端也只处置处罚后端自己的业务代码,前端和后援通过某种机制来耦合。 我们通过 M-V-C 的概念来阐明前后端分离的概念。M 指的是 Model-数据模型,V 指的是 View-视图,C 指的是 Controller-控制器。视图可以理解为前端,重要用于对数据的呈现,模型可以理解为后端,重要负责对业务的处置处罚,而控制器重要负责吸收用户的输入并协调视图和模型。M、V、C 三者之间的关系如下: MVC 计划 Python 代码的模拟实现如下: [code]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}")[/code]
然后,通过 MVC 的方法增长控制器并解耦,具体实现如下: [code]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) [/code]上述代码中,我们通过引入 ProductController 类分离了视图和模型,使得视图和模型的耦合关系松开,通过控制器决定 View 的更新和模型的更新,而不是视图直接调用模型或者模型去驱动视图。今后如果须要视图上的逻辑(比如想换一个视图)就可以轻松地完成。 到此这篇关于基于python的前后端分离的模拟实现的文章就介绍到这了,更多相关python前后端分离的模拟内容请搜索脚本之家以前的文章或继承欣赏下面的相关文章盼望大家以后多多支持脚本之家! 来源:https://www.jb51.net/python/3283226ly.htm 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|手机版|小黑屋|梦想之都-俊月星空
( 粤ICP备18056059号 )|网站地图
GMT+8, 2025-7-1 19:07 , Processed in 0.027950 second(s), 20 queries .
Powered by Mxzdjyxk! X3.5
© 2001-2025 Discuz! Team.