本文整理汇总了Python中transaction.doom函数的典型用法代码示例。如果您正苦于以下问题:Python doom函数的具体用法?Python doom怎么用?Python doom使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了doom函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
raise Exception(
"this script will assign new reference numbers while moving, "
"most certainly you don't want that to happen..."
)
app = setup_app()
parser = setup_option_parser()
parser.add_option("-n", dest="dry_run", action="store_true", default=False)
(options, args) = parser.parse_args()
print SEPARATOR
print SEPARATOR
print "Date: {}".format(datetime.now().isoformat())
setup_plone(app, options)
if options.dry_run:
transaction.doom()
print "DRY-RUN"
rename_repositories(options)
print "Done."
print SEPARATOR
print SEPARATOR
开发者ID:4teamwork,项目名称:opengever.maintenance,代码行数:26,代码来源:01_rename_repository_folders.py
示例2: create_model
def create_model(self, form):
"""
Create model from form.
:param form:
Form instance
"""
try:
with self.session.begin_nested():
model = self.model()
form.populate_obj(model)
self.session.add(model)
self._on_model_change(form, model, True)
self.session.flush()
except Exception as ex:
if not self.handle_view_exception(ex):
flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
log.exception('Failed to create record.')
transaction.doom()
return False
else:
self.after_model_change(form, model, True)
return model
开发者ID:pombredanne,项目名称:pyramid-admin,代码行数:26,代码来源:view.py
示例3: update_model
def update_model(self, form, model):
"""
Update model from form.
:param form:
Form instance
:param model:
Model instance
"""
try:
with self.session.begin_nested():
form.populate_obj(model)
self._on_model_change(form, model, False)
except Exception as ex:
if not self.handle_view_exception(ex):
flash(gettext('Failed to update record. %(error)s', error=str(ex)), 'error')
log.exception('Failed to update record.')
transaction.doom()
return False
else:
self.after_model_change(form, model, False)
return True
开发者ID:pombredanne,项目名称:pyramid-admin,代码行数:26,代码来源:view.py
示例4: action_delete
def action_delete(self, ids):
try:
query = get_query_for_ids(self.get_query(), self.model, ids)
if self.fast_mass_delete:
count = query.delete(synchronize_session=False)
else:
count = 0
for m in query.all():
if self.delete_model(m):
count += 1
self.session.flush()
flash(ngettext('Record was successfully deleted.',
'%(count)s records were successfully deleted.',
count,
count=count))
except Exception as ex:
if not self.handle_view_exception(ex):
raise
transaction.doom()
flash(gettext('Failed to delete records. %(error)s', error=str(ex)), 'error')
开发者ID:pombredanne,项目名称:pyramid-admin,代码行数:26,代码来源:view.py
示例5: main
def main():
app = setup_app()
parser = setup_option_parser()
parser.add_option("-n", dest="dry_run", action="store_true", default=False)
parser.add_option("-p", dest="profile",
help="profile that contains the repository excel file.")
options, args = parser.parse_args()
if not options.profile:
logger.error("the profile (-p) argument is required.")
return
if ":" not in options.profile:
logger.error("invalid profile id: '{}', missing ':'"
.format(options.profile))
return
if options.dry_run:
logger.warn('transaction doomed because we are in dry-mode.')
transaction.doom()
plone = setup_plone(app, options)
RetentionPeriodFixer(plone, options).run()
if options.dry_run:
logger.warn('skipping commit because we are in dry-mode.')
else:
transaction.commit()
logger.info('done.')
开发者ID:4teamwork,项目名称:opengever.maintenance,代码行数:27,代码来源:fix_retention_period.py
示例6: put
def put(self, host_id=None, *a, **kw):
h = DBSession.query(Host).filter_by(id=host_id).first()
if not h:
raise HTTPNotFound
errors = _h.get_validation_errors()
h.user = request.identity['user']
h.group = _h.get_group_by_name(kw.get('group_name', None))
h.address = unicode(kw['address'].strip())
h.online_status = DBSession.query(Status)\
.filter_by(label='Offline').first()
res = self._get_geoip_data(h.address)
if not res:
errors['host_address'] = "The host '%s' could not be " + \
"identified via GeoIP. Please " + \
"ensure the hostname resolves" % h.address
if errors:
transaction.doom()
return dict(errors=errors, host=h)
h.city = unicode(res.get('city', None))
h.region_name = unicode(res.get('region_name', None))
h.longitude = res.get('longitude', None)
h.latitude = res.get('latitude', None)
h.country_name = unicode(res.get('country_name', None))
h.country_code = unicode(res.get('country_code', None))
h.country_code3 = unicode(res.get('country_code3', None))
h.postal_code = res.get('postal_code', None)
flash(_("%s updated successfully!" % kw['address']), 'info')
redirect(url('/dashboard'))
开发者ID:jness,项目名称:dmirr,代码行数:31,代码来源:host.py
示例7: handleCut
def handleCut(self, action):
if not len(self.selectedItems):
self.status = self.cutNoItemsMessage
return
items = []
append = items.append
for obj in self.selectedItems:
mover = IObjectMover(obj)
__name__ = api.getName(obj)
if not mover.moveable():
m = {"name": __name__}
if name:
m["name"] = __name__
self.status = _(
"Object '${name}' (${name}) cannot be moved",
mapping=m)
else:
self.status = _("Object '${name}' cannot be moved",
mapping=m)
transaction.doom()
return
append(api.joinPath(api.getPath(self.context), __name__))
self.status = self.cutItemsSelected
# store the requested operation in the principal annotations:
self.clipboard.clearContents()
self.clipboard.addItems('cut', items)
开发者ID:jean,项目名称:z3c.contents,代码行数:28,代码来源:browser.py
示例8: preview_wikipage_view
def preview_wikipage_view(context, request, WikiPage=WikiPage):
version_num = int(request.params['version_num'])
repo = find_repo(context)
for version in repo.history(context.docid):
if version.version_num == version_num:
break
else:
raise NotFound("No such version: %d" % version_num)
page = WikiPage()
page.__parent__ = context.__parent__
page.revert(version)
is_front_page = (context.__name__ == 'front_page')
if is_front_page:
community = find_interface(context, ICommunity)
page_title = '%s Community Wiki Page' % community.title
else:
page_title = page.title
profiles = find_profiles(context)
author = profiles[version.user]
# Extra paranoia, probably not strictly necessary. I just want to make
# extra special sure that the temp WikiPage object we create above
# doesn't accidentally get attached to the persistent object graph.
transaction.doom()
return {
'date': format_local_date(version.archive_time),
'author': author.title,
'title': page_title,
'body': page.cook(request),
}
开发者ID:reebalazs,项目名称:karl,代码行数:34,代码来源:wiki.py
示例9: reindex_cataloged
def reindex_cataloged(self, commit_interval=100, idxs=None, start=0,
end=-1, query=None, doom=True):
"""Reindex all cataloged content in Solr."""
query = query or {}
for key, value in self.request.form.items():
if key in ['UID', 'path', 'created', 'modified', 'portal_type',
'object_provides', 'sort_on', 'sort_order']:
query[key] = value
if 'sort_on' not in query:
query['sort_on'] = 'path'
catalog = getToolByName(self.context, 'portal_catalog')
items = catalog.unrestrictedSearchResults(**query)
try:
start = int(start)
end = int(end)
commit_interval = int(commit_interval)
except ValueError:
start = 0
end = -1
commit_interval = 100
processed = 0
real = timer()
lap = timer()
cpu = timer(clock)
if doom:
transaction.doom()
zodb_conn = self.context._p_jar
def commit():
conn = self.manager.connection
conn.commit(extract_after_commit=False)
zodb_conn.cacheGC()
self.log(
'Intermediate commit (%d items processed, last batch in %s)',
processed, lap.next())
cpi = checkpoint_iterator(commit, interval=commit_interval)
self.log('Reindexing Solr...')
site = getSite()
for item in items[start:end]:
path = item.getPath()
obj = site.unrestrictedTraverse(path, None)
if obj is None:
logger.warning("Object at path %s doesn't exist", path)
continue
handler = getMultiAdapter((obj, self.manager), ISolrIndexHandler)
handler.add(idxs)
processed += 1
cpi.next()
commit()
self.log('Solr index rebuilt.')
self.log(
'Processed %d items in %s (%s cpu time).',
processed, real.next(), cpu.next())
开发者ID:4teamwork,项目名称:ftw.solr,代码行数:60,代码来源:maintenance.py
示例10: saveNew
def saveNew( self, ** kw ):
item_code = kw.get( 'item_code', '' ).strip()
item = DBAItem.get_by_code( item_code )
if item:
flash( "%s already in the system!" )
redirect( "/%s/index?item_code=%s" % ( self.url, item_code ) )
else:
try:
file_dir = os.path.join( config.get( 'public_dir' ), 'images/dba' )
image = kw.get( 'image' )
new_filename = '%s_%s' % ( item_code, datetime.now().strftime( "%Y%m%d%H%M%S" ) )
save_file = os.path.join( file_dir, '%s%s' % ( new_filename, '.jpg' ) )
with open( save_file, 'wb' ) as f:
f.write( image.file.read() )
obj = self.dbObj()
obj.item_code = item_code
obj.category_id = kw.get( 'category_id' ).strip()
obj.type_id = kw.get( 'type_id' ).strip()
obj.flatted_size = kw.get( 'flatted_size' ).strip()
obj.image = new_filename
DBSession.add( obj )
except:
transaction.doom()
flash( "The service is not avaiable now.", "warn" )
redirect( "/%s/add" % self.url )
else:
flash( "Save the new DBA item successfully!" )
redirect( "/%s/index?item_code=%s" % ( self.url, item_code ) )
开发者ID:LamCiuLoeng,项目名称:internal,代码行数:28,代码来源:master.py
示例11: save
def save(self, **kw):
try:
save_items = []
itemIDs = kw.get('itemIDs').split('|')
reHeader = ReceiveItemHeader()
reHeader.no = 'REC%s' % dt.now().strftime('%Y%m%d')
reHeader.remark = kw.get('remark', '')
reHeader.warehouseID = kw.get('warehouseID')
reHeader.issuedBy = request.identity["user"]
reHeader.lastModifyBy = request.identity["user"]
reHeader.createTime = kw.get('receivedDate', dt.now())
for itemID in itemIDs:
_r = ReceiveItem()
_r.qty = int(kw.get('qty-%s' % itemID))
_r.internalPO = kw.get('internalPO-%s' % itemID)
_r.header = reHeader
_r.itemID = itemID
_r.warehouseID = int(kw.get('warehouseID'))
_r.issuedBy = request.identity["user"]
_r.lastModifyBy = request.identity["user"]
_r.createTime = reHeader.createTime
save_items.append(_r)
DBSession.add_all(save_items)
DBSession.flush()
reHeader.no = '%s%05d' % (reHeader.no, reHeader.id)
except:
transaction.doom()
traceback.print_exc()
flash("The service is not avaiable now!", "warn")
else:
flash("Confirmed successfully!")
redirect("/receive/view?recid=%s" % reHeader.id)
开发者ID:LamCiuLoeng,项目名称:gap,代码行数:33,代码来源:receive.py
示例12: put
def put(self, product_label=None, *a, **kw):
p = DBSession.query(Product).filter_by(label=product_label).first()
project = p.project
_project_label = project.label
if not p:
raise HTTPNotFound
if not project:
raise HTTPNotFound
_h.protect_obj_modify(project)
_h.protect_obj_modify(p.project)
errors = _h.get_validation_errors()
if kw.get('label', None) != p.label:
_existing_p = _h.get_product_by_name(kw.get('label', None))
if _existing_p:
errors['label'] = "%s already exists!" % kw.get('label', None)
p.label = unicode(re.sub(' ', '_', kw['label']).lower())
p.display_name = unicode(kw['display_name'])
p.desc = kw['desc']
p.project = project
if errors:
transaction.doom()
return dict(project=p.project, errors=errors, product=p)
transaction.commit()
flash(_("%s updated successfully!" % kw['display_name']), 'info')
redirect(url("/project/%s/edit#products" % _project_label))
开发者ID:jness,项目名称:dmirr,代码行数:32,代码来源:product.py
示例13: post
def post(self, *a, **kw):
errors = _h.get_validation_errors()
group = _h.get_group_by_name(kw.get('group_name', None))
protocol = _h.get_protocol_by_name(kw.get('sync_protocol', None))
all_protocols = DBSession.query(SyncProtocol).all()
if not group:
errors['group'] = 'Group does not exist!'
if not protocol:
errors['sync_protocol'] = 'Sync Protocol does not exist!'
p = Project()
p.label = unicode(re.sub(' ', '_', kw['label']).lower())
_label = p.label
p.display_name = unicode(kw.get('display_name', None))
p.desc = kw.get('desc', None)
p.url = unicode(kw.get('url', None))
p.user = request.identity['user']
p.sync_base_path = unicode(kw.get('sync_base_path', None))
p.sync_flags = unicode(kw.get('sync_flags', None))
p.group = group
p.sync_protocol = protocol
if len(errors) > 0:
transaction.doom()
return dict(page="project", errors=errors, project=p,
all_protocols=all_protocols)
DBSession.add(p)
transaction.commit()
flash(_("%s created successfully!" % kw['display_name']), 'info')
redirect(url('/project/%s/edit' % _label))
开发者ID:jness,项目名称:dmirr,代码行数:31,代码来源:project.py
示例14: get_delete
def get_delete(self, *args, **kw):
'''This is the code that creates a confirm_delete page
The delete operation will be simulated to be able to display all related
objects that would be deleted too.
'''
if not self.allow_delete:
abort(403)
pks = self.provider.get_primary_fields(self.model)
kw, d = {}, {}
for i, pk in enumerate(pks):
kw[pk] = args[i]
for i, arg in enumerate(args):
d[pks[i]] = arg
obj = self.provider.delete(self.model, d)
deps = u'<dl>'
for k, g in groupby(sorted(o for o in DBSession.deleted if o != obj), lambda x: type(x)):
deps += u'<dt>' + unicode(k.__name__) + u's' + u'</dt>'
deps += u'<dd>' + u', '.join(sorted(unicode(o) for o in g)) + u'</dd>'
deps += u'</dl>'
transaction.doom()
#obj = self.edit_filler.__provider__.get_obj(self.model, params=kw, fields=self.edit_filler.__fields__)
pklist = u'/'.join(map(lambda x: unicode(getattr(obj, x)), pks))
return dict(obj=obj,
model=self.model.__name__,
deps=deps,
pk_count=len(pks), pklist=pklist)
开发者ID:Ayutac,项目名称:SAUCE,代码行数:31,代码来源:base.py
示例15: save_order
def save_order(self, **kw):
try:
kw = extract_inline_list('fabric_set',** kw)
if kw.has_key('fabric_set'):
for i in kw['fabric_set']:
for k,v in i.iteritems():
if type(v)==list or type(v)==tuple:
v = ','.join(map(str, v))
if not kw.has_key(k):
kw[k] = v
elif k=='fabric_ids':
kw[k] = '%s,%s' % (kw[k], v)
else:
kw[k] = '%s|%s' % (kw[k], v)
del kw['fabric_set']
else:
kw['fabric_ids'] = None
kw['composition_percents'] = None
kw['composition_ids'] = None
if kw.get('id', None):
order = OrchestraOrder.get(kw['id'])
order.update(**kw)
flash("Order update success!")
else:
if kw.has_key('id'): del kw['id']
order = OrchestraOrder.create(**kw)
flash("Order create success!")
order.attachment = None
DBSession.flush()
except Exception, e:
log.exception(str(e))
transaction.doom()
flash("Error occor on the server side!", 'warn')
redirect('/orchestra/%s/index' % kw['team'])
开发者ID:LamCiuLoeng,项目名称:internal,代码行数:34,代码来源:orchestra.py
示例16: save_vendor
def save_vendor(self, **kw):
try:
kw = extract_inline_list('vendor_obj','shipto_set','user_set','billto_set',** kw)
if kw.has_key('_create'):
vendor = CabelasVendor.create(**kw['vendor_obj'])
DBSession.flush()
for type in ['shipto', 'billto']:
type_set = '%s_set' % type
if kw.has_key(type_set):
for i in kw[type_set]:
vendor_info = CabelasVendorInfo.create(vendor_id=vendor.id, type=type, **i)
else:
vendor = CabelasVendor.get(kw['vendor_obj']['id'])
vendor_info_map = {}
for i in vendor.vendor_infos:
vendor_info_map.update({str(i.id):i})
vendor.update(**kw['vendor_obj'])
for type in ['shipto', 'billto']:
type_set = '%s_set' % type
if kw.has_key(type_set):
for i in kw[type_set]:
if i.has_key('id'):
vendor_info = CabelasVendorInfo.get(i['id'])
vendor_info.update(**i)
del vendor_info_map[str(vendor_info.id)]
else:
vendor_info = CabelasVendorInfo.create(vendor_id=vendor.id, type=type, **i)
for k,v in vendor_info_map.iteritems():
v.disable()
flash("The vendor saved successful!")
except Exception, e:
flash("Error occor on the server side!", 'warn')
log.exception(str(e))
transaction.doom()
开发者ID:LamCiuLoeng,项目名称:internal,代码行数:34,代码来源:cabelas.py
示例17: saveSO
def saveSO(self, **kw):
#DBSession.begin(subtransactions = True)
try:
_config = {"so":"soNo",
"soRemark":"soRemark", }
for k, v in kw.items():
key = k.split("_")[0]
ids = k.split("_")[1:]
rs = DBSession.query(TAGItem).filter(TAGItem.id.in_([int(id) for id in ids if id])).all()
if rs:
for r in rs:
oldValue = getattr(r, _config[key])
setattr(r, _config[key], str(v.strip()))
r.soDate = dt.now()
his = TAGHistory(item = r)
actionType = "modify" if oldValue else "Add"
his.actionKind = actionType
his.actionContent = "Change <%s> from [%s] to [%s]." % (key, oldValue, str(v.strip()))
his.actionUser = request.identity["user"]
DBSession.add(his)
DBSession.flush()
return {"flag":"OK"}
except:
#DBSession.rollback()
transaction.doom()
traceback.print_exc()
return {"flag":"error"}
开发者ID:LamCiuLoeng,项目名称:internal,代码行数:27,代码来源:tag.py
示例18: put
def put(self, site_label=None, *a, **kw):
errors = _h.get_validation_errors()
s = DBSession.query(Site).filter_by(label=site_label).first()
group = _h.get_group_by_name(kw.get('group_name', None))
all_p = DBSession.query(Project).all()
_h.protect_obj(s)
if not s:
raise HTTPNotFound
if not group:
errors['group'] = 'Group does not exist!'
s.label = unicode(re.sub(' ', '_', kw['label']).lower())
s.display_name = unicode(kw.get('display_name', None))
s.desc = kw.get('desc', None)
s.url = unicode(kw.get('url', None))
s.contact_name = unicode(kw.get('contact_name', None))
s.contact_email = unicode(kw.get('contact_email', None))
s.sync_base_path = unicode(kw.get('sync_base_path', None))
s.user = request.identity['user']
s.group = group
if len(errors) > 0:
all_projects = [x for x in all_p if x not in s.projects]
all_hosts = [x for x in request.identity['user'].hosts \
if x not in s.hosts]
transaction.doom()
return dict(page='site', errors=errors, site=s,
all_projects=all_projects, all_hosts=all_hosts)
transaction.commit()
flash(_("%s updated successfully!" % kw['display_name']), 'info')
redirect(url('/site/%s/edit' % kw['label']))
开发者ID:jness,项目名称:dmirr,代码行数:33,代码来源:site.py
示例19: assign_project
def assign_project(self, site_id, *a, **kw):
errors = _h.get_validation_errors()
s = DBSession.query(Site).filter_by(id=site_id).first()
p = DBSession.query(Project).filter_by(id=kw.get('project_id', None))\
.first()
all_p = DBSession.query(Project).all()
_h.protect_obj(s)
_h.protect_obj(p)
if not s:
raise HTTPNotFound
if not p:
raise HTTPNotFound
all_projects = [x for x in all_p if x not in s.projects]
if errors:
transaction.doom()
return dict(errors=errors, site=s, all_projects=all_projects)
_s_label = s.label
s.projects.append(p)
if kw.get('sync_path', None):
self._add_site_sync_path(s.id, p.id, kw['sync_path'])
else:
transaction.doom()
flash(_('Site sync path required for each project.'), 'warning')
redirect(url("/site/%s/edit#mirrored_projects" % _s_label))
transaction.commit()
redirect(url("/site/%s/edit#projects" % _s_label))
开发者ID:jness,项目名称:dmirr,代码行数:33,代码来源:site.py
示例20: connection_raw_execute
def connection_raw_execute(self, connection, raw_cursor,
statement, params):
"""See `TimeoutTracer`"""
# Only perform timeout handling on LaunchpadDatabase
# connections.
if not isinstance(connection._database, LaunchpadDatabase):
return
# If we are outside of a request, don't do timeout adjustment.
try:
if self.get_remaining_time() is None:
return
super(LaunchpadTimeoutTracer, self).connection_raw_execute(
connection, raw_cursor, statement, params)
except (RequestExpired, TimeoutError):
# XXX: This code does not belong here - see bug=636804.
# Robert Collins 20100913.
OpStats.stats['timeouts'] += 1
# XXX bug=636801 Robert Colins 20100914 This is duplicated
# from the statement tracer, because the tracers are not
# arranged in a stack rather a queue: the done-code in the
# statement tracer never runs.
action = getattr(connection, '_lp_statement_action', None)
if action is not None:
# action may be None if the tracer was installed after
# the statement was submitted.
action.finish()
info = sys.exc_info()
transaction.doom()
try:
raise info[0], info[1], info[2]
finally:
info = None
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:32,代码来源:adapter.py
注:本文中的transaction.doom函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论