Esempio n. 1
0
    def get(self, request, *args, **kwargs):
        """Returns a user's profile."""
        # Get user
        try:
            username = kwargs.get('username')
            user = DjangoDev.objects.get(username=username)
        except:
            return Http404('This user does not exist')

        # Serialize user
        user_fields = ['username', 'job_title', 'company',
            'interests', 'email', 'website', 'image']
        serialized_user = serialize(user, fields=user_fields)
        
        # Serialize attached posts
        # Check if logged in user is authorized to view these posts
        model_filters = {"user": user}
        if not ((request.user.is_authenticated()) and (user == request.user)):
            model_filters["is_draft"] = True
        posts = paginate(request=request, model=BlogPost,
            model_filters=model_filters)
        post_fields = ['title', 'caption', 
            ('url', lambda obj: obj.get_url()),
        ]
        serialized_posts = serialize(posts.object_list, fields=post_fields)
        
        # Conjoin the two together
        serialized_user['posts'] = serialized_posts
        return Http200(serialized_user)
Esempio n. 2
0
 def get(self, request, *args, **kwargs):
     """Returns the main quote, and the latest meetups, jobs, and posts."""
     # Posts{"is_draft": False}
     posts = BlogPost.objects.filter(**{"is_draft": False})[:5]
     post_fields = [ "title", "caption",
         ("url", lambda obj: obj.get_url())
     ]
     
     # Jobs
     jobs = Job.objects.all()[:5]
     job_fields = ["title", "company",
         ("url", lambda obj: obj.get_url())
     ]
     
     # Meetups
     meetups = Meetup.objects.all()[:5]
     meetup_fields = ["title", "event_url"]
     
     return_data = {
         "caption": HOME_CAPTION,
         "posts": serialize(posts, post_fields),
         "jobs": serialize(jobs, job_fields),
         "meetups": serialize(meetups, meetup_fields)
     }
     return Http200(return_data)
Esempio n. 3
0
 def post(self, request, format=None):
     print "User: "******"Data: ", request.POST
     # print "Method: ",request.method
     if request.method == "POST":
         print request.POST
         if "code" in request.POST:
             code = request.POST.get('code')
             print code
             ticket = get_object_or_404(EventTickets, code=code)
             print ticket.email, ticket
             dict_obj = {
                 'id': ticket.id,
                 'email': ticket.email,
                 'promocode_success': ticket.promocode_success,
                 'expire': ticket.expire,
                 'amount': ticket.amount,
                 'quantity': ticket.quantity,
                 'earlybird_ticket': ticket.earlybird_ticket,
                 'group_ticket': ticket.group_ticket,
                 'code': ticket.code,
                 'is_attended': ticket.is_attended,
                 'created_at': str(ticket.created_at),
                 'phone': ticket.phone,
                 'event': ticket.event.name,
             }
             print dict_obj
             return Http200(serialize(dict_obj))
         elif "code_update" in request.POST:
             code = request.POST.get('code_update')
             print code
             ticket = get_object_or_404(EventTickets, code=code)
             ticket.is_attended = True
             ticket.save()
             dict_obj = {
                 'id': ticket.id,
                 'email': ticket.email,
                 'promocode_success': ticket.promocode_success,
                 'expire': ticket.expire,
                 'amount': ticket.amount,
                 'quantity': ticket.quantity,
                 'earlybird_ticket': ticket.earlybird_ticket,
                 'group_ticket': ticket.group_ticket,
                 'code': ticket.code,
                 'is_attended': ticket.is_attended,
                 'created_at': str(ticket.created_at),
                 'phone': ticket.phone,
                 'event': ticket.event.name,
             }
             print Http200(serialize(dict_obj))
             return Http200(serialize(dict_obj))
     print 'get'
     return HttpResponse("No such method available.")
Esempio n. 4
0
    def post(self, request):
        try:
            cluster = Cluster.objects.get(pk=request.data['uuid'])
        except Cluster.DoesNotExist:
            return Http404("That cluster does not exist.")

        form = ClusterForm(request.data, instance=cluster)

        if form.is_valid():
            form.save()
        else:
            return serialize([(k, v[0]) for k, v in form.errors.items()])

        return serialize(cluster)
