def getStatusApp(self, data): language = data.get('locale') or 'en' translation.activate(language) status_code = constant.APP_EXE_STATUS_FAIL message = '' operationSetting = None computer_info = data['computer_info'] # Get activation to check try: activation = self.activationServices.getActivationByKey(data['activate_status_info']['id']) except (ObjectDoesNotExist, ValueError) as error: print(translation.ugettext('Activation not found')) raise ObjectDoesNotExist(translation.ugettext('Activation not found')) # Check expirate of license currentDate = datetime.utcnow().replace(tzinfo=pytz.utc) exe_status_expiration = datetime(1900, 1, 1, tzinfo=timezone.utc) exe_temp = self.getExecutionStatusByActivation(activation, currentDate) if len(exe_temp) > 0: raise ObjectDoesNotExist(translation.ugettext('Activation has been used')) license = activation.license # Check license is delete if license is None or license.is_deleted is True or license.pause is True: raise ObjectDoesNotExist(translation.ugettext('License not found or paused')) # Check the license and the licenses access if license.license_expiration > currentDate: list_status_app = self.getNumberOfActiveStatusApp(license, currentDate) if (len(list_status_app) < (license.start_app_num or 0)): # check MAC_ADDRESS countErr = 0 fieldErr = [] if activation.pc_name != data['computer_info']['name']: countErr += 1 fieldErr.append(translation.ugettext('pc name')) if activation.windows_product_id != data['computer_info']['windows_product_id']: countErr += 1 fieldErr.append(translation.ugettext('windows product ID')) if activation.mac_address != data['computer_info']['mac_address']: countErr += 1 fieldErr.append(translation.ugettext('mac address')) if activation.drive_serial_number != data['computer_info']['drive_serial_number']: countErr += 1 fieldErr.append(translation.ugettext('drive serial number')) # If the 3 fields match, it will be successful if countErr < 3: # set status status_code = constant.APP_EXE_STATUS_SUCCESS # return success message = translation.ugettext('Start the application successfully') # get operationSetting of product operationSetting = self.operationSettingServices.getOperationSettingByProduct(license.product) if operationSetting is None: raise ObjectDoesNotExist(translation.ugettext('OperationSetting not found')) exe_status_expiration = currentDate + timedelta(seconds=(operationSetting.status_valid_seconds or 0)) else: message = (translation.ugettext("The {} is not used correctly with the registered one at Activation")).format(','.join(fieldErr)) else: message = translation.ugettext('The number of license is limited') print(message) else: message = translation.ugettext('The license of products is expired') # Insert always execute executionStatus = ExecutionStatus.objects.create_status( activation=activation, app_exe_status_key=str(uuid.uuid4())[:6], status_code=status_code, exe_status_expiration=exe_status_expiration ) return executionStatus,message,operationSetting
def delete(self, *args, **kwargs): if not self.pk: raise ObjectDoesNotExist( 'Object must be created before it can be deleted') self.deleted = timezone.now() return super(StoreDeleted, self).save(*args, **kwargs)
def _createReport(exp, eas, resultsName, doThumbnail, previousReport): ''' create Result and related objects ''' loc = exp.location() if not loc: raise ObjectDoesNotExist("There are no Location objects, at all.") # error out if cmdline args are missing if not eas.have_args(thumbnail=doThumbnail): raise Exception( "Analysis cannot start because of missing Command Line Args.") # Always use the default ReportStorage object storage = models.ReportStorage.objects.filter(default=True)[0] try: with transaction.atomic(): result = build_result(exp, resultsName, storage, loc, doThumbnail) # Don't allow EAS to be edited once analysis has started if eas.isEditable: eas.isEditable = False eas.save() result.eas = eas result.reference = eas.reference # attach project(s) projectNames = get_project_names(exp) for name in projectNames.split(','): if name: try: p = models.Project.objects.get(name=name) except models.Project.DoesNotExist: p = models.Project() p.name = name p.creator = models.User.objects.get( username='******') p.save() models.EventLog.objects.add_entry( p, "Created project name= %s during report creation." % p.name, 'ionadmin') result.projects.add(p) result.save() # handle from-Basecalling reAnalysis if previousReport: parent_obj = None try: selected_previous_pk = int( previousReport.strip('/').split('_')[-1]) parent_obj = models.Results.objects.get( pk=selected_previous_pk) except: # TorrentSuiteCloud plugin 3.4.2 uses reportName for this value try: parent_obj = models.Results.objects.get( resultsName=os.path.basename(previousReport)) except: pass if parent_obj: result.parentResult = parent_obj result.save() # replace dmfilestat dmfilestat = parent_obj.get_filestat(dmactions_types.BASE) result.dmfilestat_set.filter( dmfileset__type=dmactions_types.BASE).delete() dmfilestat.pk = None dmfilestat.result = result dmfilestat.save() return result except Exception as e: logger.exception("Aborted createReport for result %d: '%s'", result.pk, e) raise
def delete_post(post_id): try: post = Post.objects.get(pk=post_id) post.delete() except ObjectDoesNotExist: raise ObjectDoesNotExist('Post Not Found')
def _deleted(self, *args, **kwargs): """ Scrambling method for already deleted objects """ raise ObjectDoesNotExist("This object was already deleted!")
def get_item(self, pk, **kwargs): try: return dict((i.id, i) for i in self._items)[int(pk)] except KeyError: raise ObjectDoesNotExist()
def obj_get_info(self, request, **kwargs): _data = self._meta.rinor_pipe.get_info_extended() if not (_data): raise ObjectDoesNotExist() return _data
def delete_resource_file(pk, filename_or_id, user, delete_logical_file=True): """ Deletes an individual file from a HydroShare resource. If the file does not exist, the Exceptions.NotFound exception is raised. REST URL: DELETE /resource/{pid}/files/{filename} Parameters: :param pk: The unique HydroShare identifier for the resource from which the file will be deleted :param filename_or_id: Name of the file or id of the file to be deleted from the resource :param user: requesting user :param delete_logical_file: If True then if the ResourceFile object to be deleted is part of a LogicalFile object then the LogicalFile object will be deleted which deletes all associated ResourceFile objects and file type metadata objects. :returns: The name or id of the file which was deleted Return Type: string or integer Raises: Exceptions.NotAuthorized - The user is not authorized Exceptions.NotFound - The resource identified by pid does not exist or the file identified by file does not exist Exception.ServiceFailure - The service is unable to process the request Note: This does not handle immutability as previously intended. """ resource = utils.get_resource_by_shortkey(pk) res_cls = resource.__class__ for f in ResourceFile.objects.filter(object_id=resource.id): if filter_condition(filename_or_id, f): if delete_logical_file: if f.has_logical_file and not f.logical_file.is_fileset: # delete logical file if any resource file that belongs to logical file # gets deleted for any logical file other than fileset logical file # logical_delete() calls this function (delete_resource_file()) # to delete each of its contained ResourceFile objects f.logical_file.logical_delete(user) return filename_or_id signals.pre_delete_file_from_resource.send(sender=res_cls, file=f, resource=resource, user=user) file_name = delete_resource_file_only(resource, f) # This presumes that the file is no longer in django delete_format_metadata_after_delete_file(resource, file_name) signals.post_delete_file_from_resource.send(sender=res_cls, resource=resource) # set to private if necessary -- AFTER post_delete_file handling resource.update_public_and_discoverable( ) # set to False if necessary # generate bag utils.resource_modified(resource, user, overwrite_bag=False) return filename_or_id # if execution gets here, file was not found raise ObjectDoesNotExist( str.format("resource {}, file {} not found", resource.short_id, filename_or_id))
def handle(self, *args, **options): try: page = FacePage.objects.first() fb = FaceBot(page.page_id) except AttributeError: raise ObjectDoesNotExist('No facebook pages found. Run the create_page command first.') if options['date']: try: datetime.datetime.strptime(options['date'], '%Y-%m-%d') posts = fb.get_posts(options['date']) except ValueError: raise ValueError('Date should be in the format YYYY-MM-DD') elif options['latest']: latest_date = PagePost.objects.latest('created_time') posts = fb.get_posts(latest_date) else: posts = fb.get_posts() for post in posts: page_post, created = PagePost.objects.get_or_create( page_post_id=post['id'], defaults={'created_time': post['created_time'], 'message': post.get('message')} ) if created: if post.get('full_picture'): r = requests.get(post['full_picture']) if r.status_code == requests.codes.ok: img_content = ContentFile(r.content) full_img_id = post.get('object_id', post['id'].split('_')[1]) image = TimelineImage(post=page_post, timeline_image_id=full_img_id, created_time=post['created_time']) image.image.save(f'{full_img_id}_full.jpg', img_content) image.save() if post.get('attachments'): subattachments = post['attachments']['data'][0]['subattachments']['data'] for attachment in subattachments: if attachment['type'] == 'photo': r = requests.get(attachment['media']['image']['src']) if r.status_code == requests.codes.ok: img_content = ContentFile(r.content) image_id = attachment['target']['id'] full_img_id = post.get('object_id', post['id'].split('_')[1]) # Only create a new image if the image id is distinct from the full picture id if image_id != full_img_id: image = TimelineImage.objects.create(post=page_post, timeline_image_id=image_id, created_time=post['created_time']) image.image.save(f'{attachment["target"]["id"]}.jpg', img_content) image.save()
def get_labels(self, user_id, annotation_id): annotation = Annotation.objects.filter(id=annotation_id).first() if annotation is None: raise ObjectDoesNotExist()
def get_newest_annotation(self, annotation_id): newest_annotation = AnnotationProgress.objects.filter( annotation_id=annotation_id).order_by('-updated_at').first() if newest_annotation is None: raise ObjectDoesNotExist() return newest_annotation
def delete_annotation(self, annotation_id): annotation = Annotation.objects.filter(id=annotation_id).first() if annotation.delete_flag is True: raise ObjectDoesNotExist() annotation.delete_flag = True annotation.save()
def get_object(self, request, *args, **kwargs): try: return Category.objects.get(pk=kwargs["pk"]) except Category.DoesNotExist: raise ObjectDoesNotExist("Нет такой категории!")
def _validate_asset_type(self, resource_type, content_type, provided_as, metadata): if not resource_type and metadata: raise ValueError( 'You have to specify a valid asset type for providing meta data' ) if not resource_type: return plugins = ResourcePlugin.objects.filter(name=resource_type) if not len(plugins): raise ObjectDoesNotExist('The asset type ' + resource_type + ' does not exists') asset_type = plugins[0] # Validate content type if len(asset_type.media_types ) and content_type not in asset_type.media_types: raise ValueError('The content type ' + content_type + ' is not valid for the specified asset type') # Validate providing method if provided_as not in asset_type.formats: raise ValueError( 'The format used for providing the digital asset (' + provided_as + ') is not valid for the given asset type') # Validate that the included metadata is valid according to the form field if metadata and not asset_type.form: raise ValueError( 'The specified asset type does not allow meta data') if asset_type.form: for k, v in asset_type.form.items(): # Validate mandatory fields if 'mandatory' in v and v[ 'mandatory'] and 'default' not in v and k not in metadata: raise ValueError('Missing mandatory field ' + k + ' in metadata') # Validate metadata types if k in metadata and v['type'] != 'checkbox' and not ( isinstance(metadata[k], str)): raise TypeError('Metadata field ' + k + ' must be a string') if k in metadata and v['type'] == 'checkbox' and not isinstance( metadata[k], bool): raise TypeError('Metadata field ' + k + ' must be a boolean') if k in metadata and v['type'] == 'select' and metadata[ k].lower() not in [ option['value'].lower() for option in v['options'] ]: raise ValueError( 'Metadata field ' + k + ' value is not one of the available options') # Include default values if k not in metadata and 'default' in v: metadata[k] = v['default']
def object_does_not_exist(doc_type, doc_id): """ Builds a 404 error message with standard, translated, verbiage """ return ObjectDoesNotExist(_("Could not find %(doc_type)s with id %(id)s") % \ {"doc_type": doc_type, "id": doc_id})
def get_object(self): person = Person.objects.filter(user=self.request.user).first() if not person: raise ObjectDoesNotExist('Your profile does not exist') return person
def get_repo_blob(repo, full_name, commit_sha, allow_tree=True): # type: (Repo_ish, Text, bytes, bool) -> dulwich.Blob """ :arg full_name: A Unicode string indicating the file name. :arg commit_sha: A byte string containing the commit hash :arg allow_tree: Allow the resulting object to be a directory """ dul_repo, full_name = get_true_repo_and_path(repo, full_name) # https://github.com/inducer/relate/pull/556 names = os.path.normpath(full_name).split(os.sep) # Allow non-ASCII file name full_name_bytes = full_name.encode('utf-8') try: tree_sha = dul_repo[commit_sha].tree except KeyError: raise ObjectDoesNotExist( _("commit sha '%s' not found") % commit_sha.decode()) tree = dul_repo[tree_sha] def access_directory_content(maybe_tree, name): # type: (Any, Text) -> Any try: mode_and_blob_sha = maybe_tree[name.encode()] except TypeError: raise ObjectDoesNotExist( _("resource '%s' is a file, " "not a directory") % full_name) mode, blob_sha = mode_and_blob_sha return mode_and_blob_sha if not full_name_bytes: if allow_tree: return tree else: raise ObjectDoesNotExist(_("repo root is a directory, not a file")) try: for name in names[:-1]: if not name: # tolerate empty path components (begrudgingly) continue mode, blob_sha = access_directory_content(tree, name) tree = dul_repo[blob_sha] mode, blob_sha = access_directory_content(tree, names[-1]) result = dul_repo[blob_sha] if not allow_tree and not hasattr(result, "data"): raise ObjectDoesNotExist( _("resource '%s' is a directory, not a file") % full_name) return result except KeyError: raise ObjectDoesNotExist(_("resource '%s' not found") % full_name)
def obj_get(self, bundle, **kwargs): if 'pk' in kwargs: raise ObjectDoesNotExist() return provide_route_configuration()
def obj_get(self, request, **kwargs): _data = self._meta.rinor_pipe.get_detail(kwargs['hostname'], kwargs['id'], kwargs['key']) if not (_data): raise ObjectDoesNotExist() return _data
def site(request,site_id): current_user = request.user profile =Profile.objects.get(username=current_user) try: project = Project.objects.get(id=site_id) except: raise ObjectDoesNotExist() try: ratings = Rating.objects.filter(project_id=site_id) design = Rating.objects.filter(project_id=site_id).values_list('design',flat=True) usability = Rating.objects.filter(project_id=site_id).values_list('usability',flat=True) creativity = Rating.objects.filter(project_id=site_id).values_list('creativity',flat=True) content = Rating.objects.filter(project_id=site_id).values_list('content',flat=True) total_design=0 total_usability=0 total_creativity=0 total_content = 0 print(design) for rate in design: total_design+=rate print(total_design) for rate in usability: total_usability+=rate print(total_usability) for rate in creativity: total_creativity+=rate print(total_creativity) for rate in content: total_content+=rate print(total_content) overall_score=(total_design+total_content+total_usability+total_creativity)/4 print(overall_score) project.design = total_design project.usability = total_usability project.creativity = total_creativity project.content = total_content project.overall_score = overall_score project.save() except: return None if request.method =='POST': form = RatingForm(request.POST,request.FILES) if form.is_valid(): rating = form.save(commit=False) rating.project= project rating.profile = profile rating.overall_score = (rating.design+rating.usability+rating.creativity+rating.content)/2 rating.save() else: form = RatingForm() return render(request,"site.html",{"project":project,"profile":profile,"ratings":ratings,"form":form})
def obj_get_last(self, request, **kwargs): _data = self._meta.rinor_pipe.get_last(kwargs['last'], kwargs['feature']) if not (_data): raise ObjectDoesNotExist() return _data
def existsByUsername(self, usuario): try: return Usuario.objects.get(pk=usuario.get("id")) except Usuario.DoesNotExist: raise ObjectDoesNotExist("Usuario não existe! Cadastre-se!")
def send_invitation_email(request): if request.method != 'POST': raise HttpResponseBadRequest( "Only POST requests are allowed on this endpoint.") else: data = json.loads(request.body) try: user_email = data["user_email"] channel_id = data["channel_id"] share_mode = data["share_mode"] retrieved_user = User.objects.get_or_create(email=user_email) recipient = retrieved_user[0] channel = Channel.objects.get(id=channel_id) invitation = Invitation.objects.get_or_create( invited=recipient, email=user_email, channel_id=channel_id, first_name=recipient.first_name if recipient.is_active else "Guest", last_name=recipient.last_name if recipient.is_active else " ")[0] # Handle these values separately as different users might invite the same user again invitation.share_mode = share_mode invitation.sender = invitation.sender or request.user invitation.save() ctx_dict = { 'sender': request.user, 'site': get_current_site(request), 'user': recipient, 'share_mode': _(share_mode), 'channel_id': channel_id, 'invitation_key': invitation.id, 'is_new': recipient.is_active is False, 'channel': channel.name, 'domain': request.META.get('HTTP_ORIGIN'), } subject = render_to_string( 'permissions/permissions_email_subject.txt', ctx_dict) message = render_to_string('permissions/permissions_email.txt', ctx_dict) # message_html = render_to_string('permissions/permissions_email.html', ctx_dict) recipient.email_user( subject, message, settings.DEFAULT_FROM_EMAIL, ) #html_message=message_html,) # recipient.email_user(subject, message, settings.DEFAULT_FROM_EMAIL,) except KeyError: raise ObjectDoesNotExist( "Missing attribute from data: {}".format(data)) return HttpResponse( json.dumps({ "id": invitation.pk, "invited": invitation.invited_id, "email": invitation.email, "sender": invitation.sender_id, "channel": invitation.channel_id, "first_name": invitation.first_name, "last_name": invitation.last_name, "share_mode": invitation.share_mode, }))
def handle(self, *args, **options): try: page = FacePage.objects.first() fb = FaceBot(page.page_id) except AttributeError: raise ObjectDoesNotExist( 'No facebook pages found. Run the create_page command first.') if options['date']: try: datetime.datetime.strptime(options['date'], '%Y-%m-%d') photos = fb.get_photos(options['date']) except ValueError: raise ValueError('Date should be in the format YYYY-MM-DD') elif options['latest']: latest_date = TimelineImage.objects.latest('created_time') photos = fb.get_photos(latest_date) else: photos = fb.get_photos() for photo in photos: image = TimelineImage(timeline_image_id=photo['id'], created_time=photo['created_time']) r = requests.get(photo['source']) if r.status_code == requests.codes.ok and not r.headers.get( 'x-error'): img_content = ContentFile(r.content) try: image.image.save(name=f'{photo["id"]}.jpg', content=img_content) except IntegrityError: pass post = None if photo['page_story_id']: try: post = PagePost.objects.get( page_post_id=str(photo['page_story_id'])) except PagePost.DoesNotExist: post_info = fb.get_post(photo['page_story_id']) post_info['page_post_id'] = post_info.pop('id') post = PagePost.objects.create(**post_info) image.post = post try: image.save() except IntegrityError: pass
def can_edit_all_or_fail(user, ob_ids, table_name) -> bool: """ Returns true if the user owns all the objects or if the user is a superuser or if the objects have been imported by the user. Raises an Exception if the user cannot edit the object or if the object does not exist. """ # Sanitize arguments -- can't give them to django to sanitize, # for django will quote the table name if not re.match('^[a-z_]+$', table_name): raise Exception('Invalid table name: %s' % table_name) if user.is_superuser: return True ob_ids = list(ob_ids) cursor = connection.cursor() cursor.execute( f""" SELECT user_id, count(*) FROM {table_name} t JOIN UNNEST(%(obj_ids)s::bigint[]) obj(id) ON obj.id = t.id GROUP BY user_id """, { 'obj_ids': ob_ids, }) rows = tuple(cursor.fetchall()) # Check that all ids to edit exist if rows and len(ob_ids) == sum(row[1] for row in rows): if 1 == len(rows) and rows[0][0] == user.id: return True # If more than one user, check if the request.user can edit them all In # other words, check if the set of user_id associated with ob_ids is a # subset of the user's domain (the set of user_id that the user can edit) domain = user_domain(cursor, user.id) if set(row[0] for row in rows).issubset(domain): return True # If a user imported all all objects, edit permission is granted. To # only check the nodes that aren't already allowed from above tests, # find unapproved nodes: domain_list = list(domain) cursor.execute( f""" SELECT array_agg(t.id) FROM {table_name} t JOIN UNNEST(%(obj_ids)s::bigint[]) obj(id) ON obj.id = t.id WHERE user_id <> ANY(%(user_ids)s::integer[]) """, { 'obj_ids': ob_ids, 'user_ids': domain_list, }) no_permission_ids = cursor.fetchall()[0][0] if no_permission_ids and users_have_imported_all( domain_list, no_permission_ids, table_name, cursor): return True raise PermissionError( 'User %s cannot edit all of the %s unique objects from table %s' % (user.username, len(ob_ids), table_name)) raise ObjectDoesNotExist( 'One or more of the %s unique objects were not found in table %s' % (len(ob_ids), table_name))
def create_uploaded_persons_tasks(data): """ Create persons and tasks from upload data. """ # Quick sanity check. if any([row.get('errors') for row in data]): raise InternalError('Uploaded data contains errors, cancelling upload') persons_created = [] tasks_created = [] events = set() with transaction.atomic(): for row in data: try: row_repr = ('{personal} {family} {username} <{email}>, ' '{role} at {event}').format(**row) fields = {key: row[key] for key in Person.PERSON_UPLOAD_FIELDS} fields['username'] = row['username'] if row['person_exists'] and row['existing_person_id']: # we should use existing Person p = Person.objects.get(pk=row['existing_person_id']) elif row['person_exists'] and not row['existing_person_id']: # we should use existing Person p = Person.objects.get( personal=fields['personal'], family=fields['family'], username=fields['username'], email=fields['email'], ) else: # we should create a new Person without any email provided p = Person(**fields) p.save() persons_created.append(p) if row['event'] and row['role']: e = Event.objects.get(slug=row['event']) r = Role.objects.get(name=row['role']) # if the number of learners attending the event changed, # we should update ``event.attendance`` if row['role'] == 'learner': events.add(e) t, created = Task.objects.get_or_create(person=p, event=e, role=r) if created: tasks_created.append(t) except IntegrityError as e: raise IntegrityError('{0} (for "{1}")'.format( str(e), row_repr)) except ObjectDoesNotExist as e: raise ObjectDoesNotExist('{0} (for "{1}")'.format( str(e), row_repr)) return persons_created, tasks_created
def restore(self, *args, **kwargs): if not self.pk: raise ObjectDoesNotExist( 'Object must be created before it can be restored') self.deleted = None return super(StoreDeleted, self).save(*args, **kwargs)
def get_benchmark_results(data): environment = Environment.objects.get(name=data['env']) project = Project.objects.get(name=data['proj']) executable = Executable.objects.get(name=data['exe'], project=project) branch = Branch.objects.get(name=data['branch'], project=project) benchmark = Benchmark.objects.get(name=data['ben']) number_of_revs = int(data.get('revs', 10)) baseline_commit_name = (data['base_commit'] if 'base_commit' in data else None) relative_results = (('relative' in data and data['relative'] in ['1', 'yes']) or baseline_commit_name is not None) result_query = Result.objects.filter(benchmark=benchmark).filter( environment=environment).filter(executable=executable).filter( revision__project=project).filter( revision__branch=branch).select_related("revision").order_by( '-date')[:number_of_revs] if len(result_query) == 0: raise ObjectDoesNotExist("No results were found!") result_list = [item for item in result_query] result_list.reverse() if relative_results: ref_value = result_list[0].value if baseline_commit_name is not None: baseline_env = environment baseline_proj = project baseline_exe = executable baseline_branch = branch if 'base_env' in data: baseline_env = Environment.objects.get(name=data['base_env']) if 'base_proj' in data: baseline_proj = Project.objects.get(name=data['base_proj']) if 'base_exe' in data: baseline_exe = Executable.objects.get(name=data['base_exe'], project=baseline_proj) if 'base_branch' in data: baseline_branch = Branch.objects.get(name=data['base_branch'], project=baseline_proj) base_data = Result.objects.get(benchmark=benchmark, environment=baseline_env, executable=baseline_exe, revision__project=baseline_proj, revision__branch=baseline_branch, revision__commitid=baseline_commit_name) ref_value = base_data.value if relative_results: for element in result_list: element.value = (100 * (element.value - ref_value)) / ref_value return { 'environment': environment, 'project': project, 'executable': executable, 'branch': branch, 'benchmark': benchmark, 'results': result_list, 'relative': relative_results, }
def open(username, path): """Open path for user if it exists in this data store.""" if exists(username, path): return _user_data_storage(username).open(path) else: raise ObjectDoesNotExist("File path does not exist: {}".format(path))
def updateStatusApp(self, data): # get locale from request and use to return message for client language = data.get('locale') or 'en' translation.activate(language) # set status status_code = constant.APP_EXE_STATUS_FAIL message = '' operationSetting = None currentDate = datetime.utcnow().replace(tzinfo=pytz.utc) # default exe_status_expiration exe_status_expiration = datetime(1900, 1, 1, tzinfo=timezone.utc) # Get Execution status to check try: executionStatus = self.getExecutionStatusByExecutionStatusKey(data['execution_status_info']['id']) except (ObjectDoesNotExist, ValueError) as error: raise ObjectDoesNotExist(translation.ugettext('Execution status not found')) if executionStatus.status_code == constant.APP_EXE_STATUS_FAIL: raise ObjectDoesNotExist(translation.ugettext('Execution status do not activate.')) if executionStatus.status_code == constant.RELEASE_SUCCESS : raise ObjectDoesNotExist(translation.ugettext('Execution status can not be updated because the application ended.')) # Check EXE_STATUS_EXPIRATION is active if executionStatus.exe_status_expiration < currentDate: raise ObjectDoesNotExist(translation.ugettext('Execution status is expired')) # get license license = executionStatus.activation.license # Check license is delete if license is None or license.is_deleted is True or license.pause is True: raise ObjectDoesNotExist(translation.ugettext('License not found or paused')) # Check the expired license if license.license_expiration > currentDate: # if the number of starting App <= the number of limit then App is accessed list_status_app = self.getNumberOfActiveStatusApp(license, currentDate) if (len(list_status_app) <= (license.start_app_num or 0)): status_code = constant.APP_EXE_STATUS_SUCCESS message = translation.ugettext('Update the application successfully') # get operationSetting of product operationSetting = self.operationSettingServices.getOperationSettingByProduct(license.product) if operationSetting is None: raise ObjectDoesNotExist(translation.ugettext('OperationSetting status not found')) exe_status_expiration = currentDate + timedelta(seconds=(operationSetting.status_valid_seconds or 0)) else: message = translation.ugettext('The number of license is limited') else: message = translation.ugettext('The license of products is expired') # update app_exe_status if data['execution_status_id_reflesh'] == True: executionStatus.app_exe_status_key = str(uuid.uuid4())[:6] executionStatus.exe_status_expiration=exe_status_expiration executionStatus.status_code=status_code else: # executionStatus.exe_status_expiration=exe_status_expiration executionStatus.status_code=status_code print(exe_status_expiration) executionStatus.save() return executionStatus,message,operationSetting