Esempio n. 1
0
def calculate_etag(instance: models.Model) -> str:
    """
    Calculate the MD5 hash of a resource representation in the API.

    The serializer for the model class is retrieved, and then used to construct
    the representation of the instance. Then, the representation is rendered
    to camelCase JSON, after which the MD5 hash is calculated of this result.
    """
    model_class = type(instance)
    serializer_class = _get_serializer_for_models()[model_class]

    # build a dummy request with the configured domain, since we're doing STRONG
    # comparison. Required as context for hyperlinked serializers
    request = Request(StaticRequest())
    request.version = api_settings.DEFAULT_VERSION
    request.versioning_scheme = api_settings.DEFAULT_VERSIONING_CLASS()

    serializer = serializer_class(instance=instance,
                                  context={"request": request})

    # render the output to json, which is used as hash input
    renderer = CamelCaseJSONRenderer()
    rendered = renderer.render(serializer.data, "application/json")

    # calculate md5 hash
    return hashlib.md5(rendered).hexdigest()
Esempio n. 2
0
def get_match_detail_json(request, match_id):
    '''Simple serializer'''
    match_obj = get_object_or_404(Match, pk=match_id)
    if request.session.get('match%d' % match_id, 0) == 0:
        match_obj.view_count = match_obj.view_count + 1
        match_obj.save()
        request.session['match%d' % match_id] = 1
    serializer = MatchSerializer(match_obj)
    match_json = serializer.data
    match_json.update({
        'hostUser': {
            'id': match_obj.host_user.id,
            'username': match_obj.host_user.username
        }
    })
    match_json.update({
        'num_participants':
        match_obj.participation_match.all().count(),
        'participants': [
            participation['user_id']
            for participation in match_obj.participation_match.values()
        ],
        'host_name':
        match_obj.host_user.username
    })
    if match_json['match_thumbnail'] is None:
        match_json.update({
            'match_thumbnail':
            'https://t1matchmaker.ml/media/thumbnail/default-thumbnail.png'
        })
    match_json = json.loads(CamelCaseJSONRenderer().render(match_json))
    return match_json
Esempio n. 3
0
def match_join(request, match_id):
    ''' Join match '''
    if request.method == 'POST':
        match_obj = get_object_or_404(Match, pk=match_id)
        if request.user.is_authenticated:
            data = {'user_id': request.user.id, 'match_id': match_obj.id}
            serializer = ParticipationSerializer(data=data)
            serializer.is_valid()  # always valid
            serializer.create(data)
            response = json.loads(CamelCaseJSONRenderer().render(
                serializer.data))
            return JsonResponse(response, status=200)
        return HttpResponse(status=401)  # not authenticated
    if request.method == 'DELETE':
        match_obj = get_object_or_404(Match, pk=match_id)
        if request.user.is_authenticated:
            if match_obj.host_user_id == request.user.id:
                match_obj.delete()
            else:
                Participation.objects.get(user_id=request.user.id,
                                          match_id=match_obj.id).delete()
            return HttpResponse(status=200)
        return HttpResponse(status=401)  # not authenticated
    # 405
    return HttpResponseNotAllowed(['POST', 'DELETE'])
Esempio n. 4
0
def match_detail(request, match_id):
    '''Handles requests about a match'''
    if request.method == 'GET':
        match_json = get_match_detail_json(request, match_id)
        return JsonResponse(match_json, safe=False, status=200)

    if request.method == 'POST':
        match_obj = get_object_or_404(Match, pk=match_id)
        if match_obj.host_user != request.user:
            # 403
            return HttpResponseForbidden()
        data = process_post_request(request)
        match_serializer = MatchSerializer(data=data)
        if match_serializer.is_valid():
            match_serializer.update(match_obj, data)
            match_data = match_serializer.validated_data
            match_data.update({
                "id":
                match_obj.pk,
                'num_participants':
                match_obj.participation_match.all().count()
            })
            response = json.loads(CamelCaseJSONRenderer().render(match_data))
            return JsonResponse(response, status=200)
        # 400
        return HttpResponseBadRequest()
    # 405
    return HttpResponseNotAllowed(['GET', 'POST', 'PATCH', 'DELETE'])