Esempio n. 5
0
    def test_serialize_doesnt_mutate_fields(self):
        runs = [0]

        def accessor(obj):
            runs[0] += 1
            return 'foo'

        # If fields are appended on, 'desc' will be twice in the list
        # for the second run, so in total the accessor function will be
        # run 3 instead of 2 times
        serialize([self.author, self.author], fields=['id'],
            include=[('desc', accessor)])

        self.assertEqual(runs[0], 2)
Esempio n. 6
0
    def put(self, request, sensor_id):
        sensor = self.get_sensor(request, sensor_id)

        if not isinstance(sensor, Sensor):
            return sensor

        form = SensorForm(request.data, instance=sensor)

        if form.is_valid():
            form.save()
        else:
            return serialize([(k, v[0]) for k, v in form.errors.items()])

        return serialize(sensor)
Esempio n. 7
0
    def test_serialize_doesnt_mutate_fields(self):
        runs = [0]

        def accessor(obj):
            runs[0] += 1
            return 'foo'

        # If fields are appended on, 'desc' will be twice in the list
        # for the second run, so in total the accessor function will be
        # run 3 instead of 2 times
        serialize([self.author, self.author],
                  fields=['id'],
                  include=[('desc', accessor)])

        self.assertEqual(runs[0], 2)
Esempio n. 8
0
 def get(self, request, *args, **kwargs):
     """Returns a list of public or private posts, depending on whether or 
     not the requested user is the one authenticated,
     """
     username = kwargs.get('username')
     try:
         request_user = get_user_model().objects.get(username=username)
     except:
         return Http404("User, %s, does not exist" % username)
     if request.user.is_authenticated() and \
             username == request.user.username:
         model_filters = {'user': request_user}
     else:
         model_filters = {'user': request_user, 'is_draft': False}
     posts = paginate(request=request, model=BlogPost, 
         model_filters=model_filters)
     post_fields = ["title", "caption",
         ("last_updated", lambda obj: obj.last_updated.strftime(
             "%B %d, %Y")),
         ("url", lambda obj: obj.get_url()),
         ("user", dict(fields=[
             "username",
             'image',
             ("url", lambda obj: obj.get_url())
         ]))
     ]
     serialized_data = {
         "posts": serialize(posts.object_list, post_fields),
         "page": posts.number,
         "count": posts.paginator.per_page
     }
     return Http200(serialized_data)
Esempio n. 9
0
 def get(self, request, *args, **kwargs):
     """Returns a list of paginated comments."""
     try: # Check if Blog post exists, and return a list of related comments
         username = kwargs.get('username')
         user = get_user_model().objects.get(username=username)
         title_slug = kwargs.get('title_slug')
         post = BlogPost.objects.get(user=user, title_slug=title_slug)
         model_filters = {"post": post}
         comments = paginate(request=request,
             model=Comment, model_filters=model_filters)
         comment_fields = ['text', 'pk',
             ('date_created', lambda obj: obj.date_created.strftime(
                 "%B %d, %Y")),
             ('date_updated', lambda obj: obj.date_updated.strftime(
                 "%B %d, %Y")),
             ('user', dict(fields=[
                 'username',
                 'image',
                 ('url', lambda obj: obj.get_url())
             ]))
         ]
         return_data = {
             "comments": serialize(comments.object_list, comment_fields),
             "page": comments.number,
             "count": comments.paginator.per_page
         }
         return Http200(return_data)
     except:
         return Http404("Blog post does not exist.")
Esempio n. 10
0
    def get(self, request, *args, **kwargs):
        """Returns the data for a full blog post, and a hyperlink for attached
        comments.
        """
        try: # Check if blog post exists
            title = kwargs.get('title_slug')
            username = kwargs.get('username')
            user = get_user_model().objects.get(username=username)
            post = BlogPost.objects.get(title_slug=title, user=user) 
        except:
            return Http404("This blog post does not exist.")

        if post.is_draft and request.user.username != user.username:
            return Http403("You are not authorized to view this post "
                "because you are not the owner, and it is not public yet.")
        post_fields = ['title', 'caption', 'text', 'pk',
            ('last_updated', lambda obj: obj.last_updated.strftime(
                "%B %d, %Y")),
            ('user', dict(fields=[
                'username',
                ('url', lambda obj: obj.get_url())
            ]))
        ]
        if post.is_draft == False:
            post_fields.append(('date_published', 
                lambda obj: obj.date_published.strftime("%B %d, %Y")))
        return_data = serialize(post, fields=post_fields)
        return Http200(return_data)
