def get_object_list(self, request): #Store KA exercise content load in UserButton table if request.GET['key']: kusername = get_username(request.GET['key']) if kusername: if Exercise.objects.filter(name=request.GET['name']).count()==1: kexercise = Exercise.objects.get(name=request.GET['name']) with transaction.commit_on_success(): kbook = Books.objects.get(book_name= request.GET['book']) user_data, created = UserData.objects.get_or_create(user=kusername,book=kbook) module = get_module(request.GET['module']) if kexercise and module: with transaction.commit_on_success(): user_module, exist = UserModule.objects.get_or_create(user=kusername, book=kbook,module=module) text = 'User loaded %s exercise' %request.GET['name'] user_button,correct = log_button_action( kusername, kexercise, module, kbook, 'load-ka', text, time.time()*1000, None, request.user_agent.browser.family, request.user_agent.browser.version_string, request.user_agent.os.family, request.user_agent.os.version_string, request.user_agent.device.family, request.META['REMOTE_ADDR'], ) return super(ExerciseResource, self).get_object_list(request)
def delete(self, **options): if "label" in options: label = options.get("label") eltos = self.gdb.get_relationships_by_label( label, include_properties=False ) count = self.gdb.delete_relationships( [relationship_id for relationship_id, r_props, r_label in eltos] ) with transaction.commit_on_success(): self.data.total_relationships -= count self.data.save() if self.schema: schema = self.schema reltype = schema.relationshiptype_set.get(pk=label) reltype.total = 0 reltype.save() elif "id" in options: relationship_ids = options.get("id") if not isinstance(relationship_ids, (list, tuple)): relationship_ids = [relationship_ids] for relationship_id in relationship_ids: Relationship(relationship_id, self.graph).delete() else: eltos = self.gdb.get_all_relationships(include_properties=False) self.gdb.delete_relationships(eltos) with transaction.commit_on_success(): self.data.total_relationships = 0 self.data.save() if self.schema: schema = self.schema for reltype in schema.relationshiptype_set.all(): reltype.total = 0 reltype.save()
def test_associate_associates(self): with transaction.commit_on_success(): handle = self.a.make_unassociated() with transaction.commit_on_success(): self.a.associate(handle, 1) with transaction.commit_on_success(): self.assertEqual(self.a.id(handle), 1)
def handle(self, *args, **options): options['handle'] = self bounds ={ VAR_PERIOD: {'fifteen_start': MAX_DATE, 'fifteen_end': MIN_DATE, 'hourly_start': MAX_DATE, 'hourly_end': MIN_DATE, 'daily_start': MAX_DATE, 'daily_end': MIN_DATE, 'monthly_start': MAX_DATE, 'monthly_end': MIN_DATE}, VAR_ENERGY_PERIOD: {'fifteen_start': MAX_DATE, 'fifteen_end': MIN_DATE, 'hourly_start': MAX_DATE, 'hourly_end': MIN_DATE, 'daily_start': MAX_DATE, 'daily_end': MIN_DATE, 'monthly_start': MAX_DATE, 'monthly_end': MIN_DATE}} for household in Household.objects.all(): # We "commit" to database each household, if everything # went ok. (Write some action on failures and) # exceptions, maybe the whole process should be under one # big transaction, or oposite solution: on exception # ignore and continue to other households, log the error. with transaction.commit_on_success(): process_household(household, bounds) for dma in DMA.objects.all(): # The same holds for DMAs (see above) with transaction.commit_on_success(): process_dma(dma, bounds)
def run(self, force = False, debug = False): from bambu_cron.models import Job kwargs = {} if not force: kwargs['next_run__lte'] = now() with transaction.commit_on_success(): for job in Job.objects.filter(running = False, **kwargs).select_for_update(): handler = self._registry.get(job.name) if handler is None: job.delete() continue job.running = True job.save() try: if handler.transactional: with transaction.commit_on_success(): handler.run(self.logger) else: handler.run(self.logger) except Exception, ex: if debug: raise else: self.logger.error('Error running cron job', exc_info = True) job.running = False job.next_run = handler.next_run_date() job.save()
def handle(self, **options): # drop existing layers with new names: only needed if you've run dd_load # before update_layer_names # for new_name in RENAMES.values(): # for l in Layer.objects.filter(name=new_name): # l.delete() with transaction.commit_on_success(): cursor = connection.cursor() for old_name, new_name in RENAMES.iteritems(): cursor.execute("UPDATE data_dict_layer SET name = %s WHERE name = %s;", [new_name, old_name]) cursor.execute("UPDATE data_dict_tag SET layer_id = %s WHERE layer_id = %s;", [new_name, old_name]) cursor.execute("UPDATE data_dict_layerindataset SET layer_id = %s WHERE layer_id = %s;", [new_name, old_name]) print 'CONNECTION: default' for q in connection.queries: print q['sql'] # the actual layers for conn_name in connections: if conn_name != 'default': conn = connections[conn_name] with transaction.commit_on_success(): cursor = conn.cursor() for old_name, new_name in RENAMES.iteritems(): cursor.execute("UPDATE geometry_columns SET f_table_name = %s WHERE f_table_name = %s;", [new_name, old_name]) cursor.execute("SELECT 1 FROM pg_tables WHERE schemaname='public' AND tablename=%s;", [old_name]) old_table_exists = cursor.fetchall() if old_table_exists: print "In %s renaming %s to %s" % (conn_name, old_name, new_name) cursor.execute("ALTER TABLE %s RENAME TO %s;" % (old_name, new_name)) print 'CONNECTION: %s' % (conn_name,) for q in conn.queries: print q['sql']
def test_send_status_batch(self): fake_request = self.mox.CreateMockAnything() fake_request.method = 'PUT' messages = { MESSAGE_ID_1: 200, MESSAGE_ID_2: 400 } body_dict = {'messages': messages} body = json.dumps(body_dict) fake_request.body = body self.mox.StubOutWithMock(transaction, 'commit_on_success') trans_obj = self.mox.CreateMockAnything() transaction.commit_on_success().AndReturn(trans_obj) trans_obj.__enter__() results1 = self.mox.CreateMockAnything() models.InstanceExists.objects.select_for_update().AndReturn(results1) exists1 = self.mox.CreateMockAnything() results1.get(message_id=MESSAGE_ID_2).AndReturn(exists1) exists1.save() results2 = self.mox.CreateMockAnything() models.InstanceExists.objects.select_for_update().AndReturn(results2) exists2 = self.mox.CreateMockAnything() results2.get(message_id=MESSAGE_ID_1).AndReturn(exists2) exists2.save() trans_obj.__exit__(None, None, None) self.mox.ReplayAll() resp = dbapi.exists_send_status(fake_request, 'batch') self.assertEqual(resp.status_code, 200) exists1.send_status = 200 self.mox.VerifyAll()
def _create_or_update_path(tobj, path, ptype, label): """ create or update the path item""" _label = "'%s'"%label if label else None try: with transaction.commit_on_success(): pitm = PI.objects.create(path=path, type=ptype, label=label) pitm.owners.add(tobj) except IntegrityError: #update the path item with transaction.commit_on_success(): pitm = PI.objects.get(path=path) pitm.type = ptype pitm.label = label pitm.save() pitm.owners.add(tobj) self.pi_update += 1 self.print_msg("An existing path item updated. ID='%s' PATH=" "'%s' TYPE=%s LABEL=%s"%(identifier, path, PI.TYPE2STR[ptype], _label)) else: self.pi_create += 1 self.print_msg("New path item cretated. ID='%s' PATH='%s' " "TYPE=%s LABEL=%s"%(identifier, path, PI.TYPE2STR[ptype], _label)) return pitm
def merge(self, other): TitleMapping.objects.filter(work=other).update(work=self) forced = [] try: with transaction.commit_on_success(): other.record_set.update(work=self) other.history_set.update(work=self) except IntegrityError, e: # self와 other의 기록을 함께 가진 경우 # 나중에 기록된 것에 모두 합쳐버린다. w = [self, other] for u in User.objects.filter(record__work__in=w) \ .annotate(count=models.Count('record__work')) \ .filter(count__gt=1): forced.append(u) with transaction.commit_on_success(): r = u.record_set.filter(work__in=w).latest('updated_at') delete = other if r.work == self else self u.record_set.filter(work=delete).delete() u.history_set.filter(work=delete).update(work=r.work) # 병합 처리가 완료되면 다시 합쳐본다. with transaction.commit_on_success(): other.record_set.update(work=self) other.history_set.update(work=self)
def create_profile_callback(sender, **kwargs): ''' Automatically create profile when creating new user. ''' if kwargs['created']: # Need to handle this in separate transaction as it might fail # in case we're run from syncdb. Transaction handling is needed # for PostgreSQL as otherwise whole transaction will be in bad # state ("current transaction is aborted, queries ignored until # end of transaction block") transaction.commit() try: with transaction.commit_on_success(): # Create profile profile, newprofile = Profile.objects.get_or_create(user = kwargs['instance']) with transaction.commit_on_success(): # Add user to Users group if it exists try: group = Group.objects.get(name = 'Users') kwargs['instance'].groups.add(group) except Group.DoesNotExist: pass except DatabaseError: pass
def patientregistrationview(request): """bill view""" if request.method == "POST": patientregistrationform = PatientRegistrationForm(request.POST) patientcontactform = PatientContactForm(request.POST) if patientcontactform.is_valid()and patientregistrationform.is_valid(): with transaction.commit_on_success(): idd=len(PatientMaster.objects.all())+1 patient='HSP'+str(idd) new_user = patientregistrationform.save(commit=False) # blood=patientregistrationform.data['lastname'] new_user.patientid=patient new_user.save() with transaction.commit_on_success(): conct= patientcontactform.save(commit=False); conct.contactid=patient conct.save() patients = PatientMaster.objects.order_by('patientid') contact = PatientContact.objects.all() return render_to_response("patient.html",{"patients":patients,"contact":contact,}, context_instance=RequestContext(request)) else: #redirects to bill.html with error in form return render_to_response('patientregistration.html',{'patientregistrationform':patientregistrationform,'patientcontactform':patientcontactform,},context_instance=RequestContext(request)) # default page for rendering when /bill is loaded for first time patientregistrationform = PatientRegistrationForm() patientcontactform = PatientContactForm() return render_to_response('patientregistration.html',{'patientregistrationform':patientregistrationform,'patientcontactform':patientcontactform,},context_instance=RequestContext(request))
def import_user_bookmarks_from_ns_list(user, nsbmk_txt): ref_and_metadata = import_references_from_ns_bookmark_list(nsbmk_txt) bmk_to_process = [] for ref, meta in ref_and_metadata.items(): try: bmk = UserBookmark.objects.get(owner=user, reference=ref) except ObjectDoesNotExist: bmk = UserBookmark(owner=user, reference=ref, saved_date=ref.pub_date) ref.save_count += 1 for src in ref.sources.all(): user.userprofile.sources.add(src) bmk.is_public = meta.is_public bmk.comment = meta.note # pile up the bookmarks for tag attribution bmk_to_process.append((bmk, meta)) with transaction.commit_on_success(): for b, _ in bmk_to_process: b.reference.save() b.save() classif_data_to_save = [] for bmk, meta in bmk_to_process: valid_tags = [t for t in meta.tags if len(t) <= TAG_NAME_MAX_LENGTH] if len(valid_tags) != len(meta.tags): invalid_tags = [t for t in meta.tags if len(t) > TAG_NAME_MAX_LENGTH] logger.error( "Could not import some bmk tags with too long names (%s>%s)" % (",".join(len(t) for t in invalid_tags), TAG_NAME_MAX_LENGTH) ) classif_data_to_save.append(set_item_tag_names(user, bmk.reference, valid_tags)) with transaction.commit_on_success(): for cd in classif_data_to_save: cd.save()
def run(): global site, SCRIPT_PATH url = raw_input("Enter the address of a MediaWiki site (ex: http://arborwiki.org/): ") site = wiki.Wiki(guess_api_endpoint(url)) SCRIPT_PATH = guess_script_path(url) sitename = site.siteinfo.get('sitename', None) if not sitename: print "Unable to connect to API. Please check the address." sys.exit(1) print "Ready to import %s" % sitename yes_no = raw_input("This import will clear out any existing data in this " "LocalWiki instance. Continue import? (yes/no) ") if yes_no.lower() != "yes": sys.exit() print "Clearing out existing data..." with transaction.commit_on_success(): clear_out_existing_data() start = time.time() print "Importing users..." with transaction.commit_on_success(): import_users() print "Importing pages..." import_pages() print "Importing redirects..." import_redirects() if _maps_installed: print "Processing map data..." process_mapdata() print "Import completed in %.2f minutes" % ((time.time() - start) / 60.0)
def update_user_results(self, user, problem_instance): """Updates score for problem instance, round and contest. Usually this method creates instances (if they don't exist) of: * :class:`~oioioi.contests.models.UserResultForProblem` * :class:`~oioioi.contests.models.UserResultForRound` * :class:`~oioioi.contests.models.UserResultForContest` and then calls proper methods of ContestController to update them. """ round = problem_instance.round contest = round.contest # We do this in three separate transactions, because in some database # engines (namely MySQL in REPEATABLE READ transaction isolation level) # data changed by a transaction is not visible in subsequent SELECTs # even in the same transaction. # First: UserResultForProblem with transaction.commit_on_success(): result, created = UserResultForProblem.objects.select_for_update() \ .get_or_create(user=user, problem_instance=problem_instance) self.update_user_result_for_problem(result) # Second: UserResultForRound with transaction.commit_on_success(): result, created = UserResultForRound.objects.select_for_update() \ .get_or_create(user=user, round=round) self.update_user_result_for_round(result) # Third: UserResultForContest with transaction.commit_on_success(): result, created = UserResultForContest.objects.select_for_update() \ .get_or_create(user=user, contest=contest) self.update_user_result_for_contest(result)
def pre_execute(self): """ Do pre-execution work. At the moment, this work entails: parsing and initializing sources, parsing and initializing the site model (if there is one), parsing vulnerability and exposure files, and generating logic tree realizations. (The latter piece basically defines the work to be done in the `execute` phase.) """ # if you don't use an explicit transaction, errors will be masked # the problem is that Django by default performs implicit transactions # without rollback, see # https://docs.djangoproject.com/en/1.3/topics/db/transactions/ with transaction.commit_on_success(using='job_init'): self.parse_risk_model() with transaction.commit_on_success(using='job_init'): self.initialize_site_collection() hc = self.hc n_sites = len(self.site_collection) n_gmf = hc.number_of_ground_motion_fields n_imts = len(hc.intensity_measure_types_and_levels) output_weight = n_sites * n_imts * n_gmf logs.LOG.info('Expected output size=%s', output_weight) models.JobInfo.objects.create( oq_job=self.job, num_sites=n_sites, num_realizations=1, num_imts=n_imts, num_levels=0, input_weight=0, output_weight=output_weight) self.check_limits(input_weight=0, output_weight=output_weight) self.create_ruptures() return 0, output_weight
def test_release_entry_lock_releases(self): with transaction.commit_on_success(): acquired_lock = locking.try_acquiring_lock(self.entry_abcd, self.foo) self.assertIsNotNone(acquired_lock) self.assertLogRegexp( r"^foo acquired lock \d+ on entry \d+ \(headword: abcd\)$") with transaction.commit_on_success(): lock = locking.try_acquiring_lock(self.entry_abcd, self.foo2) self.assertIsNone(lock) self.assertLogRegexp( r"^foo2 failed to expire lock \d+ on entry \d+ " r"\(headword: abcd\)$") locking.release_entry_lock(acquired_lock, self.foo) self.assertLogRegexp( r"^foo released lock \d+ on entry \d+ \(headword: abcd\)$") # This will work because the lock was released with transaction.commit_on_success(): lock = locking.try_acquiring_lock(self.entry_abcd, self.foo2) self.assertIsNotNone(lock) self.assertLogRegexp( r"^foo2 acquired lock \d+ on entry \d+ \(headword: abcd\)$")
def test_send_status_batch_multiple_results(self): fake_request = self.mox.CreateMockAnything() fake_request.method = 'PUT' messages = { MESSAGE_ID_1: 200, } body_dict = {'messages': messages} body = json.dumps(body_dict) fake_request.body = body self.mox.StubOutWithMock(transaction, 'commit_on_success') trans_obj = self.mox.CreateMockAnything() transaction.commit_on_success().AndReturn(trans_obj) trans_obj.__enter__() results = self.mox.CreateMockAnything() models.InstanceExists.objects.select_for_update().AndReturn(results) exception = models.InstanceExists.MultipleObjectsReturned() results.get(message_id=MESSAGE_ID_1).AndRaise(exception) trans_obj.__exit__(dbapi.APIException().__class__, mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() resp = dbapi.exists_send_status(fake_request, 'batch') self.assertEqual(resp.status_code, 500) body = json.loads(resp.content) self.assertEqual(body.get("status"), 500) msg = "Multiple Exists records with message_id = '%s'" msg = msg % MESSAGE_ID_1 self.assertEqual(body.get("message"), msg) self.mox.VerifyAll()
def reset_password(request, guid = None): if guid: with transaction.commit_on_success(): reset = get_object_or_404(PasswordReset, guid = guid) reset.reset() messages.success(request, _('Your new password should be in your inbox shortly.') ) return HttpResponseRedirect(settings.LOGIN_URL) form = PasswordResetForm(request.POST or None) if request.method == 'POST' and form.is_valid(): with transaction.commit_on_success(): try: user = User.objects.get(email__iexact = form.cleaned_data['email']) user.password_resets.all().delete() reset = user.password_resets.create() except User.DoesNotExist: pass return TemplateResponse( request, 'saas/password-reset.html', {} ) return TemplateResponse( request, 'saas/forgot-password.html', { 'form': form } )
def logavbutton(self, request, **kwargs): print request.POST for key,value in request.POST.iteritems(): #if request.POST['key']: # kusername = get_username(request.POST['key']) #if kusername: # actions = simplejson.loads(request.POST['actions']) #actions = simplejson.loads(request.POST) actions = json.loads(key) number_logs = 0 for act in actions: if 'score[total]' in request.POST: streak = request.POST['score[total]'] else: streak = 0 with transaction.commit_on_success(): kusername, created = User.objects.get_or_create(username=act['user']) if Exercise.objects.filter(name=act['av']).count()==1: kexercise = Exercise.objects.get(name=act['av']) else: with transaction.commit_on_success(): kexercise = Exercise(name=act['av'], streak=streak) kexercise.save() with transaction.commit_on_success(): kbook = Books.objects.get(book_name= act['book']) #request.POST['book']) user_data, created = UserData.objects.get_or_create(user=kusername,book=kbook) module = get_module(act['module']) if kexercise and module: with transaction.commit_on_success(): user_module, exist = UserModule.objects.get_or_create(user=kusername, book=kbook,module=module) user_button,correct = log_button_action( kusername, kexercise, module, kbook, act['type'], act['desc'], act['tstamp'], act['uiid'], request.user_agent.browser.family, request.user_agent.browser.version_string, request.user_agent.os.family, request.user_agent.os.version_string, request.user_agent.device.family, request.META['REMOTE_ADDR'], ) if correct: number_logs += 1 if number_logs == len(actions): return self.create_response(request, {'success': True, 'message': 'all button action logged'}) else: return self.create_response(request, {'success': False, 'error': 'not all button action logged'}, HttpBadRequest) return self.create_response(request, {'success': False, 'error': 'unauthorized action'}, HttpUnauthorized)
def test_try_acquiring_lock_on_two_entries(self): # Same user acquires lock on two different entries. with transaction.commit_on_success(): lock = locking.try_acquiring_lock(self.entry_abcd, self.foo) self.assertIsNotNone(lock) with transaction.commit_on_success(): lock = locking.try_acquiring_lock(self.entry_foo, self.foo) self.assertIsNotNone(lock)
def _handle(self, browse_layer_id, browse_type): from ngeo_browse_server.control.queries import remove_browse # query the browse layer if browse_layer_id: try: browse_layer_model = BrowseLayer.objects.get(id=browse_layer_id) except BrowseLayer.DoesNotExist: logger.error( "Browse layer '%s' does not exist" % browse_layer_id ) raise CommandError( "Browse layer '%s' does not exist" % browse_layer_id ) else: try: browse_layer_model = BrowseLayer.objects.get( browse_type=browse_type ) except BrowseLayer.DoesNotExist: logger.error("Browse layer with browse type '%s' does " "not exist" % browse_type) raise CommandError("Browse layer with browse type '%s' does " "not exist" % browse_type) # get all browses of browse layer browses_qs = Browse.objects.all().filter(browse_layer=browse_layer_model) paths_to_delete = [] seed_areas = [] with transaction.commit_on_success(): with transaction.commit_on_success(using="mapcache"): logger.info("Deleting '%d' browse%s from database." % (browses_qs.count(), "s" if browses_qs.count() > 1 else "")) # go through all browses to be deleted for browse_model in browses_qs: _, filename = remove_browse( browse_model, browse_layer_model, browse_model.coverage_id, seed_areas, unseed=False ) paths_to_delete.append(filename) # loop through optimized browse images and delete them # This is done at this point to make sure a rollback is possible # if there is an error while deleting the browses and coverages for file_path in paths_to_delete: if exists(file_path): remove(file_path) logger.info("Optimized browse image deleted: %s" % file_path) else: logger.warning("Optimized browse image to be deleted not found " "in path: %s" % file_path) delete_browse_layer(browse_layer_model, purge=True)
def add_borrower(request): logged_in = request.user.is_authenticated() if not logged_in: return redirect('/sign_in') username1 = request.user.get_username() type = UserProfile.objects.get(username = username1).type if type != 1: return redirect('/rule') registered = False error = False if request.method == 'POST': borrower = BorrowerForm(request.POST) if borrower.is_valid(): username = borrower.cleaned_data['username'] password = borrower.cleaned_data['password'] type0 = borrower.cleaned_data['type'] name = borrower.cleaned_data['name'] address = borrower.cleaned_data['address'] phone = borrower.cleaned_data['phone'] emailAddress = borrower.cleaned_data['emailAddress'] sinOrStNo = borrower.cleaned_data['sinOrStNo'] cursor = connection.cursor() try: type = BorrowerType.objects.get(type=type0) except ObjectDoesNotExist: if type0 == 'ST': bookTimeLimit = 14 elif type0 == 'FA': bookTimeLimit = 84 elif type0 == 'SF': bookTimeLimit = 42 cursor.execute("INSERT INTO books_borrowertype (type, bookTimeLimit) VALUES ('%s', '%s') " %(type0, bookTimeLimit)) transaction.commit_on_success() type = BorrowerType.objects.get(type=type0) # we assume the expiry date for every borrower is one year from current day expiryDate = date.today() + timedelta(days = 365) # add borrower table cursor.execute("INSERT INTO books_borrower (username, password, name, address, phone, emailAddress, sinOrStNo, expiryDate, type_id) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', ADDDATE(CURDATE(), 365), '%s') " %(username, password, name, address, phone, emailAddress,sinOrStNo, type0)) transaction.commit_on_success() # add borrower accounts user = User.objects.create_user(username, None, password) user.set_password(password) user.save() user_type = UserProfile(username=username,type=0) user_type.save() registered = True else: error = True; else: borrower = BorrowerForm() return render(request, 'books/clerk/add_borrower.html', {'logged_in':logged_in, 'username':username1, 'type':type, 'error':error, 'borrower':borrower, 'registered':registered})
def _update_curves(hc, matrices, lt_rlz, src_ids): """ Helper function for updating source, hazard curve, and realization progress records in the database. This is intended to be used by :func:`compute_hazard_curves`. :param hc: :class:`openquake.engine.db.models.HazardCalculation` instance. :param lt_rlz: :class:`openquake.engine.db.models.LtRealization` record for the current realization. :param src_ids: List of source IDs considered for this calculation task. """ with logs.tracing('_update_curves for all IMTs'): for imt in hc.intensity_measure_types_and_levels.keys(): with transaction.commit_on_success(): logs.LOG.debug('> updating hazard for IMT=%s' % imt) hazardlib_imt = haz_general.imt_to_hazardlib(imt) query = """ SELECT * FROM htemp.hazard_curve_progress WHERE lt_realization_id = %s AND imt = %s FOR UPDATE""" [hc_progress] = models.HazardCurveProgress.objects.raw( query, [lt_rlz.id, imt]) hc_progress.result_matrix = update_result_matrix( hc_progress.result_matrix, matrices[hazardlib_imt]) hc_progress.save() logs.LOG.debug('< done updating hazard for IMT=%s' % imt) with transaction.commit_on_success(): # Check here if any of records in source progress model # with parsed_source_id from src_ids are marked as complete, # and rollback and abort if there is at least one src_prog = models.SourceProgress.objects.filter( lt_realization=lt_rlz, parsed_source__in=src_ids) if any(x.is_complete for x in src_prog): msg = ( 'One or more `source_progress` records were marked as ' 'complete. This was unexpected and probably means that the' ' calculation workload was not distributed properly.' ) logs.LOG.critical(msg) transaction.rollback() raise RuntimeError(msg) # Mark source_progress records as complete src_prog.update(is_complete=True) # Update realiation progress, # mark realization as complete if it is done haz_general.update_realization(lt_rlz.id, len(src_ids))
def test_make_unassociated_is_per_session(self): with transaction.commit_on_success(): self.assertEqual(self.a.make_unassociated(), 0, "first") with transaction.commit_on_success(): self.assertEqual(self.a.make_unassociated(), 1, "second") with transaction.commit_on_success(): self.assertEqual(self.b.make_unassociated(), 0, "first") with transaction.commit_on_success(): self.assertEqual(self.b.make_unassociated(), 1, "second")
def test_make_unassociated_remembers(self): with transaction.commit_on_success(): self.assertEqual(self.a.make_unassociated(), 0, "first") with transaction.commit_on_success(): self.assertEqual(self.a.make_unassociated(), 1, "second") # This creates an object which will have to read from the DB. new_a = handles.HandleManager("a") with transaction.commit_on_success(): self.assertEqual(new_a.make_unassociated(), 2, "third")
def test_associate_is_per_session(self): with transaction.commit_on_success(): handle_a = self.a.make_unassociated() handle_b = self.b.make_unassociated() self.assertEqual(handle_a, handle_b) with transaction.commit_on_success(): self.a.associate(handle_a, 1) with transaction.commit_on_success(): self.assertEqual(self.a.id(handle_a), 1) self.assertIsNone(self.b.id(handle_b))
def import_compra_lineas(compra_lineas): import_count = 0 for i in compra_lineas: try: compralinea = to_compralinea_entity(i) if compralinea is not None: compralinea.save() transaction.commit_on_success(compralinea) import_count += 1 except Exception: logger.exception('Failed to import compralinea: %r', i) logger.info('Successfully imported %d CompraLineaItems', import_count)
def test_coupon_flyer_unicity(self): """ Assert a coupon cannot be added to a flyer twice. """ flyer = Flyer.objects.create(site_id=3) coupon = COUPON_FACTORY.create_coupon() # Adding works once. with transaction.commit_on_success(): self.assertTrue(append_coupon_to_flyer(flyer, coupon)) # This still returns True to say the flyer still needs more coupons. with transaction.commit_on_success(): self.assertTrue(append_coupon_to_flyer(flyer, coupon)) # The coupon is only relate to the flyer once, however. self.assertEqual(flyer.flyer_coupons.filter(coupon=coupon).count(), 1)
def import_compra_lineas(compra_lineas): for i in compra_lineas: try: compralinea = to_compralinea_entity(i) if compralinea is None: logger.info("compralinea is None, i'm out") continue compralinea.save() transaction.commit_on_success(compralinea) except Exception: logger.exception('Failed to import compralinea: %r', i) logger.info('Successfully imported %d CompraLineaItems', len(compra_lineas))
def import_compras(compras): imported_compras = set() for i in compras: try: orden_compra = int(i['orden_compra']) if orden_compra not in imported_compras: compra = to_compra_entity(i) imported_compras.add(orden_compra) compra.save() transaction.commit_on_success(compra) except Exception: logger.exception('Failed to import compra: %r', i) logger.info('Successfully imported %d CompraItems', len(imported_compras))
def object_view(self, request, object_id, **kwargs): """ The view for the second (object) endpoint, wherein a 'GET' request returns an object matching the given ID and kwargs, a 'PUT' updates the object and a 'DELETE' removes it. When a 'PUT' request is given, the values of the posted data are given to a newly-instantiated ``Form``. If the data is correct, the updated object is returned. If invalid, an ``APIException`` is raised, with the descriptions of the offending fields' validation exceptions contained within. When a 'DELETE' request is given and the operation successful, the value 'OK' is returned. """ obj = self.get_object(request, object_id, **kwargs) if request.method == 'DELETE': with transaction.commit_on_success(): obj.delete() return ['OK'] elif request.method == 'PUT': request.method = 'POST' request._load_post_and_files() request.method = 'PUT' form_class = self.get_form(request, obj) data = self.prepare_initial_data(form_class, obj) for key, value in request.POST.items(): data[key] = value form = form_class(data, request.FILES, instance=obj) if form.is_valid(): obj = self.save_form(request, form, obj) self.save_object(request, obj) return obj errors = [] for error in form.non_field_errors(): errors.append(error) for field in form: if field.errors and any(field.errors): inline_errors = list([e for e in field.errors]) errors.append({field.name: inline_errors}) raise Exception(errors) return obj
def _store_cached_input_links(self, with_transaction=True): """ Store all input links that are in the local cache, transferring them to the DB. :note: This can be called only if all parents are already stored. :note: Links are stored only after the input nodes are stored. Moreover, link storage is done in a transaction, and if one of the links cannot be stored, an exception is raised and *all* links will remain in the cache. :note: This function can be called only after the node is stored. After that, it can be called multiple times, and nothing will be executed if no links are still in the cache. :parameter with_transaction: if False, no transaction is used. This is meant to be used ONLY if the outer calling function has already a transaction open! """ from django.db import transaction from aiida.common.utils import EmptyContextManager if with_transaction: context_man = transaction.commit_on_success() else: context_man = EmptyContextManager() if self._to_be_stored: raise ModificationNotAllowed( "Node with pk= {} is not stored yet".format(self.pk)) with context_man: # This raises if there is an unstored node. self._check_are_parents_stored() # I have to store only those links where the source is already # stored links_to_store = list(self._inputlinks_cache.keys()) for label in links_to_store: src, link_type = self._inputlinks_cache[label] self._add_dblink_from(src, label, link_type) # If everything went smoothly, clear the entries from the cache. # I do it here because I delete them all at once if no error # occurred; otherwise, links will not be stored and I # should not delete them from the cache (but then an exception # would have been raised, and the following lines are not executed) self._inputlinks_cache.clear()
def bulk_history_create(model, history_model): """Save a copy of all instances to the historical model.""" historical_instances = [ history_model(history_date=getattr(instance, '_history_date', now()), history_user=getattr(instance, '_history_user', None), **dict((field.attname, getattr(instance, field.attname)) for field in instance._meta.fields)) for instance in model.objects.all() ] try: history_model.objects.bulk_create(historical_instances) except AttributeError: # pragma: no cover # bulk_create was added in Django 1.4, handle legacy versions with transaction.commit_on_success(): for instance in historical_instances: instance.save()
def create_join_request(account, team, application): if not can_join(account, team): raise PermissionDenied join_request = None with transaction.commit_on_success(): join_request = JoinRequest() join_request.team = team join_request.requester = account join_request.application = application if len(team.members.all()) == 0: # auto join empty teams join_request.status = "ACCEPTED" team.members.add(account) join_request.save() signals.join_request_created.send(sender=create_join_request, join_request=join_request) return join_request
def load_data(self, name): """ Load stored model module and run it, creating new model objects. This script is run under a transaction to avoid committing partial settings in case of some exception. """ # ref http://stackoverflow.com/a/14192708/2157429 buf = self.buffers[name]['buffer'] if buf is not None: self.stdout.write('Loading saved %s ...' % (name), ending='') m = imp.new_module('runscript') exec buf in m.__dict__ with transaction.commit_on_success(): m.run() db.close_connection() self.stdout.write('done.')
def generate(drink, invalidate_first=True): """Generate all stats for this drink. Args: drink: The drink. invalidate_first: If True, deletes any existing records for (or after) this drink first. """ with transaction.commit_on_success(): if invalidate_first: invalidate(drink) generate_system_stats(drink) generate_keg_stats(drink) generate_user_stats(drink) generate_session_stats(drink)
def update_user_results(env, **kwargs): with transaction.commit_on_success(): submission = Submission.objects.get(id=env['submission_id']) user = submission.user if not user: return env problem_instance = \ ProblemInstance.objects.get(id=env['problem_instance_id']) round = problem_instance.round assert round.id == env['round_id'] contest = round.contest assert contest.id == env['contest_id'] contest.controller.update_user_results(user, problem_instance) return env
def save(self, *args, **kwargs): super(GovorecMap, self).save(*args, **kwargs) # posodobi obstojece zapise with transaction.commit_on_success(): transaction.set_dirty() cur = connection.cursor() # zapisi cur.execute( '''UPDATE %s SET govorec_oseba_id = %%s WHERE govorec = %%s''' % Zapis._meta.db_table, [self.oseba.id, self.govorec]) # glasovanja cur.execute( '''UPDATE %s SET oseba_id = %%s WHERE poslanec = %%s''' % Glas._meta.db_table, [self.oseba.id, self.govorec])
def handle(self, *args, **options): while True: try: with DelayedKeyboardInterrupt(): with transaction.commit_on_success(): batch_sync( force_save=options['force_save'], limit=options['batch_size'], stdout=self.stdout, ) except NoMoreData: self.stdout.write( 'Up to date! Waiting {sleep_time} ' 'second(s) before continuing'.format(**options) ) time.sleep(options['sleep_time'])
def create_queue_entries_from_gt(self, queue, administrator): now = datetime.datetime.now() with transaction.commit_on_success(): for gt_record in queue.last_gt.globaltagrecord_set.all(): qte = GTQueueEntry() qte.queue = queue qte.tag = gt_record.tag qte.record = gt_record.record qte.label = gt_record.label #ASK PFN qte.comment = "Automaticaly created comment for original entries" #ASK maybe global tag entires should have qte.status = 'O' qte.submitter = administrator qte.administrator = administrator qte.administration_time = now qte.save()
def create(self, label, properties=None): if self.data.can_add_nodes(): with transaction.commit_on_success(): if self.schema: nodetype = self.schema.nodetype_set.get(pk=label) if not self.graph.relaxed: properties = self._filter_dict(properties, nodetype) nodetype.total += 1 nodetype.save() self.data.total_nodes += 1 self.data.save() node_id = self.gdb.create_node(label=label, properties=properties) node = Node(node_id, self.graph, initial=properties, label=label) return node else: raise NodesLimitReachedException
def delete_topic(request): """ Delete topic from discussion list via AJAX request. """ pk = request.POST.get('object_pk') if not pk: return HttpResponse( json.dumps({ 'success': False, 'message': _("No entry ID provided"), 'level': 'danger', })) try: topic = Discussion.objects.get(pk=pk) except Discussion.DoesNotExist as ex: return HttpResponse( json.dumps({ 'success': False, 'message': str(ex), 'level': 'danger', })) moderator = is_moderator(request.user, topic.location) if request.user != topic.creator and not moderator: return HttpResponse( json.dumps({ 'success': False, 'message': _("Permission required!"), 'level': 'danger', })) try: with transaction.commit_on_success(): topic.delete() return HttpResponse( json.dumps({ 'success': True, 'message': _("Entry deleted"), 'level': 'success', })) except Exception as ex: return HttpResponse( json.dumps({ 'success': False, 'message': str(ex), 'level': 'danger', }))
def vote(request, course_id): # retrieve course and make sure that the user is allowed to vote course = get_object_or_404(Course, id=course_id) if not course.can_user_vote(request.user): raise PermissionDenied # build forms forms = SortedDict() for questionnaire, contribution in questionnaires_and_contributions( course): form = QuestionsForm(request.POST or None, contribution=contribution, questionnaire=questionnaire) forms[(contribution, questionnaire)] = form if all(form.is_valid() for form in forms.values()): # begin vote operation with transaction.commit_on_success(): for (contribution, questionnaire), form in forms.items(): for question in questionnaire.question_set.all(): identifier = make_form_identifier(contribution, questionnaire, question) value = form.cleaned_data.get(identifier) if type(value) in [str, unicode]: value = value.strip() if value == 6: #no answer value = None # store the answer if one was given if value: question.answer_class.objects.create( contribution=contribution, question=question, answer=value) # remember that the user voted already course.voters.add(request.user) messages.add_message(request, messages.INFO, _("Your vote was recorded.")) return redirect('evap.student.views.index') else: return render_to_response("student_vote.html", dict(forms=forms.values(), course=course), context_instance=RequestContext(request))
class EmailChangeCreateView(CreateView): """ A view to create an :model:`EmailChange` object. """ model = EmailChange form_class = EmailChangeForm @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): """ If an :model:`EmailChange` object that has been created by the user is found, the user will be redirected to :view:`EmailChangeDetailView`. """ if EmailChange.objects.filter(user=request.user).count(): msg = _("An email address change request was found. It must" " be deleted before a new one can be requested.") messages.add_message(request, messages.ERROR, msg, fail_silently=True) logger.error('Pending email address change request found.') object = EmailChange.objects.filter(user=request.user).get() return HttpResponseRedirect( reverse_lazy('change_email_detail', args=[object.pk])) return super(EmailChangeCreateView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): """ Saves the email address change request, sends an email to confirm the request, adds a success message for the user and redirects to :view:`EmailChangeDetailView`. """ form.instance.user = self.request.user instance = super(EmailChangeCreateView, self).form_valid(form) msg = _("The email address change request was processed.") messages.add_message(self.request, messages.INFO, msg, fail_silently=True) email_change_created.send(sender=self, request=self.request) form.instance.send_confirmation_mail(self.request) return instance form_valid = transaction.commit_on_success(form_valid)
def handle(self, *args, **options): username = options['username'] project_title = options['project_title'] res_uri = options['res_uri'] if (not (username and project_title and res_uri)): print "Username, project, and res are required arguments." exit(0) user_uri = uris.uri('semantic_store_users', username=username) user_g = Graph(store=rdfstore(), identifier=user_uri) # Project title data is stored in the named graph for that project, so we need # to query those graphs rather than just the user graph projectsByTitle = self.project_uris_by_title(user_g, user_uri) print "projectsByTitle: %s" % projectsByTitle.items() if project_title not in projectsByTitle: print "No such project with title '%s' found for user '%s'" % \ (project_title, username) print "User %s has projects entitled %s" % (username, projectsByTitle.keys()) exit(0) project_uris = projectsByTitle[project_title] if len(project_uris) > 1: print "More than one project with that title exists." exit(0) else: project_identifier = project_uris[0] with transaction.commit_on_success(): uri = uris.uri('semantic_store_projects', uri=project_identifier) project_g = Graph(store=rdfstore(), identifier=uri) project_g.add((project_identifier, NS.ore['aggregates'], URIRef(res_uri))) main_g = ConjunctiveGraph(store=rdfstore(), identifier=default_identifier) for t in main_g.triples( (URIRef(res_uri), NS.dc['title'], None)): project_g.add(t) for t in main_g.triples( (URIRef(res_uri), NS.ore['isDescribedBy'], None)): project_g.add(t) for t in main_g.triples( (URIRef(res_uri), NS.rdf['type'], None)): project_g.add(t)
def _process_context(context_id): test_info = [] with transaction.commit_on_success(): logger.debug("progress_context.context_id=%s" % context_id) try: run_context = models.Context.objects.select_for_update( nowait=True).get(id=context_id, deleted=False) except DatabaseError: logger.debug("progress context for %s is already running. exiting" % context_id) return except models.Context.DoesNotExist, e: logger.debug("Context %s removed from other thread" % context_id) return except Exception, e: logger.error(e) return
def import_agenda_items(csvfile): """ Performs the import of agenda items form a csv file. """ # Check encoding try: csvfile.read().decode('utf8') except UnicodeDecodeError: return_value = '', '', _( 'Import file has wrong character encoding, only UTF-8 is supported!' ) else: csvfile.seek(0) # Check dialect dialect = csv.Sniffer().sniff(csvfile.readline()) dialect = csv_ext.patchup(dialect) csvfile.seek(0) # Parse CSV file with transaction.commit_on_success(): success_lines = [] error_lines = [] for (line_no, line) in enumerate(csv.reader(csvfile, dialect=dialect)): if line_no == 0: # Do not read the header line continue # Check format try: title, text, duration = line[:3] except ValueError: error_lines.append(line_no + 1) continue if duration and re.match('^(?:[0-9]{1,2}:[0-5][0-9]|[0-9]+)$', duration) is None: error_lines.append(line_no + 1) continue Item.objects.create(title=title, text=text, duration=duration) success_lines.append(line_no + 1) success = _('%d items successfully imported.') % len(success_lines) if error_lines: error = _('Error in the following lines: %s.') % ', '.join( str(number) for number in error_lines) else: error = '' return_value = success, '', error return return_value
def debit(self, order_number, amount, bankcard, basket, billing_address=None): with transaction.commit_on_success(): response = self.gateway.auth( card_number=bankcard.card_number, expiry_date=bankcard.expiry_date, amount=amount, currency='GBP', merchant_reference=self.generate_merchant_reference( order_number), ccv=bankcard.ccv) # Create transaction model irrespective of whether transaction was successful or not txn = OrderTransaction.objects.create( order_number=order_number, basket=basket, method='auth', datacash_ref=response['datacash_reference'], merchant_ref=response['merchant_reference'], amount=amount, auth_code=response['auth_code'], status=int(response['status']), reason=response['reason'], request_xml=self.gateway.last_request_xml(), response_xml=self.gateway.last_response_xml()) # Test if response is successful if response['status'] == INVALID_CREDENTIALS: # This needs to notify the administrators straight away import pprint msg = "Order #%s:\n%s" % (order_number, pprint.pprint(response)) mail_admins("Datacash credentials are not valid", msg) raise InvalidGatewayRequestError( "Unable to communicate with payment gateway, please try again later" ) if response['status'] == DECLINED: raise TransactionDeclined( "Your bank declined this transaction, please check your details and try again" ) return response['datacash_reference']
def gt_queue_create(request): if request.method == 'POST': gt_queue_form = GTQueueModelForm(request.POST) if gt_queue_form.is_valid(): with transaction.commit_on_success(): gt_queue_obj = gt_queue_form.save() GTQueueManager(gt_queue_obj).create_children(request.user) logger.info("Preparing for report") report_queue_created(gt_queue_obj) logger.info("Report should be sent") return HttpResponseRedirect( reverse('gt_queue_list')) # Redirect after POST else: gt_queue_form = GTQueueModelForm() return render_to_response("admin2/gt_queue_create.html", {"gt_queue_form": gt_queue_form}, context_instance=RequestContext(request))
def import_user_feedsources_from_opml(user,opml_txt): feeds_and_tags = import_feedsources_from_opml(opml_txt) profile = UserProfile.objects.get(owner=user) classif_data_to_save = [] for feed,tags in feeds_and_tags.items(): profile.web_feeds.add(feed) profile.sources.add(feed.source) valid_tags = [t for t in tags if len(t)<=TAG_NAME_MAX_LENGTH] if len(valid_tags)!=len(tags): invalid_tags = [t for t in tags if len(t)>TAG_NAME_MAX_LENGTH] logger.error("Could not import some source tags with too long names (%s>%s)"\ % (",".join(str(len(t)) for t in invalid_tags), TAG_NAME_MAX_LENGTH)) classif_data_to_save.append(set_item_tag_names(user,feed,valid_tags)) with transaction.commit_on_success(): for cd in classif_data_to_save: cd.save()
def create_zone_ajax(request): """ This view tries to create a new zone and returns an JSON with either 'success' = True or 'success' = False and some errors. """ qd = request.POST.copy() # See if the domain exists. # Fail if it already exists or if it's under a delegated domain. root_domain = qd.get('root_domain', None) primary = qd.get('soa_primary', None) contact = qd.get('soa_contact', None) # Find all the NS entries nss = [] number_re = re.compile('nameserver_(\d+)') # parse nameserver bits from POST request. # compile some tuples that look like: # (<server_fqdn>, <ttl>, [<view_name>,..]) for k, server in request.POST.iteritems(): if k.startswith('nameserver_'): n = number_re.search(k) if not n: continue ns_number = n.groups()[0] views = [] if qd.get('private_view_{0}'.format(ns_number), 'off') == 'on': views.append('private') if qd.get('public_view_{0}'.format(ns_number), 'off') == 'on': views.append('public') ttl = qd.get('ttl_{0}'.format(ns_number)) if ttl and ttl.isdigit(): ttl = int(ttl) else: ttl = None nss.append((server, ttl, views)) try: with transaction.commit_on_success(): domain = _create_zone(root_domain, primary, contact, nss) except (ValueError, ValidationError), e: return HttpResponse(json.dumps({ 'success': False, 'error': str(e) }), status=400)
def create_remove_request(requester, concerned, team, reason): if not can_create_remove_request(requester, concerned, team): raise PermissionDenied remove_request = None with transaction.commit_on_success(): remove_request = RemoveRequest() remove_request.team = team remove_request.requester = requester remove_request.concerned = concerned remove_request.reason = reason if len(team.members.all()) == 1: # auto remove last member remove_request.status = "ACCEPTED" remove_request.team.members.remove(remove_request.concerned) remove_request.save() signals.remove_request_created.send(sender=create_remove_request, remove_request=remove_request) return remove_request
def verify_email(request, guid = None): if guid: with transaction.commit_on_success(): validation = get_object_or_404(EmailValidation, guid = guid) user = validation.user user.is_active = True user.save() if user.pending_newsletter_optins.exists(): newsletter_optin.send( type(user), user = user ) user.pending_newsletter_optins.all().delete() validation.delete() messages.success(request, _('Thanks for confirming your email address.')) plan_signup.send( UserPlan, plan = UserPlan.objects.get_for_user(user), user = user ) next = getattr(settings, 'SIGNUP_REDIRECT', getattr(settings, 'LOGIN_REDIRECT_URL', '/') ) return HttpResponseRedirect( '%s?%s' % ( settings.LOGIN_URL, urlencode( { 'next': next } ) ) ) return TemplateResponse( request, 'saas/signup-complete.html', {} )
def acquire_lock(self, timeout=0, no_wait=True): try: with transaction.commit_on_success(using=self.connection): SerialQueue.objects.using(self.connection).select_for_update( no_wait=no_wait).get(name=self.name, lock_expires__lte=now()) if timeout: self.lock_expires = now() + timedelta(seconds=timeout) self.save() except DatabaseError: logger.debug('%s SerialQueue currently locked on update' % self.name) return False except SerialQueue.DoesNotExist: logger.debug('%s SerialQueue currently locked' % self.name) return False return True
class Ajuda(models.Model): titulo = models.CharField(_('Titulo'), max_length=50) # order ordem = PositionField(_('Ordem')) class Meta: app_label = "ferramentas" verbose_name = _('Ajuda') verbose_name_plural = _('Ajuda') ordering = ['ordem'] def __unicode__(self): return u"%s" % (self.titulo) save = transaction.commit_on_success(models.Model.save)
def post(self, request, *args, **kwargs): action = request.POST.get('action') source = request.POST.get('source') error_ids = [] prefix = 'PillowError_' prefix_len = len(prefix) for p in request.POST: if p.startswith(prefix): error_ids.append(p[prefix_len:]) redirect_url = None error_list_url = reverse('admin_report_dispatcher', args=('pillow_errors', )) if not action or action not in ACTIONS: messages.error( self.request, _("Unknown action: '%(action)s'") % {'action': action}) elif not error_ids: messages.error(self.request, _("No error records specified")) elif action == ACTION_SEND and not len(error_ids) == 1: messages.error( self.request, _("Only one error may be sent to FogBugs at a time.")) else: with transaction.commit_on_success(): if action == ACTION_DELETE: PillowError.objects.filter(id__in=error_ids).delete() elif action == ACTION_RESET: PillowError.objects.filter(id__in=error_ids).\ update(current_attempt=0, date_next_attempt=datetime.utcnow()) elif action == ACTION_SEND: self.bug_report(request.couch_user, error_ids[0]) success = _("%(num)s records successfully %(action)s") % { 'num': len(error_ids), 'action': action } messages.success(self.request, success) if source == SOURCE_SINGLE and action == ACTION_DELETE: redirect_url = error_list_url redirect_url = redirect_url or request.META.get( 'HTTP_REFERER', error_list_url) return redirect(redirect_url)
def import_keys(keyring): outdata = call_gpg(keyring, "--list-sigs") keydata = parse_keydata(outdata) logger.info("creating or finding %d keys", len(keydata)) created_ct = updated_ct = 0 with transaction.commit_on_success(): finder = UserFinder() # we are dependent on parents coming before children; parse_keydata # uses an OrderedDict to ensure this is the case. for data in keydata.values(): parent_id = None if data.parent: parent_data = keydata.get(data.parent, None) if parent_data: parent_id = parent_data.db_id other = { 'expires': data.expires, 'revoked': data.revoked, 'parent_id': parent_id, } dkey, created = DeveloperKey.objects.get_or_create( key=data.key, created=data.created, defaults=other) data.db_id = dkey.id # set or update any additional data we might need to needs_save = False if created: created_ct += 1 else: for k, v in other.items(): if getattr(dkey, k) != v: setattr(dkey, k, v) needs_save = True if dkey.owner_id is None: owner = find_key_owner(data, keydata, finder) if owner is not None: dkey.owner = owner needs_save = True if needs_save: dkey.save() updated_ct += 1 key_ct = DeveloperKey.objects.all().count() logger.info("%d total keys in database", key_ct) logger.info("created %d, updated %d keys", created_ct, updated_ct)
def setup(self): from bambu_cron.models import Job with transaction.commit_on_success(): for handler in self._registry.values(): next = handler.next_run_date() if not Job.objects.filter(name=handler).exists(): Job.objects.create(name=handler, next_run=next) else: Job.objects.filter( name=handler).select_for_update().update(next_run=next) self.logger.info('%s set to run on %s' % (handler, next.strftime('%c %z'))) Job.objects.exclude(name__in=[str(n) for n in self._registry]).delete()
def handle(self, *args, **options): with transaction.commit_on_success(): sandbox = Sandbox() test = sandbox.create_user('test', 'Test User') subject = sandbox.create_subject( short_name=options['subject_shortname'], long_name=options['subject_longname']) period = sandbox.create_period(subject, short_name='fall2012', long_name='Fall 2012') if options['subjectadmin']: subject.admins.add(test) else: period.admins.add(test)
def handle(self, *args, **options): from_site = options.get('from_site', None) to_site = options.get('to_site', None) if not from_site or not to_site: raise CommandError("You must use --from and --to to use this command.") self.get_site(from_site) site = self.get_site(to_site) pages = Page.objects.filter(site=from_site, level=0) with transaction.commit_on_success(): for page in pages: page.copy_page(None, site) Page.objects.filter(site=to_site).update(published=True) self.stdout.write("Copied CMS Tree from SITE_ID {0} successfully to SITE_ID {1}.\n".format(from_site, to_site))