Python 三层架构

三层架构(3-tier architecture) 通常意义上的三层架构就是将整个业务应用划分为:
表现层(Presentation layer)、业务逻辑层(Business Logic Layer)、数据访问层(Data access layer)

区分层次的目的即为了"高内聚低耦合"的思想
高内聚低耦合,是软件工程中的概念,是判断设计好坏的标准,主要是面向对象的设计,主要是看类的内聚性是否高,耦合度是否低。

三层架构,如下图:

 

1、表现层(UI):通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。
2、业务逻辑层(BLL):针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
3、数据访问层(DAL):该层所做事务直接操作数据库,针对数据的增添、删除、修改、查找等。

架构示例:

 

conf.py

1 #数据库连接配置文件
2 conn_dict=dict(
3     host='192.168.0.109',
4     user='root',
5     passwd='',
6     db ='TESTDB'
7 )
View Code

mysql_helper.py

 1 import MySQLdb
 2 import conf
 3 
 4 class mysqlhelper(object):
 5     def __init__(self):
 6         self.__conn_dict=conf.conn_dict     #定义一个私有字段__conn_dict,并将数据库字典配置赋值给它,外部无法直接访问
 7     def get_info(self,sql,params):
 8         conn=MySQLdb.connect(**self.__conn_dict)   #使用两个*号可以将字典中的值作为参数传进来
 9         cur=conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) #创建游标
10 
11         reCount=cur.execute(sql,params)
12         data=cur.fetchall()   #获取所有信息
13 
14         cur.close()
15         conn.close()
16         print data
17         return data
18 
19     def get_oneinfo(self, sql, params):
20         conn=MySQLdb.connect(**self.__conn_dict)
21         cur=conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
22         try:
23             cur.execute(sql,params)
24             data=cur.fetchone()  #获取一条信息
25         except:
26             print "出错了",sql,params
27         cur.close()
28         conn.close()
29         return data
30 
31 
32     def insert_info(self,sql,params):
33         conn = MySQLdb.connect(**self.__conn_dict)
34         cur = conn.cursor()
35 
36         cur.execute(sql, params)
37         conn.commit()  #提交插入语句
38         cur.close()
39         conn.close()
View Code

login.py

 1 from utility.mysql_helper import mysqlhelper
 2 
 3 class login(object):
 4     def __init__(self):
 5         self.__helper=mysqlhelper() #login类初始化,自动将mysqlhelper类赋给私有字段__helper
 6     def get_info(self,firstname):
 7         sql = "select * from emploeye where FIRST_NAME= %s"
 8         params = (firstname,)
 9         return self.__helper.get_info(sql,params)
10     def checkvalidate(self,firstname,password):
11         sql = "select * from emploeye where FIRST_NAME=%s and LAST_NAME=%s"
12         params = (firstname, password,)
13         return self.__helper.get_oneinfo(sql,params)
View Code

index.py

 1 from modules.login import login
 2 
 3 def main():
 4     user = raw_input('firstname:')
 5     pwd = raw_input("lastname:")
 6     admin=login()
 7     result=admin.checkvalidate(user,pwd)
 8     if not result:
 9         print '用户名或密码错误'
10     else:
11         print '管理员%s进入后台登录界面' % user
12 
13 if __name__ == '__main__':
14     main()
View Code
我们的征途是星辰大海
原文地址:https://www.cnblogs.com/honey-badger/p/8353124.html