Esempio n. 11
0
    def get(self, request):
        """
        @query page     Requested page number
        @query per_page Number of results per page

        """
        objects = request.user.team.advisories \
                                   .prefetch_related("sensor", "rule") \
                                   .order_by("-created")

        # Parse Parameters
        per_page = safe_cast(request.GET.get("per_page"), int, default=100)
        page = safe_cast(request.GET.get("page"), int, default=1)

        pages = Paginator(objects, per_page)

        try:
            advisories = pages.page(page)
        except EmptyPage:
            return None

        return serialize({
            "advisories":
            AdvisoryPresenter(advisories.object_list).serialized,
            "page":
            page,
            "num_pages":
            pages.num_pages,
        })
Esempio n. 12
0
def iOSLoginBAWF(request):
    if request.method == "POST":
        print 'abcd'
        print request.POST
        print request.GET
        print request
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not username and not password:
            print "response inside if"
            return Http400("failed")
        print 'ca', username
        print 'ca', password
        user_auth = authenticate(username=username, password=password)
        try:
            print 'auth', user_auth
            user_auth.backend = 'django.contrib.auth.backends.ModelBackend'
            auth_login(request, user_auth)
            print 'auth'
            if not user_auth.is_staff:
                return Http400("failed")
            token = Token.objects.get_or_create(user=user_auth)[0]

            # return HttpResponse(json.dumps({
            #     'key':token.key,
            # }))
            return Http200(serialize({
                'key': token.key,
            }))
        except Exception as e:
            print e

    return Http400("failed")
Esempio n. 13
0
    def get(self, request, pk, *args, **kwargs):
        params = request.params

        fields = self.default_fields
        if 'fields' in params:
            fields = params.pop('fields').split(",")

        related, config = get_fields(self.serialize_config, fields=fields)

        self.start_debug()

        try:
            obj = self.model.objects.prefetch_related(*related).get(pk=pk)
        except ObjectDoesNotExist as e:
            raise HttpError(404, "Error: {}".format(e))
        except Exception:
            raise HttpError(500, "Error: Something went wrong with your request")

        serialized = serialize(obj, **config)
        serialized['debug'] = self.get_debug()

        response = Http200(serialized)
        response['Access-Control-Allow-Origin'] = "*"

        return response
Esempio n. 14
0
 def post(self, request):
     form = AuthorForm(request.data)
     if form.is_valid():
         author = form.save()
         return Http201(serialize(author))
     else:
         return Http400(reason='invalid author data', details=form.errors)
Esempio n. 15
0
 def post(self, request):
     """Assign boat to timeslot."""
     fields = ('timeslot_id', 'boat_id')
     ids = prepare_record(request.data, fields)
     ts = Timeslot.objects.get(pk=int(ids['timeslot_id']))
     boat = Boat.objects.get(pk=int(ids['boat_id']))
     return serialize(Assignment.objects.create(boat=boat, timeslot=ts))
Esempio n. 16
0
    def get(self, request):
        sensor_id = request.GET.get("sensor")

        param = Q()

        if sensor_id:
            param = Q(sensor=sensor_id)

        rules_count = request.user.team.advisories \
                                       .filter(param) \
                                       .prefetch_related("rule") \
                                       .values("rule") \
                                       .annotate(Count("rule")) \
                                       .order_by()

        rule_map = {}
        for r in Rule.objects.values("id", "name").all():
            rule_map[r["id"]] = r["name"]

        advisory_total = request.user.team.advisories \
                                          .filter(param) \
                                          .count()
        type_data = []

        for a in rules_count:
            type_data.append({
                "name": rule_map[a["rule"]],
                "count": a["rule__count"],
            })

        return serialize({
            "total": advisory_total,
            "types": type_data,
        })
Esempio n. 17
0
 def post(self, request):
     """Create a timeslot."""
     fields = ('start_time', 'duration')
     rec = prepare_record(request.data, fields)
     rec['end_time'] = duration_to_timestamp(rec['duration'], rec['start_time'])
     del rec['duration']
     return serialize(self._augment(Timeslot.objects.create(**rec)))
