def search_patient_unhcr(self, unhcr_id): if unhcr_id: patients = Patient.objects.filter(UNHCR=unhcr_id) if patients.exists(): yield (Patient, patients) else: raise NotFound() else: raise NotFound()
def add_physician(self, physician_id): if physician_id: # Need to sync try: the_physician = Physician.objects.get(uuid=physician_id) Clinic_Physician(clinic=self.device.clinic, physician=the_physician).save() yield the_physician except models.ObjectDoesNotExist: raise NotFound() else: raise NotFound()
def search_physician_contact(self, contact_info): if contact_info: try: # is it email or phone? if '@' in contact_info: the_physician = Physician.objects.get(email=contact_info) else: the_physician = Physician.objects.get(phone=contact_info) Clinic_Physician(clinic=self.device.clinic, physician=the_physician).save() yield the_physician except models.ObjectDoesNotExist: raise NotFound() else: raise NotFound()
def _get_collection(self): accessor = models.Accessor(self.request.user) id = self._get_collection_id() try: return accessor.query_collections().get(id=id) except ObjectDoesNotExist: raise NotFound('No such collection: %r' % id)
def update(self, pk): audit_msg(self.request) form = forms.CollectionForm(self.data) if not form.is_valid(): raise BadRequest('Validation failure: %r' % form.errors) with transaction.atomic(): accessor = models.Accessor(self.request.user) try: coll = accessor.query_collections().get(id=pk) except ObjectDoesNotExist: raise NotFound('Invalid collection id = %r' % pk) coll.blogged = form.cleaned_data['blogged'] if form.cleaned_data['blogged']: coll.ensure_blog_exists() coll.blog.slug = form.cleaned_data['blog_slug'] coll.blog.description = form.cleaned_data['blog_desc'] coll.blog.save() else: models.BlogCollection.objects.filter(collection=coll).delete() coll.name = form.cleaned_data['name'] coll.save() return self._prepare(coll)
def get_or_404(_model, id, bind=None): """ Return object or not found exception :param _model: Model :param id: Primary key :param bind: Name of other engine Example: # without bind food = get_or_404(Food, 1) food.name >>> Espinafre # with bind food = get_or_404(Food, 1, 'other1') food.name >>> CuzCuz # not found food = get_or_404(Food, 42) # { "error": "Food not found" } """ if bind: obj = session.using(bind).query(_model).get(id) else: obj = session.query(_model).get(id) if obj: return obj else: raise NotFound('{0} not found'.format(_model.__name__))
def list(self): if self.request.GET.__contains__('unhcr'): res = SerializedSynchronizationProcessor( self.device).search_patient_unhcr(self.request.GET['unhcr']) elif self.request.GET.__contains__('birthYear'): year = self.request.GET['birthYear'] city = None first_name = None last_name = None gender = None if self.request.GET.__contains__('birthCity'): city = self.request.GET['birthCity'] if self.request.GET.__contains__('firstName'): first_name = self.request.GET['firstName'] if self.request.GET.__contains__('lastName'): last_name = self.request.GET['lastName'] if self.request.GET.__contains__('gender'): gender = self.request.GET['gender'] res = SerializedSynchronizationProcessor( self.device).search_patient(year, first_name, last_name, city, gender) else: raise NotFound() if self._use_transport_encryption(): res = self.serializer.serialize(res).encode("utf-8") res = self.device.key.encrypt(res) return Data(res, should_prepare=False)
def test_build_error(self): err = HttpError("Whoopsie") resp = self.res.build_error(err) resp_body = json.loads(resp.body) self.assertEqual(resp_body, {'error': 'Whoopsie'}) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.status_code, 500) nf_err = NotFound() resp = self.res.build_error(nf_err) resp_body = json.loads(resp.body) # Default error message. self.assertEqual(resp_body, {'error': 'Resource not found.'}) self.assertEqual(resp.content_type, 'application/json') # Custom status code. self.assertEqual(resp.status_code, 404) # Non-restless exception. unknown_err = AttributeError("'something' not found on the object.") resp = self.res.build_error(unknown_err) resp_body = json.loads(resp.body) # Still gets the JSON treatment & an appropriate status code. self.assertEqual(resp_body, {'error': "'something' not found on the object."}) self.assertEqual(resp.content_type, 'application/json') self.assertEqual(resp.status_code, 500)
def delete(self, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: raise NotFound({"errMsg": 'No Post Found!'}) post.delete()
def delete(self, pk): try: comment = Comment.objects.get(pk=pk) except Comment.DoesNotExist: raise NotFound({"errMsg": 'No Comment Found!'}) comment.delete() return {'message': 'Comment Deleted Successfully'}
def search_patient(self, year, first, last, city, gender): if year: patients = Patient.objects.filter(birthYear__exact=year) if city: patients = patients.filter(birthCity__istartswith=city) if first: patients = patients.filter(firstName__istartswith=first) if last: patients = patients.filter(lastName__istartswith=last) if gender: patients = patients.filter(gender__exact=gender) if patients.exists(): yield (Patient, patients) else: raise NotFound() else: raise NotFound()
def random_course(self): # Order by random, then take the first one. random_order = self.base_qs.order_by('?') if random_order.exists(): return random_order[0] raise NotFound('No courses found.')
def detail(self, pk): audit_msg(self.request) accessor = models.Accessor(self.request.user) try: return self._prepare(accessor.query_items().get(id=pk)) except ObjectDoesNotExist: raise NotFound('No id = %r' % pk)
def delete(self, pk): audit_msg(self.request) accessor = models.Accessor(self.request.user) try: accessor.query_items(owner=True).get(id=pk).delete() except ObjectDoesNotExist: raise NotFound('No id = %r' % pk)
def get(self, pk): identifier = pk template = self.get_template(identifier) if not template: raise NotFound() return template.format(include_data=True)
def update(self, pk): audit_msg(self.request) form = forms.ItemForm(self.data) if not form.is_valid(): raise BadRequest('Validation failure: %r' % form.errors) accessor = models.Accessor(self.request.user) try: item = accessor.query_items().get(id=pk) except ObjectDoesNotExist: raise NotFound('No id = %r' % pk) if 'collection_id' in self.data: cid = form.cleaned_data['collection_id'] if item.collection.encrypted: raise BadRequest('Cannot move from an encrypted journal') try: collection = accessor.query_collections().get(id=cid) except ObjectDoesNotExist: raise NotFound('No collection id = %r' % cid) if collection.encrypted: raise BadRequest('Cannot move to an encrypted journal') item.collection = collection if 'title' in self.data: item.title = form.cleaned_data['title'] if 'content' in self.data: item.content = form.cleaned_data['content'] if 'notes' in self.data: item.notes = form.cleaned_data['notes'] if 'typ' in self.data: item.typ = form.cleaned_data['typ'] if 'created_at' in self.data: month, day, year = [ int(x) for x in form.cleaned_data['created_at'].split('/') ] d = item.created_at item.created_at = d.replace(year=year, month=month, day=day) if 'visibility' in self.data: item.visibility = form.cleaned_data['visibility'] slug = slugify(item.title) if len(slug) > 50: slug = slug[:50] item.slug = slug item.save() return self._prepare(item)
def remove(self, pk): name = pk dataset = self.get_dataset(name) if not dataset: raise NotFound() kubernetes_client = KubernetesClient() kubernetes_client.delete_crd(group='com.ie.ibm.hpsys', version='v1alpha1', namespace=self.user.namespace, plural='datasets', name=name)
def delete(self, pk): audit_msg(self.request) accessor = models.Accessor(self.request.user) try: collection = accessor.query_collections(owner=True).get(id=pk) collection.delete() except ObjectDoesNotExist: raise NotFound('Invalid collection id = %r' % pk)
def get_page(self, data): try: page_no = int(self.request.GET.get(self.page_attribute_name, 1)) except (TypeError, ValueError): raise NotFound('Invalid page number.') if page_no < 1: raise NotFound('Page number should be 1 or greater.') # Explicitly evaluate data before sending it to Paginator, otherwise # (at least in the case of RelatedSearchQuerySet) the total count # goes completely wrong # see: https://github.com/django-haystack/django-haystack/issues/362 data[:self.results_per_page] paginator = Paginator(data, self.results_per_page) try: page = paginator.page(page_no) except InvalidPage: raise NotFound('No such page!') return page
def add_patient(self, patient_id, physician_id): try: the_patient = Patient.objects.get(uuid=patient_id) Patient_Physician( patient=the_patient, physician=Physician.objects.get(uuid=physician_id)).save() yield from self.update_patient(the_patient) except models.ObjectDoesNotExist: raise NotFound()
def delete(self, pk): try: notification = Notification.objects.get(pk=pk) except ObjectDoesNotExist: raise NotFound({ 'errNo': 404, 'errDev': 'No notification found.', 'errMsg': _('No notification found'), }) notification.delete()
def list(self): if self.request.GET.__contains__('contact'): res = SerializedSynchronizationProcessor( self.device).search_physician_contact( self.request.GET['contact']), elif self.request.GET.__contains__('add_physician'): res = SerializedSynchronizationProcessor( self.device).add_physician(self.request.GET['add_physician']) else: raise NotFound() return Data(res, should_prepare=False)
def remove(self, pk): identifier = pk template = self.get_template(identifier) if not template: raise NotFound() if type(template) == FileTemplate: raise Forbidden() kubernetes_client = KubernetesClient() kubernetes_client.delete_crd(group='karvdash.carv.ics.forth.gr', version='v1', namespace=self.user.namespace, plural='templates', name=template.identifier)
def detail(self, pk): try: user = User.objects.get(pk=pk) except ObjectDoesNotExist: raise NotFound({ 'errNo': 404, 'errDev': 'No user found.', 'errMsg': _('No user found'), }) return user
def publish_post(self, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: raise NotFound({"errMsg": 'No Post Found!'}) if not post.published: post.update_post() post.publish_post() return post return post
def update(self, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: raise NotFound({"errMsg": 'No Post Found!'}) form = PostForm(self.data) if not form.is_valid(): raise BadRequest({"errMsg": "Invalid Data!"}) post.title = form.cleaned_data['title'] post.author = form.cleaned_data['author'] post.content = form.cleaned_data['content'] post.update_post() return post
def update(self, pk): if not pk.isdigit(): raise BadRequest("id:[%s] is invalid" % (pk)) try: emp = Employee.objects.get(id=pk) except Employee.DoesNotExist: raise NotFound("employee id:[%s] not found" % (pk)) eclean, dclean = self.validate_employee(instance=emp) emp.name = eclean['name'] emp.email = eclean['email'] if dclean['name'] != emp.department.name: emp.department = self.get_department(dclean['name']) emp.save() return emp
def delete(self, pk): name = pk kubernetes_client = KubernetesClient() service_database_path = os.path.join(settings.SERVICE_DATABASE_DIR, self.user.username) if not os.path.exists(service_database_path): os.makedirs(service_database_path) service_yaml = os.path.join(service_database_path, '%s.yaml' % name) if not os.path.exists(service_yaml): raise NotFound() else: try: kubernetes_client.delete_yaml(service_yaml, namespace=self.user.namespace) except: raise else: os.unlink(service_yaml)
def get_or_404(cls, pk): """ Get a object or raise a 404 exception :param pk: ID of record Example: food = Food.get_or_404(1) food.name >>> Palmito food.price >>> 10.9 """ obj = cls.query.get(pk) if obj: return obj else: raise NotFound()
def list(self): if self.request.GET.__contains__('synchronized_after'): datestring = self.request.GET["synchronized_after"] datestring = datestring.replace(" ", "+") synchronized_after_ts = dateutil.parser.parse(datestring) if not synchronized_after_ts.tzinfo: synchronized_after_ts = pytz.utc.localize(synchronized_after_ts) res = SerializedSynchronizationProcessor(self.device).calculate_delta(synchronized_after_ts) elif self.request.GET.__contains__('add_patient'): res = SerializedSynchronizationProcessor(self.device).add_patient(self.request.GET['add_patient'], self.request.GET['physician']) elif self.request.GET.__contains__('add_physician'): res = SerializedSynchronizationProcessor(self.device).add_physician(self.request.GET['add_physician']) return Data(res, should_prepare=False) else: raise NotFound() if self._use_transport_encryption(): res = self.serializer.serialize(res).encode("utf-8") res = self.device.key.encrypt(res) return Data(res, should_prepare=False)