热点新闻
565. 【自动化测试】基于python的前后端分离的模拟实现
2023-07-20 16:48  浏览:433  搜索引擎搜索“富博农业网”
温馨提示:为防找不到此信息,请务必收藏信息以备急用! 联系我时,请说明是在富博农业网看到的信息,谢谢。
展会发布 展会网站大全 报名观展合作 软文发布

前端只处理前端本身的逻辑,比如图形展示、文字的格式化等,后端也只处理后端自己的业务代码,前端和后盾通过某种机制来耦合。

我们通过 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 的更新和模型的更新,而不是视图直接调用模型或者模型去驱动视图。今后如果需要视图上的逻辑(比如想换一个视图)就可以轻松地完成。
发布人:e8fa****    IP:101.229.41.***     举报/删稿
展会推荐
让朕来说2句
评论
收藏
点赞
转发