Esempio n. 18
0
    def get(self, request, pk, *args, **kwargs):
        params = request.params

        fields = self.default_fields
        if 'fields' in params:
            fields = params.pop('fields').split(",")

        related, config = get_fields(self.serialize_config, fields=fields)

        self.start_debug()

        try:
            obj = self.model.objects.prefetch_related(*related).get(pk=pk)
        except ObjectDoesNotExist as e:
            raise HttpError(404, "Error: {}".format(e))
        except Exception:
            raise HttpError(500,
                            "Error: Something went wrong with your request")

        serialized = serialize(obj, **config)
        serialized['debug'] = self.get_debug()

        response = Http200(serialized)
        response['Access-Control-Allow-Origin'] = "*"

        return response
Esempio n. 19
0
    def get(self, request, sensor_id):
        sensor = self.get_sensor(request, sensor_id)

        if not isinstance(sensor, Sensor):
            return sensor

        objects = sensor.advisories.prefetch_related("rule") \
                                   .order_by("-created")

        # Parse Parameters
        per_page = safe_cast(request.GET.get("per_page"), int, default=100)
        page = safe_cast(request.GET.get("page"), int, default=1)

        pages = Paginator(objects, per_page)

        try:
            advisories = pages.page(page)
        except EmptyPage:
            return None

        return serialize({
            "advisories":
            AdvisoryPresenter(advisories.object_list).serialized,
            "page":
            page,
            "num_pages":
            pages.num_pages,
        })
Esempio n. 20
0
    def test_serialize_related_flatten(self):
        """Test injection of related models' fields into the serialized one"""

        b = self.books[0]
        s = serialize(b, fields=[('author', dict())], fixup=flatten('author'))

        self.assertEqual(s['name'], b.author.name)
Esempio n. 21
0
    def test_serialize_related_flatten(self):
        """Test injection of related models' fields into the serialized one"""

        b = self.books[0]
        s = serialize(b, related={
            'author': (None, None, True)
        })
        self.assertEqual(s['name'], b.author.name)
Esempio n. 22
0
 def put(self, request, item_id):
     item = Item.objects.get(pk=item_id)
     if item.user != request.user:
         return HttpResponseForbidden()
     self.request_to_item(request, item)
     item.user = request.user
     item.save()
     return serialize(item)
Esempio n. 23
0
 def get(self, request, pk):
     pages = Page.objects.filter(course_id=pk)
     # on inclut le champs "order" pour mettre en évidence la page active dans le menu
     return serialize(pages, fields=[
             'name',
             'order',
             ('sections', dict(fields=['name']))
         ])
Esempio n. 24
0
    def get(self, request, *args, **kwargs):
        params = dict(request.GET)
        response = Http200(serialize(
            self.get_object(request, *args, **kwargs),
            **self.PUBLIC_SCHEMA))

        response['Access-Control-Allow-Origin'] = "*"
        return response
Esempio n. 25
0
 def post(self, request):
     form = AuthorForm(request.data)
     if form.is_valid():
         author = form.save()
         return Http201(serialize(author))
     else:
         return Http400(reason='invalid author data',
             details=form.errors)
Esempio n. 26
0
    def get(self, request, *args, **kwargs):
        params = dict(request.GET)
        response = Http200(
            serialize(self.get_object(request, *args, **kwargs),
                      **self.PUBLIC_SCHEMA))

        response['Access-Control-Allow-Origin'] = "*"
        return response
Esempio n. 27
0
    def get(self, request):
        from .update import apply_modeldiffs
        result = apply_modeldiffs()

        if len(result['rows_skipped']) > 0:
            mail_admins('Some modeldiffs failed to apply!', 'ERROR!')

        return serialize(result['qs'], exclude=('the_geom'))
Esempio n. 28
0
    def get(self, request):
        from .update import apply_modeldiffs
        result = apply_modeldiffs()

        if len(result['rows_skipped']) > 0:
            mail_admins('Some modeldiffs failed to apply!', 'ERROR!')

        return serialize(result['qs'], exclude=('the_geom'))
