当前位置:   article > 正文

Peewee-笔记,轻量快速的ORM_playhouse.shortcuts.reconnectmixin

playhouse.shortcuts.reconnectmixin

安装

pip install peewee

使用背景:

1.相比于操作pymysql,peewee增删改查更方便

2.对于大数据量存储mysql,peewee可更好的胜任,(如:实例情况,10w条100列的txt文件,peewee在1分钟左右完成导入)

文件结构:

 models.py内容:

  1. import peewee
  2. import traceback
  3. import datetime
  4. from peewee import *
  5. from playhouse.shortcuts import ReconnectMixin
  6. class ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):
  7. pass
  8. try:
  9. db = ReconnectMySQLDatabase('db', host='127.0.0.1', port= 3306, user= 'root', passwd='123456',sql_mode='NO_AUTO_CREATE_USER')
  10. except:
  11. traceback.print_exc()
  12. exit()
  13. class BaseModel(peewee.Model):
  14. """A base model that will use our mysql database"""
  15. class Meta:
  16. database = db
  17. class Test(BaseModel):
  18. rec_id = peewee.AutoField(primary_key=True)
  19. class Meta:
  20. db_table = 'Test'
  21. verbose_name = '测试'
  22. verbose_name_plural = verbose_name

insert.py内容:

  1. import peewee
  2. import pandas as pd
  3. import traceback
  4. import click
  5. from .models import *
  6. try:
  7. db.connect()
  8. except:
  9. traceback.print_exc()
  10. exit()
  11. #判断连接是否终端
  12. if db.is_closed():
  13. print('mysql reconnect')
  14. db = ReconnectMySQLDatabase('db', host='127.0.0.1', port= 3306, user= 'root', passwd='123456',sql_mode='NO_AUTO_CREATE_USER')
  15. db.connect()
  16. “”“操作”“”

事务:

  1. with db.atomic() as txn:
  2. try:
  3. """操作"""
  4. pass
  5. except Exception as e:
  6. txn.rollback()
  7. exit(traceback.print_exc())

判空:

Test.select().where(Test.rec_id== 1).exists()

 查找:

Test.get(rec_id=1).rec_id

 批次新增:

#list为Test表结构相同的字典组成的列表,如[{“rec_id”:1}]
for batch in peewee.chunked(list, 1000):
    Test.insert_many(batch).execute()

 更新:

#dict为Test表结构相同的字典,如{“rec_id”:1}
Test.update(dict).where(Test.rec_id== 1).execute()
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/172745
推荐阅读
相关标签
  

闽ICP备14008679号