Python perform update
30 Python code examples are found related to "
perform update".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: api.py From linkedevents with MIT License | 6 votes |
def perform_update(self, serializer): # Prevent changing an event that user does not have write permissions # For bulk update, the editable queryset is filtered in filter_queryset # method if isinstance(serializer, EventSerializer) and not self.request.user.can_edit_event( serializer.instance.publisher, serializer.instance.publication_status, ): raise DRFPermissionDenied() # Prevent changing existing events to a state that user doe snot have write permissions if isinstance(serializer.validated_data, list): event_data_list = serializer.validated_data else: event_data_list = [serializer.validated_data] for event_data in event_data_list: org = self.organization if hasattr(event_data, 'publisher'): org = event_data['publisher'] if not self.request.user.can_edit_event(org, event_data['publication_status']): raise DRFPermissionDenied() super().perform_update(serializer)
Example 2
Source File: views.py From CTF_AWD_Platform with MIT License | 6 votes |
def perform_update(self, serializer): # 判断题目并汇总分数 -- ok UserChoiceIn = serializer.instance competition = UserChoiceIn.competition team = UserChoiceIn.team user = UserChoiceIn.user choice_submit_queryset = CompetitionChoiceSubmit.objects.filter(competition=competition,team=team,user=user) score = 0 for _ in choice_submit_queryset: if _.true_result == _.submit_result: _.result = True score += _.score else: _.result = False _.save() UserChoiceIn.score = score return serializer.save()
Example 3
Source File: alarm_clock_views.py From piclodio3 with MIT License | 6 votes |
def perform_update(self, serializer): instance = serializer.save() from utils.scheduler_manager import SchedulerManager scheduler_manager = SchedulerManager() if instance.enabled: # delete first scheduler_manager.delete_job_by_id(instance.id) # then create back to update scheduler_manager.add_new_job(job_id=instance.id, day_of_week_string=instance.get_day_of_week(), hour=instance.hour, minute=instance.minute, url=instance.webradio.url, auto_stop_minutes=instance.auto_stop_minutes) else: scheduler_manager.delete_job_by_id(instance.id)
Example 4
Source File: collection.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
def perform_update(self, serializer, *args, **kwargs): """ Only the owner is allowed to change `discoverable_when_public` """ original_collection = self.get_object() if (self.request.user != original_collection.owner and 'discoverable_when_public' in serializer.validated_data and (serializer.validated_data['discoverable_when_public'] != original_collection.discoverable_when_public)): raise exceptions.PermissionDenied() # Some fields shouldn't affect the modification date FIELDS_NOT_AFFECTING_MODIFICATION_DATE = {'discoverable_when_public'} changed_fields = set() for k, v in serializer.validated_data.items(): if getattr(original_collection, k) != v: changed_fields.add(k) if changed_fields.issubset(FIELDS_NOT_AFFECTING_MODIFICATION_DATE): with disable_auto_field_update(Collection, 'date_modified'): return super().perform_update( serializer, *args, **kwargs) return super().perform_update(serializer, *args, **kwargs)
Example 5
Source File: updater.py From redeem with GNU General Public License v3.0 | 6 votes |
def perform_git_update(): print("Perform git update") command = ["git", "pull"] with open(os.devnull, 'wb') as hide_output: try: p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=hide_output) except: print("Error running \"git pull\"") stdout = p.communicate()[0].strip() if PY3: stdout = stdout.decode() exit_code = p.returncode if exit_code != 0: print("\"git pull\" failed with return code %d" % (p.returncode)) print(stdout) return exit_code == 0
Example 6
Source File: rest_framework.py From fcm-django with MIT License | 5 votes |
def perform_update(self, serializer): if is_user_authenticated(self.request.user): if (SETTINGS["ONE_DEVICE_PER_USER"] and self.request.data.get('active', False)): FCMDevice.objects.filter(user=self.request.user).update( active=False) return serializer.save(user=self.request.user) return serializer.save()
Example 7
Source File: common_db.py From shipyard with Apache License 2.0 | 5 votes |
def perform_update(self, query, **kwargs): """ Performs a parameterized update """ return self.perform_change_dml(query, **kwargs)
Example 8
Source File: api.py From teamvault with GNU General Public License v3.0 | 5 votes |
def perform_update(self, serializer): instance = serializer.save() if hasattr(instance, '_data'): instance.set_data(self.request.user, instance._data) del instance._data
Example 9
Source File: views.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def perform_update(self, serializer): existed_record = ShoppingCart.objects.get(id=serializer.instance.id) existed_nums = existed_record.nums # 先保存之前的数据existed_nums saved_record = serializer.save() # 变化的数量 nums = saved_record.nums - existed_nums goods = saved_record.goods goods.stock -= nums goods.save()
Example 10
Source File: paren_matcher.py From thonny with MIT License | 5 votes |
def perform_update(self): try: self.update_highlighting() finally: self._update_scheduled = False
Example 11
Source File: viewsets.py From product-definition-center with MIT License | 5 votes |
def perform_update(self, serializer): super(NotificationMixin, self).perform_update(serializer) if self.initial_status != serializer.data: self._send_message('changed', {'old_value': self.initial_status, 'new_value': serializer.data}, obj=serializer.instance)
Example 12
Source File: api.py From diting with GNU General Public License v2.0 | 5 votes |
def perform_update(self, serializer): # Note: we are not updating the user object here. # We just do the reset-password stuff. import uuid from .utils import send_reset_password_mail user = self.get_object() user.password_raw = str(uuid.uuid4()) user.save() send_reset_password_mail(user)
Example 13
Source File: views.py From ChRIS_ultron_backEnd with MIT License | 5 votes |
def perform_update(self, serializer): """ Overriden to cancel this plugin instance and all its descendants' execution . """ if 'status' in self.request.data: instance = self.get_object() descendants = instance.get_descendant_instances() for inst in descendants: inst.cancel() super(PluginInstanceDetail, self).perform_update(serializer)
Example 14
Source File: scans.py From ws-backend-community with GNU General Public License v3.0 | 5 votes |
def perform_update(self, serializer): if self.scan_config.is_default and not self.request.user.is_superuser: raise PermissionDenied() elif hasattr(self.scan_config, "organization") \ and self.request.user not in self.scan_config.organization.admin_group.users.all() \ and not self.request.user.is_superuser: raise PermissionDenied( "You do not have administrative permissions for the scanning configuration's organization." ) elif not self.scan_config.can_be_modified: raise PermissionDenied("That scan configuration cannot be modified.") else: return super(ScanConfigDetailView, self).perform_update(serializer)
Example 15
Source File: views.py From guacozy with MIT License | 5 votes |
def perform_update(self, serializer): allowed_to_view_folders = user_allowed_folders_ids(self.request.user, require_view_permission=True) allowed_to_view_folders_ids = user_allowed_folders_ids(self.request.user, require_view_permission=True) if serializer.instance.id not in allowed_to_view_folders_ids: raise PermissionDenied(detail="You are not allowed to update this folder") if 'parent' in serializer.validated_data and serializer.validated_data['parent'].id not in allowed_to_view_folders_ids: raise PermissionDenied(detail="You are not allowed to move folder here") super(FolderFlatViewSet, self).perform_update(serializer)
Example 16
Source File: updater.py From redeem with GNU General Public License v3.0 | 5 votes |
def perform_update(): service_name = switch_to_source_directory() service_was_running = is_service_running(service_name) if service_was_running: stop_service(service_name) perform_git_update() reinstall(service_name) if service_was_running: start_service(service_name) print("Update of %s complete" % (service_name))
Example 17
Source File: views.py From cookiecutter-django-vue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def perform_update(self, serializer): user = serializer.save() if 'password' in self.request.data: user.set_password(self.request.data.get('password')) user.save()
Example 18
Source File: model_anonymizers.py From django-GDPR with MIT License | 5 votes |
def perform_update_with_version(self, obj: Model, updated_data: Dict[str, Any], updated_version_data: List[Tuple[Any, Dict]], legal_reason: Optional[LegalReason] = None, anonymization: bool = True): with transaction.atomic(): # first we need to update versions for version, version_dict in updated_version_data: self._perform_version_update(version, version_dict) self._perform_update(obj, updated_data, legal_reason, anonymization=anonymization)
Example 19
Source File: views.py From djoser with MIT License | 5 votes |
def perform_update(self, serializer): super().perform_update(serializer) user = serializer.instance # should we send activation email after update? if settings.SEND_ACTIVATION_EMAIL: context = {"user": user} to = [get_user_email(user)] settings.EMAIL.activation(self.request, context).send(to)
Example 20
Source File: CreditTrade.py From tfrs with Apache License 2.0 | 5 votes |
def perform_update(self, serializer): previous_state = self.get_object() credit_trade = serializer.save() CreditTradeService.create_history(credit_trade, False) status_cancelled = CreditTradeStatus.objects.get(status="Cancelled") if serializer.data['status'] != status_cancelled.id: CreditTradeService.dispatch_notifications( previous_state, credit_trade)
Example 21
Source File: api.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def perform_update(self, serializer): instance = self.get_object() current_email, current_phone = instance.email, instance.phone new_email = serializer.validated_data.get('email', instance.email) new_phone = serializer.validated_data.get('phone', instance.phone) user = serializer.save() if current_email != new_email: instance.emailaddress_set.all().delete() if new_email: send_email_confirmation(self.request._request, user) if current_email: user.email = current_email utils.send_email_update_notification(current_email) if current_phone != new_phone: instance.verificationdevice_set.all().delete() if new_phone: device = VerificationDevice.objects.create( user=instance, unverified_phone=new_phone) device.generate_challenge() if current_phone: user.phone = current_phone utils.send_sms(current_phone, messages.phone_change) user.save()
Example 22
Source File: views.py From lego with MIT License | 5 votes |
def perform_update(self, serializer): """ We set the is_ready flag on update to lock the event for bumping waiting registrations. This is_ready flag is set to True when the bumping is finished """ serializer.save(is_ready=False)
Example 23
Source File: views.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def perform_update(self, serializer): """ When a new user registers, initiate email verification. """ instance = serializer.save() verify_user_emails(instance.user, instance.user.email)
Example 24
Source File: views.py From django-radio with GNU General Public License v3.0 | 5 votes |
def perform_update(self, serializer): schedule = serializer.instance start = serializer.validated_data['start'] new_start = serializer.validated_data['new_start'] if start == new_start: return schedule_excluded = Schedule.get_schedule_which_excluded_dt(schedule.programme, new_start) if schedule_excluded: # Including the date that was excluded schedule_excluded.include_date(new_start) schedule_excluded.save() if schedule.id == schedule_excluded.id: # Case when a transmission is moved from one day to other but is still part of the same schedule # The object is the same, using schedule_excluded to avoid overriding changes! schedule_excluded.exclude_date(start) schedule_excluded.save() elif schedule.has_recurrences(): # The schedule has other recurrences excluding only that date (it could be deleted) schedule.exclude_date(start) schedule.save() else: # Case when the previous schedule is not necessary schedule.delete() else: if schedule.has_recurrences(): schedule.exclude_date(start) schedule.save() new_schedule = Schedule.objects.get(id=schedule.id) new_schedule.id = new_schedule.pk = None new_schedule.from_collection = schedule new_schedule.recurrences = Recurrence() new_schedule.start_dt = new_start new_schedule.save() else: schedule.start_dt = new_start schedule.save()
Example 25
Source File: aws.py From flocker with Apache License 2.0 | 5 votes |
def perform_update_s3_error_page(dispatcher, intent): """ See :class:`UpdateS3ErrorPage`. """ s3 = boto.connect_s3() bucket = s3.get_bucket(intent.bucket) config = bucket.get_website_configuration_obj() new_error_key = intent.error_key old_error_key = config.error_key if old_error_key == new_error_key: return None else: config.error_key = new_error_key bucket.set_website_configuration(config) return old_error_key
Example 26
Source File: aws.py From flocker with Apache License 2.0 | 5 votes |
def perform_update_s3_routing_rules(dispatcher, intent): """ See :class:`UpdateS3RoutingRule`. """ s3 = boto.connect_s3() bucket = s3.get_bucket(intent.bucket) config = bucket.get_website_configuration_obj() config.routing_rules = intent.routing_rules bucket.set_website_configuration(config)
Example 27
Source File: viewsets.py From nefarious with GNU General Public License v3.0 | 5 votes |
def perform_update(self, serializer): instance = self.get_object() # type: WatchTVShow # set the auto watch date to now if it was toggled on if not instance.auto_watch and serializer.validated_data.get('auto_watch'): serializer.validated_data['auto_watch_date_updated'] = datetime.utcnow().date() super().perform_update(serializer)
Example 28
Source File: updater.py From lepidopter with GNU General Public License v3.0 | 4 votes |
def perform_update(version, skip_verification=False): try: updater = get_request(UPDATE_BASE_URL + "{0}/update.py".format(version)) updater_path = os.path.join(UPDATER_PATH, "update-{0}.py".format(version)) except RequestFailed: logging.error("Failed to download update file") raise UpdateFailed if skip_verification is not True: try: updater_sig = get_request(UPDATE_BASE_URL + "{0}/update.py.asc".format(version)) updater_sig_path = os.path.join(UPDATER_PATH, "update-{0}.py.asc".format(version)) except RequestFailed: logging.error("Failed to download update file") raise UpdateFailed with open(updater_path, "w+") as out_file: out_file.write(updater) if skip_verification is not True: with open(updater_sig_path, "w+") as out_file: out_file.write(updater_sig) if skip_verification is not True: try: verify_file(updater_sig_path, updater_path, PUBLIC_KEY_PATH) except InvalidSignature: logging.error("Found an invalid signature. Bailing") raise UpdateFailed updater = imp.load_source('updater_{0}'.format(version), updater_path) try: logging.info("Running install script") if updater.__version__ != str(version): logging.error("There is a version mismatch in the updater file. This could be a sign of a replay attack.") raise UpdateFailed updater.run() except Exception: logging.exception("Failed to run the version update script for version {0}".format(version)) raise UpdateFailed current_version_dir = os.path.dirname(CURRENT_VERSION_PATH) try: os.makedirs(current_version_dir) except OSError as ose: if ose.errno != errno.EEXIST: raise # Update the current version number with open(CURRENT_VERSION_PATH, "w+") as out_file: out_file.write(str(version)) logging.info("Updated to version {0}".format(version))
Example 29
Source File: __init__.py From truckersmp-cli with MIT License | 4 votes |
def perform_self_update(): """ Update files to latest release. Do nothing for Python package. This function checks the latest GitHub release first. If local version is not up-to-date, this function retrieves the latest GitHub release asset (.tar.xz) and replaces existing files with extracted files. """ # we don't update when Python package is used try: with open(os.path.join(os.path.dirname(Dir.scriptdir), "RELEASE")) as f: current_release = f.readline().rstrip() except Exception: sys.exit("'RELEASE' file doesn't exist. Self update aborted.") # get latest release logging.info("Retrieving RELEASE from master") try: with urllib.request.urlopen(URL.release) as f: release = f.readline().rstrip().decode("ascii") except Exception as e: sys.exit("Failed to retrieve RELEASE file: {}".format(e)) # do nothing if the installed version is latest if release == current_release: logging.info("Already up-to-date.") return # retrieve the release asset archive_url = URL.rel_tarxz_tmpl.format(release) logging.info("Retrieving release asset {}".format(archive_url)) try: with urllib.request.urlopen(archive_url) as f: asset_archive = f.read() except Exception as e: sys.exit("Failed to retrieve release asset file: {}".format(e)) # unpack the archive logging.info("Unpacking archive {}".format(archive_url)) topdir = os.path.dirname(Dir.scriptdir) try: with tarfile.open(fileobj=io.BytesIO(asset_archive), mode="r:xz") as f: f.extractall(topdir) except Exception as e: sys.exit("Failed to unpack release asset file: {}".format(e)) # update files archive_dir = os.path.join(topdir, "truckersmp-cli-" + release) for root, _dirs, files in os.walk(archive_dir, topdown=False): inner_root = root[len(archive_dir):] destdir = topdir + inner_root logging.debug("Creating directory {}".format(destdir)) os.makedirs(destdir, exist_ok=True) for f in files: srcpath = os.path.join(root, f) dstpath = os.path.join(destdir, f) logging.info("Copying {} as {}".format(srcpath, dstpath)) os.replace(srcpath, dstpath) os.rmdir(root) # done logging.info("Self update complete")
Example 30
Source File: PolyMesh.py From laplacian-meshes with GNU General Public License v3.0 | 4 votes |
def performDisplayUpdate(self, buffersOnly = False): #Clear the buffers for the invalidated mesh if self.VPosVBO: self.VPosVBO.delete() if self.VNormalsVBO: self.VNormalsVBO.delete() if self.VColorsVBO: self.VColorsVBO.delete() if self.VTexCoordsVBO: self.VTexCoordsVBO.delete() if self.IndexVBO: self.IndexVBO.delete() if self.EdgeLinesVBO: self.EdgeLinesVBO.delete() if self.VNormalLinesVBO: self.VNormalLinesVBO.delete() if self.FNormalLinesVBO: self.FNormalLinesVBO.delete() self.VPosVBO = vbo.VBO(np.array(self.VPos, dtype=np.float32)) self.VColorsVBO = vbo.VBO(np.array(self.VColors, dtype=np.float32)) self.VTexCoordsVBO = vbo.VBO(np.array(self.VTexCoords, dtype=np.float32)) if not buffersOnly: self.updateTris() self.IndexVBO = vbo.VBO(self.ITris, target=GL_ELEMENT_ARRAY_BUFFER) #Update edges buffer if buffersOnly: #Use triangle faces to add edges (will be redundancy but is faster #tradeoff for rendering only) NTris = self.ITris.shape[0] self.EdgeLines = np.zeros((NTris*3*2, 3)) for k in range(3): istart = k*NTris*2 self.EdgeLines[istart:istart+NTris*2:2, :] = self.VPos[self.ITris[:, k], :] self.EdgeLines[istart+1:istart+NTris*2:2, :] = self.VPos[self.ITris[:, (k+1)%3], :] else: #Use the mesh structure to find the edges self.EdgeLines = np.zeros((len(self.edges)*2, 3)) for i in range(len(self.edges)): self.EdgeLines[i*2, :] = self.VPos[self.edges[i].v1.ID, :] self.EdgeLines[i*2+1, :] = self.VPos[self.edges[i].v2.ID, :] self.EdgeLinesVBO = vbo.VBO(np.array(self.EdgeLines, dtype=np.float32)) #Update face and vertex normals scale = 0.01*self.getBBox().getDiagLength() self.updateNormalBuffer() self.VNormalsVBO = vbo.VBO(np.array(self.VNormals, dtype=np.float32)) VNList = np.zeros((self.VPos.shape[0]*2, 3)) VNList[np.arange(0, VNList.shape[0], 2), :] = self.VPos VNList[np.arange(1, VNList.shape[0], 2), :] = self.VPos + scale*self.VNormals self.VNormalLinesVBO = vbo.VBO(np.array(VNList, dtype=np.float32)) VFList = np.zeros((self.ITris.shape[0]*2, 3)) VFList[np.arange(0, VFList.shape[0], 2), :] = self.FCentroid VFList[np.arange(1, VFList.shape[0], 2), :] = self.FCentroid + scale*self.FNormals self.FNormalLinesVBO = vbo.VBO(np.array(VFList, dtype=np.float32)) self.needsDisplayUpdate = False #vertexColors is an Nx3 numpy array, where N is the number of vertices