Esempio n. 29
0
def blog_detail(request, pk, *args, **kwargs):
    # were going to serialize the data into json and return it via the url
    # with this object using .get is not iterable because it only returns one item
    # post = Post.objects.get(pk=pk, published=True) soooo..you have to  use
    post = Post.objects.filter(pk=pk, published=True)
    data = serialize(post)
    jsondata = json.dumps(data, cls=DjangoJSONEncoder)

    return HttpResponse(jsondata, mimetype="application/json")
Esempio n. 30
0
 def get(self, request):
     """List timeslots. ?date: YYYY-MM-DD format."""
     try:
         dt = dateparser.parse(request.params.get('date'))
     except:
         return Http400("date param missing or invalid format")
     match = dict(zip(('start_time__gte', 'start_time__lt'),
                      date_bounds(dt)))
     return serialize([self._augment(rec) for rec in Timeslot.objects.filter(**match)])
Esempio n. 31
0
    def test_serialize_related_partial(self):
        """Test serialization of some fields of related model"""

        s = serialize(self.author, related={'books': ('title', None, False)})
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue('isbn' not in b)
Esempio n. 32
0
 def get(self, request):
     venues_list = Place.objects.all().annotate(
         pic_count=Count('location__pic')).annotate(
             preview='location__pic').order_by('pic_count').reverse()[:10]
     fields = ('id', 'name', 'pic_count',
               ('foursq_primary_cat', dict(fields=[
                   'name',
               ])), ('location', dict(fields=['lat', 'lon'])))
     return serialize(venues_list, fields)
Esempio n. 33
0
    def test_serialize_related_flatten(self):
        """Test injection of related models' fields into the serialized one"""

        b = self.books[0]
        s = serialize(b, fields=[
            ('author', dict())
        ], fixup=flatten('author'))

        self.assertEqual(s['name'], b.author.name)
Esempio n. 34
0
    def test_serialize_related(self):
        """Test serialization of related model"""

        s = serialize(self.author, related={'books': None})
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue(b['isbn'].startswith('123-1-12-123456-'))
Esempio n. 35
0
    def test_serialize_related(self):
        """Test serialization of related model"""

        s = serialize(self.author, include=[('books', dict())])
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue(b['isbn'].startswith('123-1-12-123456-'))
Esempio n. 36
0
    def test_serialize_related_partial(self):
        """Test serialization of some fields of related model"""

        s = serialize(self.author, include=[('books', dict(fields=['title']))])
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue('isbn' not in b)
Esempio n. 37
0
 def post(self, request, pk):
     comment_form = CommentForm(request.data)
     if comment_form.is_valid():
         comment = comment_form.save(commit=False)
         comment.user = request.user
         comment.course_id = pk
         comment.save()
         return Http201(serialize(comment, include=[
             ('user', lambda c: c.user.username)
         ]))
Esempio n. 38
0
    def test_serialize_related_deprecated(self):
        """Test serialization of related model"""

        with warnings.catch_warnings(record=True):
            s = serialize(self.author, related={'books': None})
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue(b['isbn'].startswith('123-1-12-123456-'))
Esempio n. 39
0
    def test_serialize_dict(self):
        """Test that dict serialization deep-serializes dict values"""

        Author.objects.all().delete()
        a1 = Author.objects.create(name="foo")
        a2 = Author.objects.create(name="bar")
        s = serialize({'a1': a1, 'a2': a2})

        self.assertEqual(s['a1']['name'], a1.name)
        self.assertEqual(s['a2']['name'], a2.name)
Esempio n. 40
0
    def test_serialize_dict(self):
        """Test that dict serialization deep-serializes dict values"""

        Author.objects.all().delete()
        a1 = Author.objects.create(name="foo")
        a2 = Author.objects.create(name="bar")
        s = serialize({'a1': a1, 'a2': a2})

        self.assertEqual(s['a1']['name'], a1.name)
        self.assertEqual(s['a2']['name'], a2.name)
Esempio n. 41
0
 def post(self, request):
     """Create a booking."""
     fields = ('timeslot_id', 'size')
     rec = prepare_record(request.data, fields)
     tsid = int(rec['timeslot_id'])
     size = int(rec['size'])
     try:
         booking = Booking.book_for(tsid, size)
     except ValueError as err:
         return Http409(err.message)
     return serialize(booking)
