本文整理汇总了Python中transaction.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: queue_msg
def queue_msg(msg, queue=None):
""" Queues a rabbitmq message in the given queue
"""
_mdm = MessagesDataManager()
transaction.get().join(_mdm)
_mdm.add(queue, msg)
示例2: __init__
def __init__(self, wd, db, head, name):
self.wd = wd
self.db = db
self.name = name
self.lock_file = os.path.join(db, 'acidfs.lock')
transaction.get().join(self)
curhead = open(os.path.join(db, 'HEAD')).read().strip()[16:]
if head == curhead:
head = 'HEAD'
if head == 'HEAD':
self.headref = os.path.join(db, 'refs', 'heads', curhead)
else:
self.headref = os.path.join(db, 'refs', 'heads', head)
self.head = head
if os.path.exists(self.headref):
# Existing head, get head revision
self.prev_commit = _check_output(
['git', 'rev-list', '--max-count=1', head], cwd=db).strip()
self.tree = _TreeNode.read(db, self.prev_commit)
else:
# New head, no commits yet
self.tree = _TreeNode(db) # empty tree
self.prev_commit = None
示例3: update_list_mailtos
def update_list_mailtos(context, new_fqdn):
"""
http://www.openplans.org/projects/opencore/lists/opencore-dev/archive/2009/03/1238095821932/forum_view#1240922987323
"""
catalog = getToolByName(context, 'portal_catalog')
lookup_utility = getUtility(IListLookup, context=context)
i = 0; changed = False
for brain in catalog.unrestrictedSearchResults(portal_type=
'Open Mailing List'):
i += 1
try:
ml = brain.getObject()
except AttributeError:
# ignore catalog ghosts
continue
mailto, old_fqdn = ml.mailto.split('@')
if old_fqdn == new_fqdn:
continue
ml.mailto = mailto
lookup_utility.updateList(ml)
changed = True
if changed and i % 400 == 0:
transaction.get().note('Batch commit of mailing list FQDN update')
transaction.commit()
changed = False
transaction.get().note('Final commit of mailing list FQDN update')
transaction.commit()
示例4: create_dangling_ref
def create_dangling_ref(db):
rt = db.open().root()
rt[1] = o1 = P()
transaction.get().note(u"create o1")
transaction.commit()
rt[2] = o2 = P()
transaction.get().note(u"create o2")
transaction.commit()
c = o1.child = P()
transaction.get().note(u"set child on o1")
transaction.commit()
o1.child = P()
transaction.get().note(u"replace child on o1")
transaction.commit()
time.sleep(2)
# The pack should remove the reference to c, because it is no
# longer referenced from o1. But the object still exists and has
# an oid, so a new commit of it won't create a new object.
db.pack()
print(repr(c._p_oid))
o2.child = c
transaction.get().note(u"set child on o2")
transaction.commit()
示例5: calculate
def calculate(self):
"""Move related delivery in 'calculating' state by activity
Activity to update causality state is delayed until all related simulation
movement are reindexed.
This method should be only called by
simulation_movement_causality_interaction_workflow.
"""
delivery = self.getDeliveryValue()
if delivery is not None:
delivery = delivery.getRootDeliveryValue()
tv = getTransactionalVariable()
path = self.getPath()
delivery_path = delivery.getPath()
key = 'SimulationMovement.calculate', delivery_path
try:
tv[key].append(path)
except KeyError:
tv[key] = [path]
def before_commit():
method_id_list = ('immediateReindexObject',
'recursiveImmediateReindexObject')
tag = delivery_path + '_calculate'
delivery.activate(tag=tag).Delivery_calculate(activate_kw=
{'after_path_and_method_id': (tv[key], method_id_list)})
tv[key] = None # disallow further calls to 'calculate'
transaction.get().addBeforeCommitHook(before_commit)
示例6: _bootstrap
def _bootstrap(self):
bt_name = 'erp5_property_sheets'
from Products.ERP5.ERP5Site import ERP5Generator
ERP5Generator.bootstrap(self, bt_name, 'PropertySheetTemplateItem', (
'BaseType',
'BusinessTemplate',
'Folder',
'SimpleItem',
'Version',
'Comment',
# the following ones are required to upgrade an existing site
'Reference',
'BaseCategory',
'SQLIdGenerator',
))
def install():
from ZPublisher.BaseRequest import RequestContainer
from Products.ERP5Type.Globals import get_request
portal = self.getPortalObject()
# BusinessTemplate.install needs a request
template_tool = portal.aq_base.__of__(portal.aq_parent.__of__(
RequestContainer(REQUEST=get_request()))).portal_templates
if template_tool.getInstalledBusinessTemplate(bt_name) is None:
from Products.ERP5.ERP5Site import getBootstrapBusinessTemplateUrl
url = getBootstrapBusinessTemplateUrl(bt_name)
template_tool.download(url).install()
transaction.get().addBeforeCommitHook(unrestricted_apply, (install,))
示例7: view_user
def view_user(context, request):
if request.referrer and 'came_from' not in request.session:
request.session['came_from'] = request.referrer
editable = has_permission(WRITE, context, request)
schema = UserSchema().bind(context=context)
form = deform.Form(schema, buttons=(_('Save changes'),))
if editable and request.method == 'POST':
try:
note = 'Edited user: %s.' % context.fullname
data = form.validate(request.params.items())
context.fullname = data.get('fullname', context.fullname)
context.email = data.get('email', context.email)
if data['password']:
note += ' Changed password.'
context.set_password(data['password'])
if data['userid'] != context.__name__:
folder = context.__parent__
del folder[context.__name__]
folder[data['userid']] = context
redirect_to = request.session.pop(
'came_from', request.application_url)
transaction.get().note(note)
return HTTPFound(redirect_to)
except deform.ValidationFailure, form:
rendered = HTML(form.render())
示例8: handleTraceback
def handleTraceback(object):
context = object.context
entry_url = object.entry_url
if entry_url is None:
return
LOGGER.info("handle traceback [%s]" % entry_url)
try:
cleanup_lock.acquire()
# we don't want to produce any errors here, thus, we'll be nice and die
# silently if an error occurs here
try:
transaction.begin()
# get our logbook view to use the api
logbook = context.unrestrictedTraverse('@@logbook')
# get the generated error url from Products.SiteErrorLog
err_id = urllib.splitvalue(entry_url)[1]
# save error
logbook.save_error(err_id, context=aq_parent(context))
transaction.get().note('collective.logbook traceback [%s]' %
entry_url)
transaction.commit()
finally:
cleanup_lock.release()
# only warning
except Exception, e:
LOGGER.warning("An error occured while handling the traceback")
LOGGER.warning("%s" % e)
LOGGER.exception(e)
示例9: run_plone_migrations
def run_plone_migrations(context):
"""
Runs the migrations that are registered w/ Plone's
portal_migrations tool.
"""
migtool = getToolByName(context, 'portal_migration')
if not migtool.needUpgrading():
return
inst_version = migtool.getInstanceVersion()
if 'svn' in inst_version:
# it's an unreleased version, bump down the version number and
# use forced upgrade
inst_version = inst_version.split()[0]
from Products.CMFPlone.MigrationTool import _upgradePaths
for vfrom, vto in _upgradePaths.items():
if vto[0] == inst_version:
inst_version = vfrom
break
req = context.REQUEST
req.environ['REQUEST_METHOD'] = 'POST'
req.form = {'force_instance_version': inst_version}
req.force_instance_version = inst_version
result = migtool.upgrade(REQUEST=req)
else:
result = migtool.upgrade()
if not migtool.needUpgrading():
transaction.get().note('Plone migrations run')
transaction.commit()
else:
raise RuntimeError, "Plone migrations failed"
示例10: checkNonASCIITransactionMetadata
def checkNonASCIITransactionMetadata(self):
# Verify the database stores and retrieves non-ASCII text
# in transaction metadata.
ugly_string = ''.join(chr(c) for c in range(256))
if not isinstance(ugly_string, bytes):
# Py3
check_string = ugly_string.encode("latin-1")
else:
check_string = ugly_string
db = DB(self._storage)
try:
c1 = db.open()
r1 = c1.root()
r1['alpha'] = 1
transaction.get().setUser(ugly_string)
transaction.commit()
r1['alpha'] = 2
transaction.get().note(ugly_string)
transaction.commit()
info = self._storage.undoInfo()
self.assertEqual(info[0]['description'], check_string)
self.assertEqual(info[1]['user_name'], b'/ ' + check_string)
finally:
db.close()
示例11: checkNonASCIITransactionMetadata
def checkNonASCIITransactionMetadata(self):
# Verify the database stores and retrieves non-ASCII text
# in transaction metadata.
ugly_string = ''.join(chr(c) for c in range(256))
if isinstance(ugly_string, bytes):
# Always text. Use latin 1 because it can decode any arbitrary
# bytes.
ugly_string = ugly_string.decode('latin-1')
# The storage layer is defined to take bytes (implicitly in
# older ZODB releases, explicitly in ZODB 5.something), but historically
# it can accept either text or bytes. However, it always returns bytes
check_string = ugly_string.encode("utf-8")
db = DB(self._storage)
try:
c1 = db.open()
r1 = c1.root()
r1['alpha'] = 1
transaction.get().setUser(ugly_string)
transaction.commit()
r1['alpha'] = 2
transaction.get().note(ugly_string)
transaction.commit()
info = self._storage.undoInfo()
self.assertEqual(info[0]['description'], check_string)
self.assertEqual(info[1]['user_name'], b'/ ' + check_string)
finally:
db.close()
示例12: sql_create_all
def sql_create_all(context):
"""Add all missing SQL tables and indices.
"""
session = Session()
transaction.get().commit()
model.metadata.create_all(session.bind, checkfirst=True)
datamanager.mark_changed(session)
示例13: flush_backend
def flush_backend(self):
"""Take all transactions that are dirty or marked for removal
writes them out / removes them out if possible.
When this is done, it does a zopedb transaction commit, if you're
sharing a zopedb thread with this you'll want to be sure your data
is in a state you're comfortable having commited
"""
# if we can write to the backend
if self.can_write():
dirty_set_copy = self.dirty_transaction_set.copy()
try:
self.__advance_all_dirty_transaction_state_machine(True)
# save, and let all dirty transactions change thier state
# with the knowledge that a save just took place
try:
self.save()
except BoKeepBackendException, e:
# call close, which also triggers
# __set_all_transactions_to_reset_and_advance()
self.close('called close() because save failed ' + \
str(e))
else:
for dirty_trans_id in self.dirty_transaction_set.iterkeys():
self.dirty_transaction_set[dirty_trans_id] = \
BackendDataStateMachine.LAST_ACT_SAVE
self._p_changed = True
transaction.get().commit()
self.__advance_all_dirty_transaction_state_machine()
示例14: test_request_not_closed_when_tm_middleware_active
def test_request_not_closed_when_tm_middleware_active(self):
import transaction
from ZPublisher import WSGIPublisher
environ = self._makeEnviron()
environ['repoze.tm.active'] = 1
start_response = DummyCallable()
_request = DummyRequest()
_request._closed = False
def _close():
_request._closed = True
_request.close = _close
def _request_factory(stdin, environ, response):
return _request
_publish = DummyCallable()
_publish._result = DummyResponse()
app_iter = self._callFUT(environ, start_response, _publish,
_request_factory=_request_factory)
self.assertFalse(_request._closed)
txn = transaction.get()
self.assertTrue(txn in WSGIPublisher._request_closer_for_repoze_tm.requests)
txn.commit()
self.assertTrue(_request._closed)
self.assertFalse(txn in WSGIPublisher._request_closer_for_repoze_tm.requests)
# try again, but this time raise an exception and abort
_request._closed = False
_publish._raise = Exception('oops')
self.assertRaises(Exception, self._callFUT,
environ, start_response, _publish,
_request_factory=_request_factory)
self.assertFalse(_request._closed)
txn = transaction.get()
self.assertTrue(txn in WSGIPublisher._request_closer_for_repoze_tm.requests)
txn.abort()
self.assertFalse(txn in WSGIPublisher._request_closer_for_repoze_tm.requests)
self.assertTrue(_request._closed)
示例15: __call__
def __call__(self, batch=1000, dryrun=False):
""" find all btree-based folder below the context, potentially
migrate them & provide some logging and statistics doing so """
log = self.mklog()
log('migrating btree-based folders from %r:' % self.context)
real = timer() # real time
lap = timer() # real lap time (for intermediate commits)
cpu = timer(clock) # cpu time
processed = 0
def checkPoint():
msg = 'intermediate commit '\
'(%d objects processed, last batch in %s)...'
log(msg % (processed, next(lap)))
trx = get()
trx.note(u'migrated %d btree-folders' % processed)
trx.savepoint()
cpi = checkpointIterator(checkPoint, batch)
for path, obj in findObjects(self.context):
if isinstance(obj, BTreeFolder):
if self.migrate(obj):
processed += 1
next(cpi)
self.postprocess(obj)
checkPoint() # commit last batch
if dryrun:
get().abort() # abort on test-run...
msg = 'processed %d object(s) in %s (%s cpu time).'
msg = msg % (processed, next(real), next(cpu))
log(msg)
logger.info(msg)