Esempio n. 5
0
def index(request):
    user_data = UserSerializer(request.user).data
    if request.user.is_authenticated():
        projects = Project.objects.filter(owner__members=request.user)
        projects_data = [
            ProjectSerializer(project).data for project in projects
        ]
    else:
        projects_data = []
    return render(
        request, 'index.html', {
            'user_info':
            json.dumps(CamelCaseJSONRenderer().render(user_data).decode()),
            'projects':
            json.dumps(CamelCaseJSONRenderer().render(projects_data).decode()),
            'debug':
            settings.DEBUG,
        })
Esempio n. 6
0
    def get_context_data(self, **kwargs):
        context = super(TeacherView, self).get_context_data(**kwargs)

        context['taskStatuses'] = data.task_statuses
        context['teacher'] = data.teacher
        context['teacher'] = json.loads(CamelCaseJSONRenderer().render(
            TeacherSerializer(models.Teacher.objects.get(id=2)).data))

        return context
Esempio n. 7
0
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)

        context['student'] = json.loads(CamelCaseJSONRenderer().render(
            StudentSerializer(models.Student.objects.get(id=3)).data))

        context['statuses'] = data.statuses

        return context
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        repeating_events = CourseRepeatingEvent.objects.filter(
            course_offering=self.course_offering)

        event = repeating_events.first()
        event_id = event.id if event else None

        initial_data = {
            'num_weeks': self.request.course_offering.no_weeks,
            'event_id': event_id,
            'course_id': self.request.course_offering.id,
        }

        context['initial_data'] = CamelCaseJSONRenderer().render(initial_data)
        context['repeating_events'] = repeating_events

        return context
Esempio n. 9
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        student_id = kwargs.get('pk')
        student = get_object_or_404(
            LMSUser,
            pk=student_id,
            course_offering=self.request.course_offering)

        initial_data = {
            'course_id': self.request.course_offering.id,
            'course_start': self.request.course_offering.start_date,
            'num_weeks': self.request.course_offering.no_weeks,
            'student_id': student.id,
        }

        context['initial_data'] = CamelCaseJSONRenderer().render(initial_data)
        context['student'] = student

        return context
Esempio n. 10
0
 def test_validation_error_detail_field_camelcase_renderer(self):
     data = {'name': 'valid', 'value': 'valid', 'underscore_field': 'none'}
     serializer = TestSerializer(data=data)
     try:
         serializer.is_valid(raise_exception=True)
     except Exception as exc:
         context = {'view': views.APIView(), 'request': None}
         context['view'].perform_content_negotiation = \
             MagicMock(return_value=(CamelCaseJSONRenderer(), 'application/json'))
         resp = handlers.error_list_exception_handler(exc, context)
         assert resp.status_code == 400
         assert resp.data == {
             'errors': [
                 {
                     'code': 'invalid',
                     'message': 'cant use none',
                     'source': '/underscoreField',
                 },
             ]
         }
Esempio n. 11
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        resource_id = kwargs.get('pk')
        page = get_object_or_404(Page,
                                 pk=resource_id,
                                 course_offering=self.request.course_offering)

        initial_data = {
            'course_id': self.request.course_offering.id,
            'course_start': self.request.course_offering.start_date,
            'num_weeks': self.request.course_offering.no_weeks,
            'resource_id': page.id,
            'resource_type': page.get_page_type(),
        }
        context['initial_data'] = CamelCaseJSONRenderer().render(initial_data)

        context['resource_page'] = page

        return context
Esempio n. 12
0
def match(request):
    '''Makes and returns a new match.'''
    if request.method == 'POST':
        data = process_post_request(request)
        match_serializer = MatchSerializer(data=data)
        if match_serializer.is_valid():
            new_match_obj = match_serializer.create(data)
            participation = Participation(
                user=USER.objects.get(pk=request.user.id), match=new_match_obj)
            participation.save()
            new_match_data = match_serializer.validated_data
            new_match_data.update({
                "id": new_match_obj.pk,
                'num_participants': 1
            })
            response = json.loads(
                CamelCaseJSONRenderer().render(new_match_data))
            return JsonResponse(response, status=201)
        # 400
        return HttpResponseBadRequest()
    # 405
    return HttpResponseNotAllowed(['POST'])
