peewee 事物 回滚

peewee 事物 回滚

#!/usr/bin/env python
# coding=utf-8
from peewee import *


db = MySQLDatabase(host='123.57.229.66', user='root', passwd='password', database='czj', charset='utf8')

class tb_users(Model):
    id = PrimaryKeyField()  # 主键
    mobile = CharField(unique=True, max_length=64, null=False)  # 注册手机号/openid
    password = CharField(max_length=32)  # 密码
    truename = CharField(max_length=32)  # 真实姓名/nickname

    class Meta:
        database = db

#
def one():
    try:
        with db.atomic():
            tb_users.create(mobile='120', password='120', truename='120')
            raise 'haha'
        print 'Success'
    except IntegrityError:
        print 'Failure: %s is already in use.' % username

#
@db.atomic()
def create_user():
    tb_users.create(mobile='120', password='120', truename='120')
    raise 'haha'

def two():
    create_user()


#
def three():
    db.set_autocommit(False)
    db.begin()
    try:
        tb_users.create(mobile='120', password='120', truename='120')
        raise 'haha'
    except:
        db.rollback()
        raise
    else:
        try:
            db.commit()
        except:
            db.rollback()
            raise
    finally:
        db.set_autocommit(True)

#
def four():
    db.set_autocommit(False)
    db.begin()
    tb_users.create(mobile='120', password='120', truename='120')
    db.rollback()
    db.commit()
    db.set_autocommit(True)

实例1,2是使用 peewee封装的db.atomic()原子性,3,4是利用关闭自动提交和手动回滚来保证事物的原子性;

 

posted @ 2017-10-10 15:08  aaron_agu  阅读(663)  评论(0编辑  收藏  举报