Esempio n. 42
0
    def get(self, request):
        sensors = request.user.team.sensors.all()

        snapshot = SnapshotAPI(request.user.team.identifier)

        state = snapshot.state
        clusters = snapshot.clusters
        assets = snapshot.cloud_information

        cluster_counts = Counter()
        group_counts = Counter()
        hosts = Counter()

        # Populate cluster statistics
        for uuid, members in clusters.iteritems():
            cluster, created = Cluster.objects.get_or_create(uuid=uuid, team=request.user.team)
            cluster_counts[cluster.name] += len(members)

        # Add AWS tag information to group list
        for key, asset in assets.iteritems():
            for key, value in asset["tags"].iteritems():
                if key != "Name":
                    group = "AWS - %s" % value
                    group_counts[group] += 1

        hosts["monitored"] = 0
        for s in sensors:
            hosts["monitored"] += 1

            # Populate groups statistics
            if s.groups:
                for g in s.groups:
                    group_counts[g] += 1

            # Remove from asset list to prevent duplicate entry
            assets.pop(s.cloud_key, None)

            # Check online/offline status
            status = state.get(s.uuid, {}).get("activity", {}).get("is_connected")
            if status:
                hosts["active"] += 1
            else:
                hosts["inactive"] += 1

        # All remaining assets are "unmonitored"
        hosts["unmonitored"] = len(assets.keys())

        hosts["total"] = hosts["monitored"] + hosts["unmonitored"]

        return serialize({
            "hosts": hosts,
            "groups": [{"name": name, "count": count} for name, count in group_counts.iteritems()],
            "clusters": [{"name": name, "count": count} for name, count in cluster_counts.iteritems()]
        })
Esempio n. 43
0
    def test_serialize_related_partial(self):
        """Test serialization of some fields of related model"""

        s = serialize(self.author, related={
            'books': ('title', None, False)
        })
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue('isbn' not in b)
Esempio n. 44
0
    def get(self, request):
        groups = []

        for sensor in request.user.team.sensors.all():
            if sensor.group:
                for group in sensor.groups:
                    groups.append(str(group))
            else:
                groups.append('ungrouped')

        return serialize(set(groups))
Esempio n. 45
0
 def get(self, request):
     jobs = Job.objects.all()
     fields = [
         "id",
         "locus",
         "analysis_type",
         "date",
         "status",
         ("url", lambda job: job.url)
     ]
     return serialize(jobs,fields)
Esempio n. 46
0
 def get(self, request):
     venues_list = Place.objects.filter(
         Q(foursq_primary_cat__name__contains='Bar')
         | Q(foursq_primary_cat__name__contains='Lounge')
         | Q(foursq_primary_cat__name__contains='Beer')).annotate(
             pic_count=Count('location__pic')).order_by(
                 'pic_count').reverse()[:10]
     fields = ('id', 'name', 'pic_count',
               ('foursq_primary_cat', dict(fields=[
                   'name',
               ])), ('location', dict(fields=['lat', 'lon'])))
     return serialize(venues_list, fields)
Esempio n. 47
0
    def get(self, request, sensor_id):
        result = cache.get("%s.process_info" % sensor_id)

        if result:
            return result

        else:
            process_info = SnapshotAPI(
                request.user.team.identifier).sensor_process_tree(sensor_id)
            cache.set("%s.process_info" % sensor_id, process_info, 300)

            return serialize(process_info)
Esempio n. 48
0
    def test_serialize_related_deep(self):
        """Test serialization of twice-removed related model"""

        s = serialize(self.author,
                      include=[('books', dict(include=[('publisher', dict())]))
                               ])

        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertEqual(b['publisher']['name'], 'Publisher')
Esempio n. 49
0
    def get(self, request, pk, *args, **kwargs):
        params = request.params

        fields = self.default_fields
        if 'fields' in params:
            fields = params.pop('fields').split(",")

        obj = self.model.objects.get(pk=pk)
        config = get_fields(self.serialize_config, fields=fields)
        response = Http200(serialize(obj, **config))
        response['Access-Control-Allow-Origin'] = "*"

        return response
Esempio n. 50
0
    def put(self, request, author_id=None):
        author_id = int(author_id)
        try:
            author = Author.objects.get(id=author_id)
        except Author.DoesNotExist:
            return Http404(reason='no such author')

        form = AuthorForm(request.data, instance=author)
        if form.is_valid():
            author = form.save()
            return serialize(author)
        else:
            return Http400(reason='invalid author data', details=form.errors)
