Beispiel #1
0
 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()
Beispiel #2
0
 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()
Beispiel #3
0
    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()
Beispiel #4
0
 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)
Beispiel #5
0
    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)
Beispiel #6
0
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__))
Beispiel #7
0
 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)
Beispiel #8
0
    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)
Beispiel #9
0
    def delete(self, pk):
        try:
            post = Post.objects.get(pk=pk)
        except Post.DoesNotExist:
            raise NotFound({"errMsg": 'No Post Found!'})

        post.delete()
Beispiel #10
0
    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'}
Beispiel #11
0
 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()
Beispiel #12
0
    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.')
Beispiel #13
0
    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)
Beispiel #14
0
    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)
Beispiel #15
0
    def get(self, pk):
        identifier = pk

        template = self.get_template(identifier)
        if not template:
            raise NotFound()

        return template.format(include_data=True)
Beispiel #16
0
    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)
Beispiel #17
0
    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)
Beispiel #18
0
    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)
Beispiel #19
0
    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
Beispiel #20
0
    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()
Beispiel #22
0
 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)
Beispiel #23
0
    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)
Beispiel #24
0
    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
Beispiel #25
0
    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
Beispiel #26
0
    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
Beispiel #27
0
    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
Beispiel #28
0
    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)
Beispiel #29
0
    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()
Beispiel #30
0
 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)