def main():
session = make_session()
with transaction.manager:
old_friends = session.query(OldFriend).all()
for old in old_friends:
username = old.user
friend_username = old.friend
user_id = session.query(User.id).filter(User.username == username).first()[0]
try:
friend_id = session.query(User.id).filter(User.username == friend_username).first()[0]
except:
print "friend was missing"
continue
new_friend = Friend(user_id, friend_id)
session.add(new_friend)
#transaction.commit()
python类manager()的实例源码
def add_result_config():
session = make_session()
parser = argparse.ArgumentParser()
parser.add_argument("league", type=int, help="league id")
parser.add_argument("match", type=int, help="match id")
args = parser.parse_args()
results = results_config
with transaction.manager:
for team in results:
for player in team['players']:
result_string = "%s,%s" % (team["position"], player["kills"])
hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == player['name']).first()
if not hero_id:
print "Name wrong"
return
session.add(Result(args.league, hero_id.id, args.match, result_string,
time.time(), 1, 1))
transaction.commit()
return
def add_result():
session = make_session()
parser = argparse.ArgumentParser()
parser.add_argument("league", type=int, help="league id")
parser.add_argument("match", type=int, help="match")
parser.add_argument("player", type=str, help="player name")
parser.add_argument("position", type=int, help="team position")
parser.add_argument("kills", type=int, help="player kills")
args = parser.parse_args()
with transaction.manager:
result_string = "%s,%s" % (args.position, args.kills)
hero_id = session.query(Hero).filter(Hero.league == args.league).filter(Hero.name == args.player).first()
if not hero_id:
print "Name wrong"
return
session.add(Result(args.league, hero_id.id, args.match, result_string,
time.time(), 1, 1))
transaction.commit()
return
def main():
"""
Dont want to delete account as soon as indicated. makes battlecupos and stuff awkward.
so delete it at the end of the day.
:return:
"""
session = make_session()
with transaction.manager:
delete_accounts = session.query(User.username).filter(User.to_delete == True).all()
for username in delete_accounts:
username = username[0]
# loop over leagues and delete from them
#session.query(TeamHero).filter(TeamHero.user == username).delete()
# any others?
session.query()
delete(delete_accounts)
transaction.commit()
def main():
session = make_session()
parser = argparse.ArgumentParser()
parser.add_argument("league", type=int, help="league id")
args = parser.parse_args()
league = session.query(League).filter(League.id == args.league).first()
with transaction.manager:
print "Updating hero points"
update_hero_points(session, league)
transaction.commit()
with transaction.manager:
print "Updating league points"
update_league_points(session, league)
transaction.commit()
with transaction.manager:
print "Updating user rankings"
update_user_rankings(session, league)
transaction.commit()
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
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('pylistener.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
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
)
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
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('turingtweets.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
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
)
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
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('{{cookiecutter.project_name}}.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
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
)
def setUp(self):
"""Defines useful variables and initializes database.
After this, following variables will be available-
1. config: Application configuration
2. engine: DB engine
3. session: DB session instance
4. test_app: Test WSGI app
"""
settings = self.get_settings()
app = services.main({}, **settings)
self.test_app = webtest.TestApp(app=app)
self.config = testing.setUp(settings=settings)
self.engine = models.get_engine(settings)
session_factory = models.get_session_factory(self.engine)
self.session = models.get_tm_session(
session_factory,
transaction.manager
)
self.__init_database()
def __init_database(self):
"""Initialize the database models.
Define a method called `init_db` to initialize
any database instance. This method will automatically
be called at `setUp`.
Caution: If `init_db` is defined, a `clean_db` method
should also be defined which will be called at
`tearDown`.
"""
meta.Base.metadata.create_all(self.engine)
try:
__init_db = self.__getattribute__('init_db')
if callable(__init_db):
with transaction.manager:
__init_db()
except AttributeError:
pass
def tearDown(self):
"""Calls `pyramid.testing.tearDown` and `transaction.abort`.
Prior to calling these methods if any `clean_db` method is
defined, it will be called. Do database clean ups there.
"""
try:
__clean_db = self.__getattribute__('clean_db')
if callable(__clean_db):
with transaction.manager:
__clean_db()
except AttributeError:
pass
testing.tearDown()
transaction.abort()
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 = get_engine(settings)
Base.metadata.create_all(engine)
session_factory = get_session_factory(engine)
with transaction.manager:
dbsession = get_tm_session(session_factory, transaction.manager)
model = MyModel(name='one', value=1)
dbsession.add(model)
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
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('peecp.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
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
)
def setUp(self):
self.config = testing.setUp(settings={
'sqlalchemy.url': 'sqlite:///:memory:'
})
self.config.include('.models')
settings = self.config.get_settings()
from .models import (
get_engine,
get_session_factory,
get_tm_session,
)
self.engine = get_engine(settings)
session_factory = get_session_factory(self.engine)
self.session = get_tm_session(session_factory, transaction.manager)
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
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('PyZAPI.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')
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
)
def setUp(self):
self.config = testing.setUp(settings={
'sqlalchemy.url': 'sqlite:///:memory:'
})
self.config.include('.models')
settings = self.config.get_settings()
from .models import (
get_engine,
get_session_factory,
get_tm_session,
)
self.engine = get_engine(settings)
session_factory = get_session_factory(self.engine)
self.session = get_tm_session(session_factory, transaction.manager)
def data_root(): # type: borgcube.core.models.DataRoot
"""
Return a `DataRoot` instance.
"""
try:
root = _db_local.db.root
except AttributeError:
_db_local.db = db()
root = _db_local.db.root
try:
return root.data_root
except AttributeError:
with transaction.manager as txn:
txn.note('Initialized new data root.')
log.info('Initializing new data root.')
from borgcube.core.models import DataRoot
root.data_root = DataRoot()
return root.data_root
def remote_create(self, command_line):
try:
self.callx('create', command_line)
except CalledProcessError as cpe:
if cpe.returncode == 1:
log.debug('remote create finished (warning)')
with transaction.manager as txn:
self.job.borg_warning = True
txn.note('Set borg warning flag on job %s' % self.job.id)
else:
raise
else:
log.debug('remote create finished (success)')
finally:
transaction.begin()
self.job.update_state(BackupJob.State.client_in_progress, BackupJob.State.client_done)
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 = get_engine(settings)
Base.metadata.create_all(engine)
session_factory = get_session_factory(engine)
with transaction.manager:
dbsession = get_tm_session(session_factory, transaction.manager)
# model = MyModel(name='one', value=1)
# dbsession.add(model)
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, keep_session=True)
return dbsession
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('peter_sslers.models')``.
"""
settings = config.get_settings()
# use pyramid_tm to hook the transaction lifecycle to the request
config.include('pyramid_tm')
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
)
def ensure_transactionless(msg=None, transaction_manager=transaction.manager):
"""Make sure the current thread doesn't already have db transaction in process.
:param transaction_manager: TransactionManager to check. Defaults to thread local transaction manager.
"""
txn = transaction_manager._txn
if txn:
if not msg:
msg = "Dangling transction open in transaction.manager. You should not start new one."
transaction_thread = getattr(transaction.manager, "begin_thread", None)
logger.fatal("Transaction state management error. Trying to start TX in thread %s. TX started in thread %s", threading.current_thread(), transaction_thread)
# Destroy the transaction, so if this was a temporary failure in long running process, we don't lock the process up for the good
txn.abort()
raise TransactionAlreadyInProcess(msg)
def main(argv: t.List[str]=sys.argv):
"""Create initial tables for the database specified on the configuration file.
:param argv: Command line arguments, second one needs to be the uri to a configuration file.
:raises sys.SystemExit:
"""
if len(argv) < 2:
usage_message(argv)
config_uri = get_config_uri(argv)
request = init_websauna(config_uri)
with transaction.manager:
engine = request.dbsession.get_bind()
# Always enable UUID extension for PSQL
# TODO: Convenience for now, because we assume UUIDs, but make this somehow configurable
engine.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
Base.metadata.create_all(engine)
def test_facebook_first_login(web_server, browser, dbsession):
"""Login an user."""
b = browser
b.visit(web_server)
b.click_link_by_text("Sign in")
assert b.is_element_visible_by_css("#login-form")
b.find_by_css(".btn-login-facebook").click()
do_facebook_login_if_facebook_didnt_log_us_already(browser)
assert b.is_element_present_by_css("#msg-you-are-logged-in")
# See that we got somewhat sane data
with transaction.manager:
assert dbsession.query(User).count() == 1
u = dbsession.query(User).get(1)
assert u.first_login
assert u.email == os.environ["FACEBOOK_USER"]
assert u.is_admin() # First user becomes admin
assert u.activated_at
b.find_by_css("#nav-logout").click()
def test_facebook_login_disabled_user(web_server, browser, dbsession, init):
"""Logged in user which is not enabled should give an error.."""
with transaction.manager:
u = create_user(dbsession, init.config.registry, email=os.environ["FACEBOOK_USER"])
u.enabled = False
b = browser
b.visit(web_server)
b.click_link_by_text("Sign in")
assert b.is_element_visible_by_css("#login-form")
b.find_by_css(".btn-login-facebook").click()
do_facebook_login_if_facebook_didnt_log_us_already(browser)
assert b.is_element_present_by_css("#msg-cannot-login-social-media-user")