Esempio n. 13
0
def send_notifications(topic, action, filterset, data, obj_name=None):
    CHANNEL_NAME = '{}.{}'.format(settings.SERVICE_SHORT_NAME, topic)
    REDIS_PREFIX = 'broker'
    connection = redis.Redis(
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        db=settings.REDIS_AUTH_DB,
    )

    payload = {
        'action': action,
        'object': obj_name,
        'payload': json.loads(CamelCaseJSONRenderer().render(data)),
    }

    redis_data = {
        'subscription': CHANNEL_NAME,
        'data': payload,
    }
    redis_data.update(filterset)
    return connection.publish('{}{}'.format(REDIS_PREFIX, CHANNEL_NAME),
                              json.dumps(redis_data))
Esempio n. 14
0
def camelize(data):
    camel_case_bytes = CamelCaseJSONRenderer().render(data)
    return json.loads(camel_case_bytes.decode("utf-8"))
Esempio n. 15
0
 def resolve_filters(root, info, **kwargs):
     # XXX: Better way?
     return json.loads(CamelCaseJSONRenderer().render(root.filters))
Esempio n. 16
0
 def run(self, *args, **kwargs):
     uuid = kwargs.get('uuid')
     event = kwargs.get('event')
     payload = json.loads(CamelCaseJSONRenderer().render(
         kwargs.get('payload')))
     analytics.track(uuid, event, payload)