Esempio n. 51
0
    def test_serialize_related_deep(self):
        """Test serialization of twice-removed related model"""

        s = serialize(self.author,
                      related={'books': (None, {
                          'publisher': None,
                      }, None)})

        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertEqual(b['publisher']['name'], 'Publisher')
Esempio n. 52
0
 def get(self, request):
     user = request.user
     # Trie les cours par thème, sélectionne les cours favoris d'un utilisateur ou renvoie tous les cours
     # Retourne seulement les cours publiés
     if 'theme' in request.GET:
         courses = Course.objects.filter(chapter__theme__name=request.GET['theme'], published=True)
     elif 'favorite' in request.GET and user.is_authenticated() and user.is_active:
         courses = user.favorite_courses.filter(published=True)
     else:
         courses = Course.objects.filter(published=True)
     return serialize(courses, include=[
             ('chapter', dict(fields=['name']))
         ])
Esempio n. 53
0
	def get(self, request, pk):
		try:
			post = Post.objects.get(pk=pk)
			fields = [
				'id',
				('url', lambda post: post.url),
				'title',
				'date_created',
				'text'
			]
			return serialize(post, fields)
		except Exception as e:
			return Http400(e)
Esempio n. 54
0
    def test_serialize_list(self):
        """Test list serialization"""

        Author.objects.all().delete()
        a1 = Author.objects.create(name="foo")
        a2 = Author.objects.create(name="bar")
        s = serialize(list(Author.objects.all()))
        self.assertEqual(s,
            [
                {'name': a1.name, 'id': a1.id},
                {'name': a2.name, 'id': a2.id},
            ]
        )
Esempio n. 55
0
    def test_serialize_related_partial(self):
        """Test serialization of some fields of related model"""

        s = serialize(self.author, include=[
            ('books', dict(
                fields=['title']
            ))
        ])
        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertTrue('isbn' not in b)
Esempio n. 56
0
    def test_serialize_related_deep(self):
        """Test serialization of twice-removed related model"""

        s = serialize(self.author, related={
            'books': (None, {
                'publisher': None,
            }, None)})

        self.assertEqual(s['name'], 'User Foo')
        self.assertEqual(len(s['books']), len(self.books))
        for b in s['books']:
            self.assertTrue(b['title'].startswith('Book '))
            self.assertEqual(b['publisher']['name'], 'Publisher')
Esempio n. 57
0
    def get(self, request):
        interval = request.GET.get("interval", "hour")
        series_type = request.GET.get("type", "histogram")

        team_id = request.user.team.identifier
        manager = TimeseriesManager(team_id, series_type)

        results = []

        for rule in Rule.objects.all():
            stat = manager.query(rule.slug, interval)
            results.append(tame_results(stat, rule.name))

        return serialize(results)
Esempio n. 58
0
    def get(self, request):
        # Pull request information
        interval = request.GET.get("interval", "hour")
        series_type = request.GET.get("type", "histogram")

        team_id = request.user.team.identifier
        manager = TimeseriesManager(team_id, series_type)

        monitored = manager.query("monitored",interval)
        unmonitored = manager.query("unmonitored",interval)

        mon = tame_results(monitored, "monitored")
        unmon = tame_results(unmonitored, "unmonitored")

        return serialize([mon, unmon])
Esempio n. 59
0
    def get(self, request):
        interval = request.GET.get("interval", "hour")
        series_type = request.GET.get("type", "histogram")

        team_id = request.user.team.identifier
        clusters = request.user.team.clusters.all()

        manager = TimeseriesManager(team_id, series_type)

        results = []

        for cluster in clusters:
            stat = manager.query(cluster.uuid, interval)
            results.append(tame_results(stat, cluster.name))

        return serialize(results)
Esempio n. 60
0
def verify_access_key(request, access_key):
    """
    Verifies that an access_key is valid. Used inside of the sensor endpoint.

    """
    try:
        apikey = APIKey.objects.get(access_key=access_key)
    except APIKey.DoesNotExist:
        return Http403("The access_key is not valid.")

    return JSONResponse(
        serialize(apikey,
                  fields=[
                      'secret_key',
                      ('identifier', lambda a: a.team.identifier),
                  ]))