本文整理汇总了Python中transaction.manager方法的典型用法代码示例。如果您正苦于以下问题:Python transaction.manager方法的具体用法?Python transaction.manager怎么用?Python transaction.manager使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类transaction
的用法示例。
在下文中一共展示了transaction.manager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
#model = MyModel(name='one', value=1)
#DBSession.add(model)
admin = User()
admin.name = 'admin'
admin.password = 'admin'
admin.email = 'admin@localhost'
DBSession.add(admin)
示例2: __exit__
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def __exit__(self, exc_type, exc_value, tb):
try:
active = self.active
manager = zope_transaction.manager
final = manager.get()
if active is final:
if exc_value is None:
manager.commit()
else:
manager.abort()
else:
raise AssertionError('something wrong: the real final transaction {!r} '
'is not the transaction {!r} that has been managed'
.format(final, active))
except:
manager.abort()
raise
finally:
self.active = None
示例3: get_tm_session
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def get_tm_session(session_factory, transaction_manager):
"""
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be committed or aborted
depending on whether an exception is raised.
- When using scripts you should wrap the session in a manager yourself.
For example::
import transaction
engine = get_engine(settings)
session_factory = get_session_factory(engine)
with transaction.manager:
dbsession = get_tm_session(session_factory, transaction.manager)
"""
dbsession = session_factory()
zope.sqlalchemy.register(dbsession, transaction_manager=transaction_manager)
return dbsession
示例4: _company_creation
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def _company_creation(
company_name, schema_name, email, timezone, locale, tarif
):
with transaction.manager:
schema_name = create_company_schema(schema_name, locale)
company = DBSession.query(Company).first()
company.name = company_name
company.email = email
settings = {
'timezone': timezone,
'locale': locale,
}
if tarif:
tarif = get_tarif_by_code(tarif)
settings.update({
'tarif_code': tarif[0],
'tarif_limit': tarif[3],
})
company.settings = settings
DBSession.add(company)
示例5: _add_notification
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def _add_notification(descr, resource_id):
with transaction.manager:
resource = Resource.get(resource_id)
if not resource:
log.error(
u'Can\'t create notification for resource #%s, its not exists'
% resource_id
)
return
notification = Notification(
descr=descr,
notification_resource=resource,
resource=Resource(NotificationsResource, resource.maintainer)
)
for subscriber in resource.subscribers:
subscriber.notifications.append(notification)
log.info(u'Create notification for resource #%s' % resource_id)
示例6: main
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
with transaction.manager:
for cia in DBSession.query(CIA).all():
cia.icon_s = base64.b64encode(zlib.decompress(base64.b64decode(cia.icon_s)))
cia.icon_l = base64.b64encode(zlib.decompress(base64.b64decode(cia.icon_l)))
DBSession.query(CIA).filter_by(id=cia.id).update(dict(icon_s=cia.icon_s,icon_l=cia.icon_l))
with transaction.manager:
for cia in DBSession.query(CIA).all():
m = re.search('(.*)#(.*)', cia.url)
if m:
cia.url = m.group(1)
cia.path = m.group(2)
示例7: newlunch
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def newlunch(request):
form = Form(request, schema=LunchSchema())
if not form.validate:
raise exc.HTTPBadRequest
l = Lunch(
submitter=request.POST.get('submitter', 'nobody'),
food=request.POST.get('food', 'nothing'),
)
with transaction.manager:
DBSession.add(l)
raise exc.HTTPSeeOther('/')
示例8: setUp
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def setUp(self):
self.config = testing.setUp()
from sqlalchemy import create_engine
engine = create_engine('sqlite://')
from .models import (
Base,
MyModel,
)
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
model = MyModel(name='one', value=55)
DBSession.add(model)
示例9: main
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def main(argv=sys.argv):
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
options = parse_vars(argv[2:])
setup_logging(config_uri)
settings = get_appsettings(config_uri, options=options)
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
with transaction.manager:
model = MyModel(name='one', value=1)
DBSession.add(model)
示例10: create_user
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def create_user(DBSession, user, password):
from gengine.app.model import (
AuthUser,
Subject,
AuthRole,
AuthRolePermission,
SubjectType,
t_auth_roles_permissions
)
with transaction.manager:
subjecttype_user = DBSession.query(SubjectType).filter_by(name="User").first()
if not subjecttype_user:
subjecttype_user = SubjectType(name="User")
DBSession.add(subjecttype_user)
existing = DBSession.query(AuthUser).filter_by(email=user).first()
DBSession.flush()
if not existing:
user1 = Subject(lat=10, lng=50, timezone="Europe/Berlin", subjecttype_id=subjecttype_user.id)
DBSession.add(user1)
DBSession.flush()
auth_user = AuthUser(subject=user1, email=user, password=password, active=True)
DBSession.add(auth_user)
auth_role = get_or_create_role(DBSession=DBSession, name="Global Admin")
for perm in yield_all_perms():
if not exists_by_expr(t_auth_roles_permissions, and_(
t_auth_roles_permissions.c.auth_role_id == auth_role.id,
t_auth_roles_permissions.c.name == perm[0]
)):
DBSession.add(AuthRolePermission(role=auth_role, name=perm[0]))
auth_user.roles.append(auth_role)
DBSession.add(auth_user)
DBSession.flush()
示例11: __enter__
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def __enter__(self):
if self.active is not None:
raise RuntimeError('nested transactions are not allowed')
active = self.active = zope_transaction.manager.begin()
return active
示例12: add_to_db
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def add_to_db(engine):
'''Add some basic test data.'''
meta = sqlalchemy.MetaData()
meta.reflect(engine)
# Some initial data in a handy form.
module_file = Path(inspect.getfile(sys.modules[__name__]))
with open(str(module_file.parent / 'test_data.json')) as f:
data = json.load(f)
with transaction.manager:
for dataset in data['models']:
model = getattr(models, dataset[0])
opts = None
if len(dataset) > 2:
opts = dataset[2]
for item in dataset[1]:
set_item(model, item_transform(item), opts)
# Set the current value of the associated sequence to the maximum
# id we added.
try:
id_col_name = model.__pyramid_jsonapi__['id_col_name']
except AttributeError:
id_col_name = sqlalchemy.inspect(model).primary_key[0].name
seq_text = meta.tables[model.__tablename__].columns[id_col_name].server_default.arg.text
seq_name = re.match(r"^nextval\('(\w+)'::", seq_text).group(1)
max_id = DBSession.query(func.max(getattr(model, id_col_name))).one()[0]
DBSession.execute("select setval('{}', {})".format(seq_name, max_id))
for assoc_data in data.get('associations',[]):
table = getattr(models, assoc_data[0])
for assoc in assoc_data[1]:
rows = DBSession.query(table).filter_by(**assoc).all()
if not rows:
DBSession.execute(table.insert(), assoc)
示例13: includeme
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('{{ cookiecutter.repo_name }}.models')``.
"""
settings = config.get_settings()
settings["tm.manager_hook"] = "pyramid_tm.explicit_manager"
# use pyramid_tm to hook the transaction lifecycle to the request
config.include("pyramid_tm")
# use pyramid_retry to retry a request when transient exceptions occur
# config.include("pyramid_retry")
session_factory = get_session_factory(get_engine(settings))
config.registry["dbsession_factory"] = session_factory
# make request.dbsession available for use in Pyramid
config.add_request_method(
# r.tm is the transaction manager used by pyramid_tm
lambda r: get_tm_session(session_factory, r.tm),
"dbsession",
reify=True,
)
示例14: transactional
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def transactional(task):
@wraps(task)
def _task(*args, **kwargs):
with transaction.manager:
task(*args, **kwargs)
return _task
示例15: _initTestingDB
# 需要导入模块: import transaction [as 别名]
# 或者: from transaction import manager [as 别名]
def _initTestingDB():
from sqlalchemy import create_engine
from .models import (
DBSession,
Page,
Base
)
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
DBSession.configure(bind=engine)
with transaction.manager:
model = Page(title='FrontPage', body='This is the front page')
DBSession.add(model)
return DBSession