python tornado解析项目核心原理
同学们要跑下图代码,需要创建数据库和下图数据库对应的位置。
该下图代码是从tornado项目中连接数据库的代码,一共3个部分,这就是tornado的核心,掌握了下述原理,应付工作完全可以了。
不懂得直接留言问我。
from functools import wraps
import threading
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String, Integer, func
from sqlalchemy.ext.declarative import declarative_base
# 第一步:连接mysql的准备工作
thread_local = threading.local()
DB_CONF = {
'host': 'localhost',
'port': 3306,
'database': 'test_20191125',
'user': 'root',
'passwd': 'mysql',
'pool_size': 500
}
def transactional(func):
"""
service中的函数装饰器,用来开启事务和提交事务以及遇到错误时的事务回滚
:param func: 需要被装饰的函数
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
closeable = False
is_commit = True
if not hasattr(thread_local, 'session'):
print('start new transaction')
thread_local.session = DBUtil.session()
closeable = True
try:
return func(*args, **kwargs)
except Exception as e:
is_commit = False
print('%s', e)
raise
finally:
if closeable:
print('close transaction, is_commit=%s', str(is_commit))
if is_commit:
thread_local.session.commit()
else:
thread_local.session.rollback()
thread_local.session.close()
del thread_local.session
return wrapper
def synchronized(func):
func.__lock__ = threading.Lock()
def lock_func(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return lock_func
class BaseService:
"""
*Service的基类,单例模式
"""
_instance = None
@synchronized
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(BaseService, cls).__new__(cls)
return cls._instance
def __getattr__(self, item):
if item == 'session':
return thread_local.session
class DBUtil:
db_config = 'mysql+mysqlconnector://' \
+ DB_CONF['user'] + ':'\
+ DB_CONF['passwd'] + '@'\
+ DB_CONF['host'] + ':'\
+ str(DB_CONF['port']) + '/'\
+ DB_CONF['database']\
+ '?charset=utf8'
engine = create_engine(db_config, encoding='utf-8', convert_unicode=True, pool_size=DB_CONF['pool_size'],
pool_pre_ping=True)
DBSession = sessionmaker(bind=engine, autocommit=False, autoflush=False)
@staticmethod
def session():
return DBUtil.DBSession()
@staticmethod
def conn():
return DBUtil.engine.connect()
# 第二步: 数据库表模型
Base = declarative_base()
class TceVariableMapper(Base):
__tablename__ = 'tce_variable_mapper'
variable_id = Column(Integer, primary_key=True, autoincrement=True)
software_id = Column(Integer)
product_name = Column(String)
variable_name = Column(String)
variable_code = Column(String)
variable_type = Column(Integer)
input_limit = Column(String)
multiple_limit = Column(Integer, default=1)
unit = Column(String)
num = Column(Integer)
version_id = Column(Integer)
comment = Column(String)
state = Column(Integer, default=1)
update_time = Column(server_default=func.now(), onupdate=func.now())
class HH(BaseService):
"""
第三步: 连接数据库,输出结果
"""
@transactional
def func(self):
software_client_mapper = {}
client_software_list = self.session.query(TceVariableMapper) \
.join().filter(TceVariableMapper.variable_id > 300).all()
for client_software in client_software_list:
software_client_mapper[client_software.variable_id] = client_software.product_name
print(software_client_mapper)
if __name__ == '__main__':
hah = HH()
hah.func()
打印结果
{512: ‘Web应用防火墙(WAF)’, 513: ‘Web应用防火墙(WAF)’}