Esempio n. 17
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Pageview Graph - Content
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # summary_course_visits = SummaryCourseVisitsByDayInWeek.objects.filter(date_week=course_weeks[week_no-1], course_offering=self.request.course_offering).order_by('date_dayinweek')
        # for visit in summary_course_visits:
        #     daytotal[visit.date_dayinweek] = visit.pageviews
        #
        # PageViewGraphContentList = ','.join(map(str, daytotal))

        # # Pageview Graph - Communication
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, Pageviews FROM Summary_CourseCommunicationVisitsByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # PageViewGraphCommunicationList = ','.join(map(str, daytotal))
        #
        # # Pageview Graph - Assessment
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, Pageviews FROM Summary_CourseAssessmentVisitsByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # PageViewGraphAssessmentList = ','.join(map(str, daytotal))
        #
        # # Pageview Graph - Unique Views
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, Pageviews FROM Summary_UniquePageViewsByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # PageViewGraphUniqueViewsList = ','.join(map(str, daytotal))
        #
        # # Sparkline - Unique Pageviews
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, Pageviews FROM Summary_UniquePageViewsByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # uniquepageviewsbydayinweek = ','.join(map(str, daytotal))
        #
        # # Sparkline - Participating Users
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, Pageviews FROM Summary_ParticipatingUsersByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # participantsbydayinweek = ','.join(map(str, daytotal))
        #
        # # Sparkline - Sessions by Day in Week
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, sessions FROM Summary_SessionsByDayInWeek WHERE DATE_WEEK = %d AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # sessionsbydayinweek = ','.join(map(str, daytotal))
        #
        # # Sparkline - Average Session Length by Day in Week
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, session_average_in_minutes FROM Summary_SessionAverageLengthByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # averagesessionlengthbydayinweek = ','.join(map(str, daytotal))
        #
        # # Sparkline - Average Pages Per Session by Day in Week
        # daytotal = [0, 0, 0, 0, 0, 0, 0]
        # sql = "SELECT Date_dayinweek, pages_per_session FROM Summary_SessionAveragePagesPerSessionByDayInWeek WHERE DATE_WEEK = %d  AND course_id=%d ORDER BY Date_dayinweek;" % (
        # course_weeks[week_no - 1], course_id)
        # row_count = cursor.execute(sql);
        # result = cursor.fetchall()
        # for dayidx, row in enumerate(result):
        #     try:
        #         daytotal[int(row[0])] = int(row[1])
        #     except IndexError:
        #         print('Index Error')
        #
        # averagepagespersessionbydayinweek = ','.join(map(str, daytotal))
        #
        # histogram = generate_userbyweek_histogram(week_id, course_id)
        #
        # communication_types, assessment_types, communication_types_str, assessment_types_str = get_contenttypes(
        #     course_type)
        #
        # excluse_contentype_list = communication_types + assessment_types
        # excluse_contentype_str = ','.join("'{0}'".format(x) for x in excluse_contentype_list)
        #
        # # Top Content
        # sql = "SELECT SUM(F.pageview) AS Pageviews, F.page_id, P.title, F.module, F.action, F.url, P.order_no FROM dim_dates D LEFT JOIN fact_coursevisits F ON D.Id = F.Date_Id JOIN dim_pages P ON F.page_id=P.content_id  WHERE F.page_id!=0 AND F.module NOT IN (%s) AND D.Date_dayinweek IN (0,1,2,3,4,5,6) AND D.DATE_week IN (%s) AND F.course_id=%d GROUP BY F.page_id ORDER BY Pageviews DESC LIMIT 10;" % (
        # excluse_contentype_str, course_weeks[week_no - 1], course_id)
        # cursor.execute(sql);
        # topcontent_resultset = cursor.fetchall()
        # topcontent_table = ""
        # for row in topcontent_resultset:
        #     user_cnt = str(get_userweekcount(course_weeks[week_no - 1], int(row[1]), course_id, row[3], int(row[6])))
        #     topcontent_table = topcontent_table + '<tr><td><a href="/coursepage?page_id=%s&course_id=%s">%s</a></td><td class="center">%s</td><td class="center">%s</td><td class="center">%s</td></tr>' % (
        #     row[1], str(course_id), row[2], row[3], user_cnt, row[0])
        #
        # # Top Communcation Tools
        # topforumcontent_table = ""
        # sql = "SELECT SUM(F.pageview) AS Pageviews, F.page_id, P.title, F.module, F.action, F.url, P.order_no FROM dim_dates  D LEFT JOIN fact_coursevisits F ON D.Id = F.Date_Id JOIN dim_pages P ON F.page_id=P.content_id WHERE F.page_id!=0 AND F.module IN (%s) AND D.Date_dayinweek IN (0,1,2,3,4,5,6) AND D.DATE_week IN (%s) AND F.course_id=%d GROUP BY F.page_id ORDER BY Pageviews DESC LIMIT 10;" % (
        # communication_types_str, course_weeks[week_no - 1], course_id)
        # cursor.execute(sql);
        # topforumcontent_resultset = cursor.fetchall()
        # topforumcontent_table = ""
        # for row in topforumcontent_resultset:
        #     user_cnt = str(get_userweekcount(course_weeks[week_no - 1], int(row[1]), course_id, row[3], int(row[6])))
        #     no_posts = get_noforumposts(int(row[1]), course_id, course_weeks[week_no - 1])
        #     # no_participants = getusercount(3,1)
        #     topforumcontent_table = topforumcontent_table + '<tr><td><a href="/coursepage?page_id=%s&course_id=%s">%s</a></td><td class="center">%s</td><td class="center">%s</td><td class="center">%s</td><td class="center">%d</td></tr>' % (
        #     row[1], str(course_id), row[2], row[3], user_cnt, row[0], no_posts)
        #
        # # Top Assessment Items
        # sql = "SELECT SUM(F.pageview) AS Pageviews, F.page_id, P.title, F.module, F.action, F.url, P.order_no FROM dim_dates  D LEFT JOIN fact_coursevisits F ON D.Id = F.Date_Id JOIN dim_pages P ON F.page_id=P.content_id WHERE F.page_id!=0 AND F.module IN (%s) AND D.Date_dayinweek IN (0,1,2,3,4,5,6) AND D.DATE_week IN (%s) AND F.course_id=%d GROUP BY F.page_id ORDER BY Pageviews DESC LIMIT 10;" % (
        # assessment_types_str, course_weeks[week_no - 1], course_id)
        # cursor.execute(sql);
        # topquizcontent_resultset = cursor.fetchall()
        # topquizcontent_table = ""
        # for row in topquizcontent_resultset:
        #     user_cnt = str(get_quizusercount(course_weeks[week_no - 1], int(row[1]),
        #                                      course_id))  # str(get_userweekcount(course_weeks[week_no-1],int(row[1]),  course_id, row[3], int(row[6])))
        #     attempts = str(get_quizattemps(int(row[1]), course_id, unixstart=begweek_unix, unixend=endweek_unix))
        #     averagestudentscore = str(
        #         get_avggrade(int(row[1]), course_id, unixstart=begweek_unix, unixend=endweek_unix))
        #     topquizcontent_table = topquizcontent_table + '<tr><td><a href="/coursepage?page_id=%s&course_id=%s">%s</a></td><td class="center">%s</td><td class="center">%s</td><td class="center">%s</td><td class="center">%s</td></tr>' % (
        #     row[1], str(course_id), row[2], row[3], user_cnt, attempts, averagestudentscore)
        #
        # # Top Users/Students
        # sql = "SELECT COUNT(F.pageview) AS Pageviews, U.Firstname, U.Lastname, U.Role, F.user_id FROM dim_dates  D LEFT JOIN fact_coursevisits F ON D.Id = F.Date_Id JOIN dim_users U ON F.user_id=U.lms_user_id  WHERE D.DATE_week IN (%d) AND F.course_id=%d AND U.role='Student' GROUP BY F.user_id ORDER BY Pageviews DESC LIMIT 10;" % (
        # course_weeks[week_no - 1], course_id)
        # cursor.execute(sql);
        # topusers_resultset = cursor.fetchall()
        # topusers_table = ""
        # for row in topusers_resultset:
        #     topusers_table = topusers_table + '<tr><td class="center"><a href="/coursemember?user_id=%s_%s&course_id=%s">%s</a></td><td class="center">%s</td><td class="center">%s</td><td class="center">%s</td></tr>' % (
        #     str(course_id), row[4], str(course_id), row[1], row[2], row[3], row[0])
        #
        # # get repeating events
        # repeating_evt = CourseRepeatingEvent.objects.filter(course_offering=course_offering)
        # rpt_evt_lst = ""
        # for evt in repeating_evt:
        #     rpt_evt_lst = rpt_evt_lst + "{ value: %s, color: 'green', width: 2, label: { text: '%s'}}," % (
        #     evt.day_of_week, evt.title)

        # context_dict = {'repeatingevents': rpt_evt_lst, 'course_weeks': course_weeks, 'week_id': week_id,
        #                 'weekbeg': weekbeg, 'weekend': weekend, 'PageViewGraphContentList': PageViewGraphContentList,
        #                 'PageViewGraphCommunicationList': PageViewGraphCommunicationList,
        #                 'PageViewGraphAssessmentList': PageViewGraphAssessmentList,
        #                 'PageViewGraphUniqueViewsList': PageViewGraphUniqueViewsList,
        #                 'histogram_labels': histogram["labels"], 'histogram_values': histogram["values"],
        #                 'sessionsbydayinweek': averagepagespersessionbydayinweek,
        #                 'averagesessionlengthbydayinweek': averagesessionlengthbydayinweek,
        #                 'averagepagespersessionbydayinweek': averagepagespersessionbydayinweek,
        #                 'topusers_table': topusers_table, 'topcontent_table': topcontent_table,
        #                 'topforumcontent_table': topforumcontent_table, 'topquizcontent_table': topquizcontent_table,
        #                 'course_id': course_id, 'course_code': course_code, 'course_title': course_title,
        #                 'week_no': week_no, 'uniquepageviewsbydayinweek': uniquepageviewsbydayinweek,
        #                 'participantsbydayinweek': participantsbydayinweek}

        initial_data = {
            'course_id': self.request.course_offering.id,
            'course_start': self.request.course_offering.start_date,
            'num_weeks': self.request.course_offering.no_weeks,
        }

        context['initial_data'] = CamelCaseJSONRenderer().render(initial_data)

        return context