python 三層架構說明


三層架構(3-tier architecture) 通常意義上的三層架構就是將整個業務應用划分為:
表現層(Presentation layer)、業務邏輯層(Business Logic Layer)、數據訪問層(Data access layer)。


區分層次的目的即為了"高內聚低耦合"的思想。
高內聚低耦合,是軟件工程中的概念,是判斷設計好壞的標准,主要是面向對象的設計,主要是看類的內聚性是否高,耦合度是否低。
內聚就是一個模塊內各個元素彼此結合的緊密程度,高內聚就是一個模塊內各個元素彼此結合的緊密程度高。


所謂高內聚是指一個軟件模塊是由相關性很強的代碼組成,只負責一項任務,也就是常說的單一責任原則。
耦合:一個軟件結構內不同模塊之間互連程度的度量(耦合性也叫塊間聯系。指軟件系統結構中各模塊間相互聯系緊密程度的一種度量。
模塊之間聯系越緊密,其耦合性就越強,模塊的獨立性則越差,模塊間耦合的高低取決於模塊間接口的復雜性,調用的方式以及傳遞的信息。) 
對於低耦合,粗淺的理解是:
一個完整的系統,模塊與模塊之間,盡可能的使其獨立存在。
也就是說,讓每個模塊,盡可能的獨立完成某個特定的子功能。
模塊與模塊之間的接口,盡量的少而簡單。
如果某兩個模塊間的關系比較復雜的話,最好首先考慮進一步的模塊划分。
這樣有利於修改和組合。

三層架構,如下圖:


 

1、表現層(UI):通俗講就是展現給用戶的界面,即用戶在使用一個系統的時候他的所見所得。
2、業務邏輯層(BLL):針對具體問題的操作,也可以說是對數據層的操作,對數據業務邏輯處理。
3、數據訪問層(DAL):該層所做事務直接操作數據庫,針對數據的增添、刪除、修改、查找等。

 

示例:

 

 1 #coding:utf8
 2 
 3 from utility.sql_helper import MySqlHelper
 4 
 5 class Admin(object):
 6     def __init__(self):
 7         self.__helper = MySqlHelper()
 8         
 9     def Get_One(self,id):
10         sql = "select * from userinfo where id = %s"
11         params = (id,)
12         return self.__helper.Get_One(sql, params)
13     
14     def CheckValidate(self,username,password):
15         sql = "select * from userinfo where name=%s and password=%s"
16         params = (username,password,)
17         return self.__helper.Get_One(sql, params)
18     
19     
admin.py
 1 #coding:utf8
 2 import MySQLdb
 3 import conf
 4 
 5 
 6 class MySqlHelper(object):
 7     def __init__(self):
 8         self.__conn_dict = conf.conn_dict
 9     def Get_Dict(self,sql,params):
10         conn = MySQLdb.connect(**self.__conn_dict)
11         cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 
12         
13         reCount = cur.execute(sql,params)
14         data = cur.fetchall()   
15 
16         cur.close()
17         conn.close()
18         return data
19        
20     def Get_One(self,sql,params):
21         conn = MySQLdb.connect(**self.__conn_dict)
22         cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) 
23         
24         reCount = cur.execute(sql,params)
25         data = cur.fetchone()  
26 
27         cur.close()
28         conn.close()
29         return data
sql_helper

 

1 #coding:utf8
2 
3 conn_dict = dict(
4     host='127.0.0.1',
5     user='root',
6     passwd='123456',
7     db ='Admin'
8     )
conf.py
 1 #coding:utf8
 2 
 3 from module.admin import Admin
 4 
 5 def main():
 6     user=raw_input('username:')
 7     pwd=raw_input("password:")
 8     admin = Admin()
 9     result = admin.CheckValidate(user, pwd)
10     if not result:
11         print '用戶名或密碼錯誤'
12     else:
13         print '進入后台登錄界面'
14 
15 if __name__== '__main__':
16     main()
index.py

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM