python 多进程,多线程,使用 sqlalchemy 对数据库进行操作

创建引擎 & 获取数据库会话:

使用类的方式,然后在对象方法中去创建数据库引擎(使用单例,确保只创建一个对象,方法里对引擎做判断,确保只创建一个数据库引擎)

# mysql全局基类方法
class MysqlGlobal(object):
__instance = None
__engine = None def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance def gen_engine(self):
if not MysqlGlobal.__engine:
engine = create_engine("mysql+{driver}://{username}:{password}@{server}/{database}?charset={charset}"
.format(driver=MYSQL_DRIVER,
username=MYSQL_USERNAME,
password=MYSQL_PASSWORD,
server=MYSQL_SERVER,
database=DB_NAME,
charset=DB_CHARSET),
pool_size=100,
max_overflow=100,
# pool_recycle=7200,
pool_recycle=2,
echo=False)
engine.execute("SET NAMES {charset};".format(charset=DB_CHARSET))
MysqlGlobal.__engine = engine
return MysqlGlobal.__engine @property
def mysql_session(self):
self.gen_engine()
mysql_db = sessionmaker(bind=MysqlGlobal.__engine)
return mysql_db()

数据表模型类

# 数据库orm映射绑定引擎
MapBase = declarative_base(bind=MysqlGlobal().gen_engine()) class WfCarInfo(MapBase):
__tablename__ = "wf_carinfo"
untreated_status = 0
treated_status = 1 id = Column(Integer, primary_key=True, nullable=True, autoincrement=True)
status = Column(Integer, nullable=True, default=0) # 接入状态,0:待处理,1:已处理
# create_time = Column(DateTime, nullable=True, default=func.now()) # 记录的创建时间
# update_time = Column(DateTime, nullable=True, default=func.now(), onupdate=func.now()) # 记录的更新时间
。。。省略

数据库会话闭包装饰器

包装了数据库会话 session

def mysql_session(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
session = MysqlGlobal().mysql_session
return method(*args, session, **kwargs)
return wrapper

  

装饰器装饰模型类的类方法

这样在外面调用类方法进行数据库操作的时候,就不需要传数据库会话过来(session 参数)

@classmethod
@mysql_session
def query_all(cls, session):
carinfo_obj_list = session.query(cls).all()
info_list = [carinfo_obj.to_dict() for carinfo_obj in carinfo_obj_list]
return info_list @classmethod
@mysql_session
def query_all_by_status(cls, status, session):
carinfo_obj_list = session.query(cls).filter(cls.status == status).all()
info_list = [carinfo_obj.to_dict() for carinfo_obj in carinfo_obj_list]
return info_list @classmethod
@mysql_session
def query_all_by_index(cls, current_index, next_index, session):
carinfo_obj_list = session.query(cls).filter(and_(cls.id > current_index, cls.id <= next_index)).all()
info_list = [carinfo_obj.to_dict() for carinfo_obj in carinfo_obj_list]
return info_list @classmethod
@mysql_session
def insert_one(cls, row, session):
if not row:
return
new_record = cls(**row)
session.add(new_record)
session.commit()
return new_record @classmethod
@mysql_session
def update_status(cls, record_id, status, session):
session.query(cls).filter(cls.recordId == record_id).update({"status": status})
session.commit()
return 1 @classmethod
@mysql_session
def delete_treated_data(cls, session):
# session.query(cls).filter(cls.status == cls.treated_status).delete()
treated_obj_list = session.query(cls).filter(cls.status == cls.treated_status).all()
count = len(treated_obj_list)
[session.delete(treated_obj) for treated_obj in treated_obj_list]
session.commit()
return count

  

附加(数据库初始化)

# 数据库初始化
def init_db_data():
MapBase.metadata.create_all()
logging.info("init mysql_db success")
print("init mysql_db success")

  

end ~

多进程,多线程,使用sqlalchemy 创建引擎(单例模式),闭包装饰器承载数据库会话,装饰模型类的类方法的更多相关文章

  1. Python设计模式 - 创建型 - 单例模式(Singleton) - 十种

    对于很多开发人员来说,单例模式算是比较简单常用.也是最早接触的设计模式了,仔细研究起来单例模式似乎又不像看起来那么简单.我们知道单例模式适用于提供全局唯一访问点,频繁需要创建及销毁对象等场合,的确方便 ...

  2. python函数下篇装饰器和闭包,外加作用域

    装饰器和闭包的基础概念 装饰器是一种设计模式能实现代码重用,经常用于查日志,性能测试,事务处理等,抽离函数大量不必的功能. 装饰器:1.装饰器本身是一个函数,用于装饰其它函数:2.功能:增强被装饰函数 ...

  3. python闭包和装饰器

    本文目录: 1. 闭包的解析和用法 2. 函数式装饰器 3. 类装饰器 一.闭包 闭包是一种函数,从形式上来说是函数内部定义(嵌套)函数,实现函数的扩展.在开发过程中,考虑到兼容性和耦合度问题,如果想 ...

  4. Python之函数的本质、闭包、装饰器

    函数名的本质 函数名本质上就是函数的内存地址. 1.可以赋值给其他变量,被引用 def func(): print('in func') f = func print(f) 2.可以被当作容器类型的元 ...

  5. 闭包&装饰器

    闭包 1.函数引用 def test(): print('--test--') # 调用函数 test() # 引用函数 ret = test print(id(ret)) print(id(test ...

  6. python中对变量的作用域LEGB、闭包、装饰器基本理解

    一.作用域 在Python程序中创建.改变.查找变量名时,都是在一个保存变量名的空间中进行,我们称之为命名空间,也被称之为作用域.python的作用域是静态的,在源代码中变量名被赋值的位置决定了该变量 ...

  7. 21.python中的闭包和装饰器

    python中的闭包从表现形式上定义(解释)为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure). 以下说明主要针对 python ...

  8. Python闭包装饰器笔记

    Python三大器有迭代器,生成器,装饰器,这三个中使用最多,最重要的就是装饰器.本篇将重要从函数嵌套开始讲起,从而引入闭包,装饰器的各种用法等. python中的一切都是一个对象(函数也是) 1.首 ...

  9. python中闭包和装饰器的理解(关于python中闭包和装饰器解释最好的文章)

    转载:http://python.jobbole.com/81683/ 呵呵!作为一名教python的老师,我发现学生们基本上一开始很难搞定python的装饰器,也许因为装饰器确实很难懂.搞定装饰器需 ...

随机推荐

  1. ubuntu18.04安装docker和开通对外2375端口(方便portainer管理)

    date: 2019-08-03   21:39:37 author: headsen chen apt-get install apt-transport-https ca-certificates ...

  2. 贪心:leetcode 870. Advantage Shuffle、134. Gas Station、452. Minimum Number of Arrows to Burst Balloons、316. Remove Duplicate Letters

    870. Advantage Shuffle 思路:A数组的最大值大于B的最大值,就拿这个A跟B比较:如果不大于,就拿最小值跟B比较 A可以改变顺序,但B的顺序不能改变,只能通过容器来获得由大到小的顺 ...

  3. django 实战3 simpleui

    pip3 install django-import-export pip3 install django-simpleui pip3 install mysqlclient python3 mana ...

  4. Nginx之https配置 - 运维笔记 (http->https强转)

    一.Nginx安装(略)安装的时候需要注意加上 --with-http_ssl_module,因为http_ssl_module不属于Nginx的基本模块.Nginx安装方法: # ./configu ...

  5. CGI = MCC + MNC + LAC + CI

    CGI = MCC + MNC + LAC + CI 摘自:http://www.360doc.com/content/19/0801/10/65611272_852334484.shtml CGI是 ...

  6. 123457123457#0#----com.MC.3or1KongLongPT867----前拼后广--3or1恐龙PtGame-mc

    com.MC.3or1KongLongPT867----前拼后广--3or1恐龙PtGame-mc

  7. 函数返回new对象

    #include <iostream> using namespace std; // foo()函数本质上没什么问题,但建议你不要这样写代码 string &foo() { st ...

  8. 【opencv基础-VxWorks】话说图像格式转换-COLOR_YUV2BGR_YUY2

    前言 基于Vxworks的WindRiver获取摄像头图像进行处理,需要先进行转换,对于转换格式博主有点疑问.本文对此作出解释,若有错误,请交流指正. README.md The video came ...

  9. Shell脚本互斥设置

    参考:https://blog.csdn.net/hanjiezz/article/details/79571703 shell脚本为了防止同时执行相同的脚本需要设置互斥锁 简单方法,脚本执行开始生成 ...

  10. [计算机视觉][ARM-Linux开发] Ubuntu14.04安装OpenCV3.2中遇到的问题的解决方案

    2. ubuntu下,opencv3.x安装一直downloading这个包,要看超时信息里的下载路径,把它放到下载路径中,比如我的opencv3.2.0源文件路径为/home/han/softwar ...