当前位置: 首页>>代码示例>>Python>>正文


Python client.Client类代码示例

本文整理汇总了Python中analyticsclient.client.Client的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Client类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _update_active_students

def _update_active_students(course_key, section_data):
    auth_token = settings.ANALYTICS_DATA_TOKEN
    base_url = settings.ANALYTICS_DATA_URL

    section_data['active_student_count'] = 'N/A'
    section_data['active_student_count_start'] = 'N/A'
    section_data['active_student_count_end'] = 'N/A'

    try:
        client = Client(base_url=base_url, auth_token=auth_token)
        course = client.courses(unicode(course_key))

        recent_activity = course.recent_activity()
        section_data['active_student_count'] = recent_activity['count']

        def format_date(value):
            return value.split('T')[0]

        start = recent_activity['interval_start']
        end = recent_activity['interval_end']

        section_data['active_student_count_start'] = format_date(start)
        section_data['active_student_count_end'] = format_date(end)

    except (ClientError, KeyError) as e:
        log.exception(e)
开发者ID:DevCode1,项目名称:edx-platform,代码行数:26,代码来源:instructor_dashboard.py

示例2: BasePresenter

class BasePresenter(object):
    """
    This is the base class for the pages and sets up the analytics client
    for the presenters to use to access the data API.
    """

    def __init__(self, course_id, timeout=settings.ANALYTICS_API_DEFAULT_TIMEOUT):
        self.client = Client(base_url=settings.DATA_API_URL,
                             auth_token=settings.DATA_API_AUTH_TOKEN,
                             timeout=timeout)
        self.course_id = course_id
        self.course = self.client.courses(self.course_id)

    def get_current_date(self):
        return datetime.datetime.utcnow().strftime(Client.DATE_FORMAT)

    @staticmethod
    def parse_api_date(s):
        """ Parse a string according to the API date format. """
        return datetime.datetime.strptime(s, Client.DATE_FORMAT).date()

    @staticmethod
    def parse_api_datetime(s):
        """ Parse a string according to the API datetime format. """
        return datetime.datetime.strptime(s, Client.DATETIME_FORMAT)

    @staticmethod
    def strip_time(s):
        return s[:-7]

    @staticmethod
    def sum_counts(data):
        return sum(datum['count'] for datum in data)
开发者ID:CredoReference,项目名称:edx-analytics-dashboard,代码行数:33,代码来源:__init__.py

示例3: CourseView

class CourseView(LoginRequiredMixin, CourseValidMixin, CoursePermissionMixin, TemplateView):
    """
    Base course view.

    Adds conveniences such as course_id attribute, and handles 404s when retrieving data from the API.
    """
    client = None
    course = None
    course_id = None
    course_key = None
    user = None

    def dispatch(self, request, *args, **kwargs):
        self.user = request.user
        self.course_id = request.course_id
        self.course_key = request.course_key

        # some views will catch the NotFoundError to set data to a state that
        # the template can rendering a loading error message for the section
        try:
            return super(CourseView, self).dispatch(request, *args, **kwargs)
        except NotFoundError as e:
            logger.error('The requested data from the Analytics Data API was not found: %s', e)
            raise Http404
        except ClientError as e:
            logger.error('An error occurred while retrieving data from the Analytics Data API: %s', e)
            raise

    def get_context_data(self, **kwargs):
        context = super(CourseView, self).get_context_data(**kwargs)
        self.client = Client(base_url=settings.DATA_API_URL,
                             auth_token=settings.DATA_API_AUTH_TOKEN, timeout=5)
        self.course = self.client.courses(self.course_id)
        return context
开发者ID:Chirram,项目名称:edx-analytics-dashboard,代码行数:34,代码来源:__init__.py

示例4: BasePresenter

class BasePresenter(object):
    """
    This is the base class for the pages and sets up the analytics client
    for the presenters to use to access the data API.
    """

    def __init__(self, course_id, timeout=5):
        self.client = Client(base_url=settings.DATA_API_URL,
                             auth_token=settings.DATA_API_AUTH_TOKEN,
                             timeout=timeout)
        self.course_id = course_id
        self.course = self.client.courses(self.course_id)

    @staticmethod
    def parse_api_date(s):
        """ Parse a string according to the API date format. """
        return datetime.datetime.strptime(s, Client.DATE_FORMAT).date()

    @staticmethod
    def parse_api_datetime(s):
        """ Parse a string according to the API datetime format. """
        return datetime.datetime.strptime(s, Client.DATETIME_FORMAT)

    @staticmethod
    def strip_time(s):
        return s[:-7]
开发者ID:singingwolfboy,项目名称:edx-analytics-dashboard,代码行数:26,代码来源:presenters.py

示例5: CourseView

class CourseView(LoginRequiredMixin, CoursePermissionMixin, TemplateView):
    """
    Base course view.

    Adds conveniences such as course_id attribute, and handles 404s when retrieving data from the API.
    """
    client = None
    course = None
    course_id = None
    user = None

    def dispatch(self, request, *args, **kwargs):
        self.user = request.user
        self.course_id = kwargs['course_id']

        try:
            return super(CourseView, self).dispatch(request, *args, **kwargs)
        except NotFoundError:
            raise Http404

    def get_context_data(self, **kwargs):
        context = super(CourseView, self).get_context_data(**kwargs)
        self.client = Client(base_url=settings.DATA_API_URL,
                             auth_token=settings.DATA_API_AUTH_TOKEN, timeout=5)
        self.course = self.client.courses(self.course_id)
        return context
开发者ID:xiandiancloud,项目名称:edx-analytics-dashboard,代码行数:26,代码来源:views.py

示例6: get_sequential_open_distrib

def get_sequential_open_distrib(course_id, enrollment):
    """
    Returns the number of students that opened each subsection/sequential of the course

    `course_id` the course ID for the course interested in

    `enrollment` the number of students enrolled in this course.

    Outputs a dict mapping the 'module_id' to the number of students that have opened that subsection/sequential.
    """
    sequential_open_distrib = {}

    non_student_list = get_non_student_list(course_id)

    if enrollment <= settings.MAX_ENROLLEES_FOR_METRICS_USING_DB or not settings.ANALYTICS_DATA_URL:
        # Aggregate query on studentmodule table for "opening a subsection" data
        queryset = models.StudentModule.objects.filter(
            course_id__exact=course_id,
            module_type__exact='sequential',
        ).exclude(student_id__in=non_student_list).values('module_state_key').annotate(count_sequential=Count('module_state_key'))

        for row in queryset:
            module_id = course_id.make_usage_key_from_deprecated_string(row['module_state_key'])
            sequential_open_distrib[module_id] = row['count_sequential']
    else:
        # Retrieve course object down to subsection
        course = modulestore().get_course(course_id, depth=2)

        # Connect to analytics data client
        client = Client(base_url=settings.ANALYTICS_DATA_URL, auth_token=settings.ANALYTICS_DATA_TOKEN)

        for section in course.get_children():
            for subsection in section.get_children():
                module = client.modules(course_id, subsection.location)

                try:
                    sequential_open = module.sequential_open_distribution()
                except NotFoundError:
                    pass
                else:
                    sequential_open_distrib[subsection.location] = sequential_open[0]['count']

    return sequential_open_distrib
开发者ID:caesar2164,项目名称:edx-platform,代码行数:43,代码来源:dashboard_data.py

示例7: __init__

 def __init__(self, course_id, timeout=settings.ANALYTICS_API_DEFAULT_TIMEOUT):
     self.client = Client(base_url=settings.DATA_API_URL,
                          auth_token=settings.DATA_API_AUTH_TOKEN,
                          timeout=timeout)
     self.course_id = course_id
     self.course = self.client.courses(self.course_id)
开发者ID:CredoReference,项目名称:edx-analytics-dashboard,代码行数:6,代码来源:__init__.py

示例8: test_failed_authentication

    def test_failed_authentication(self):
        client = Client(base_url=self.api_url, auth_token='atoken')
        httpretty.register_uri(httpretty.GET, self.test_url, body='', status=401)

        self.assertEqual(client.has_resource(self.test_endpoint), False)
        self.assertEqual(httpretty.last_request().headers['Authorization'], 'Token atoken')
开发者ID:edx,项目名称:edx-analytics-data-api-client,代码行数:6,代码来源:test_client.py

示例9: get_context_data

 def get_context_data(self, **kwargs):
     context = super(CourseView, self).get_context_data(**kwargs)
     self.client = Client(base_url=settings.DATA_API_URL,
                          auth_token=settings.DATA_API_AUTH_TOKEN, timeout=5)
     self.course = self.client.courses(self.course_id)
     return context
开发者ID:Chirram,项目名称:edx-analytics-dashboard,代码行数:6,代码来源:__init__.py

示例10: __init__

 def __init__(self, course_id, timeout=5):
     self.client = Client(base_url=settings.DATA_API_URL,
                          auth_token=settings.DATA_API_AUTH_TOKEN,
                          timeout=timeout)
     self.course_id = course_id
     self.course = self.client.courses(self.course_id)
开发者ID:singingwolfboy,项目名称:edx-analytics-dashboard,代码行数:6,代码来源:presenters.py

示例11: get_problem_grade_distribution

def get_problem_grade_distribution(course_id, enrollment):
    """
    Returns the grade distribution per problem for the course

    `course_id` the course ID for the course interested in

    `enrollment` the number of students enrolled in this course.

    Output is 2 dicts:
      'prob-grade_distrib' where the key is the problem 'module_id' and the value is a dict with:
        'max_grade' - max grade for this problem
        'grade_distrib' - array of tuples (`grade`,`count`).
      'total_student_count' where the key is problem 'module_id' and the value is number of students
        attempting the problem
    """
    non_student_list = get_non_student_list(course_id)

    prob_grade_distrib = {}
    total_student_count = defaultdict(int)

    if enrollment <= settings.MAX_ENROLLEES_FOR_METRICS_USING_DB or not settings.ANALYTICS_DATA_URL:
        # Aggregate query on studentmodule table for grade data for all problems in course
        queryset = models.StudentModule.objects.filter(
            course_id__exact=course_id,
            grade__isnull=False,
            module_type__in=PROB_TYPE_LIST,
        ).exclude(student_id__in=non_student_list).values('module_state_key', 'grade', 'max_grade').annotate(count_grade=Count('grade'))

        # Loop through resultset building data for each problem
        for row in queryset:
            curr_problem = course_id.make_usage_key_from_deprecated_string(row['module_state_key'])

            # Build set of grade distributions for each problem that has student responses
            if curr_problem in prob_grade_distrib:
                prob_grade_distrib[curr_problem]['grade_distrib'].append((row['grade'], row['count_grade']))

                if ((prob_grade_distrib[curr_problem]['max_grade'] != row['max_grade']) and
                        (prob_grade_distrib[curr_problem]['max_grade'] < row['max_grade'])):
                    prob_grade_distrib[curr_problem]['max_grade'] = row['max_grade']

            else:
                prob_grade_distrib[curr_problem] = {
                    'max_grade': row['max_grade'],
                    'grade_distrib': [(row['grade'], row['count_grade']), ],
                }

            # Build set of total students attempting each problem
            total_student_count[curr_problem] += row['count_grade']
    else:
        # Retrieve course object down to problems
        course = modulestore().get_course(course_id, depth=4)

        # Connect to analytics data client
        client = Client(base_url=settings.ANALYTICS_DATA_URL, auth_token=settings.ANALYTICS_DATA_TOKEN)

        for section in course.get_children():
            for subsection in section.get_children():
                for unit in subsection.get_children():
                    for child in unit.get_children():
                        if child.location.category not in PROB_TYPE_LIST:
                            continue

                        problem_id = child.location
                        problem = client.modules(course_id, problem_id)

                        try:
                            grade_distribution = problem.grade_distribution()
                        except NotFoundError:
                            grade_distribution = []

                        for score in grade_distribution:
                            total_student_count[problem_id] += score['count']

                            if problem_id in prob_grade_distrib:
                                if prob_grade_distrib[problem_id]['max_grade'] < score['max_grade']:
                                    prob_grade_distrib[problem_id]['max_grade'] = score['max_grade']

                                prob_grade_distrib[problem_id]['grade_distrib'].append((score['grade'], score['count']))
                            else:
                                prob_grade_distrib[problem_id] = {
                                    'max_grade': score['max_grade'],
                                    'grade_distrib': [(score['grade'], score['count']), ],
                                }

    return prob_grade_distrib, total_student_count
开发者ID:caesar2164,项目名称:edx-platform,代码行数:85,代码来源:dashboard_data.py

示例12: get_problem_set_grade_distrib

def get_problem_set_grade_distrib(course_id, problem_set, enrollment):
    """
    Returns the grade distribution for the problems specified in `problem_set`.

    `course_id` the course ID for the course interested in

    `problem_set` an array of UsageKeys representing problem module_id's.

    `enrollment` the number of students enrolled in this course.

    Requests from the database the a count of each grade for each problem in the `problem_set`.

    Returns a dict, where the key is the problem 'module_id' and the value is a dict with two parts:
      'max_grade' - the maximum grade possible for the course
      'grade_distrib' - array of tuples (`grade`,`count`) ordered by `grade`
    """

    non_student_list = get_non_student_list(course_id)

    prob_grade_distrib = {}

    if enrollment <= settings.MAX_ENROLLEES_FOR_METRICS_USING_DB or not settings.ANALYTICS_DATA_URL:
        # Aggregate query on studentmodule table for grade data for set of problems in course
        queryset = models.StudentModule.objects.filter(
            course_id__exact=course_id,
            grade__isnull=False,
            module_type__in=PROB_TYPE_LIST,
            module_state_key__in=problem_set,
        ).exclude(student_id__in=non_student_list).values(
            'module_state_key',
            'grade',
            'max_grade',
        ).annotate(count_grade=Count('grade')).order_by('module_state_key', 'grade')

        # Loop through resultset building data for each problem
        for row in queryset:
            problem_id = course_id.make_usage_key_from_deprecated_string(row['module_state_key'])
            if problem_id not in prob_grade_distrib:
                prob_grade_distrib[problem_id] = {
                    'max_grade': 0,
                    'grade_distrib': [],
                }

            curr_grade_distrib = prob_grade_distrib[problem_id]
            curr_grade_distrib['grade_distrib'].append((row['grade'], row['count_grade']))

            if curr_grade_distrib['max_grade'] < row['max_grade']:
                curr_grade_distrib['max_grade'] = row['max_grade']
    else:
        # Connect to analytics data client
        client = Client(base_url=settings.ANALYTICS_DATA_URL, auth_token=settings.ANALYTICS_DATA_TOKEN)

        for problem in problem_set:
            module = client.modules(course_id, problem)

            try:
                grade_distribution = module.grade_distribution()
            except NotFoundError:
                grade_distribution = []

            for score in grade_distribution:
                if problem in prob_grade_distrib:
                    if prob_grade_distrib[problem]['max_grade'] < score['max_grade']:
                        prob_grade_distrib[problem]['max_grade'] = score['max_grade']

                    prob_grade_distrib[problem]['grade_distrib'].append((score['grade'], score['count']))
                else:
                    prob_grade_distrib[problem] = {
                        'max_grade': score['max_grade'],
                        'grade_distrib': [(score['grade'], score['count'])],
                    }

    return prob_grade_distrib
开发者ID:caesar2164,项目名称:edx-platform,代码行数:73,代码来源:dashboard_data.py

示例13: __init__

 def __init__(self):
     View.__init__(self)
     self.analytics_client = Client(base_url=settings.ANALYTICS_API_URL, auth_token=settings.ANALYTICS_API_KEY)
开发者ID:cmscom,项目名称:edx-platform,代码行数:3,代码来源:views.py

示例14: LearnerAnalyticsView

class LearnerAnalyticsView(View):
    """
    Displays the Learner Analytics Dashboard.
    """
    def __init__(self):
        View.__init__(self)
        self.analytics_client = Client(base_url=settings.ANALYTICS_API_URL, auth_token=settings.ANALYTICS_API_KEY)

    @method_decorator(login_required)
    @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True))
    @method_decorator(ensure_valid_course_key)
    def get(self, request, course_id):
        """
        Displays the user's Learner Analytics for the specified course.

        Arguments:
            request: HTTP request
            course_id (unicode): course id
        """
        course_key = CourseKey.from_string(course_id)
        if not ENABLE_DASHBOARD_TAB.is_enabled(course_key):
            raise Http404

        course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True)
        course_url_name = default_course_url_name(course.id)
        course_url = reverse(course_url_name, kwargs={'course_id': unicode(course.id)})

        is_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key)
        has_access = is_verified or request.user.is_staff

        enrollment = CourseEnrollment.get_enrollment(request.user, course_key)

        upgrade_price = None
        upgrade_url = None

        if enrollment and enrollment.upgrade_deadline:
            upgrade_url = EcommerceService().upgrade_url(request.user, course_key)
            upgrade_price = get_cosmetic_verified_display_price(course)

        context = {
            'upgrade_price': upgrade_price,
            'upgrade_link': upgrade_url,
            'course': course,
            'course_url': course_url,
            'disable_courseware_js': True,
            'uses_pattern_library': True,
            'is_self_paced': course.self_paced,
            'is_verified': is_verified,
            'has_access': has_access,
        }

        if (has_access):
            grading_policy = course.grading_policy

            (raw_grade_data, answered_percent, percent_grade) = self.get_grade_data(request.user, course_key, grading_policy['GRADE_CUTOFFS'])
            raw_schedule_data = self.get_assignments_with_due_date(request, course_key)

            grade_data, schedule_data = self.sort_grade_and_schedule_data(raw_grade_data, raw_schedule_data)

            # TODO: LEARNER-3854: Fix hacked defaults with real error handling if implementing Learner Analytics.
            try:
                weekly_active_users = self.get_weekly_course_activity_count(course_key)
                week_streak = self.consecutive_weeks_of_course_activity_for_user(
                    request.user.username, course_key
                )
            except Exception as e:
                logging.exception(e)
                weekly_active_users = 134
                week_streak = 1

            context.update({
                'grading_policy': grading_policy,
                'assignment_grades': grade_data,
                'answered_percent': answered_percent,
                'assignment_schedule': schedule_data,
                'assignment_schedule_raw': raw_schedule_data,
                'profile_image_urls': get_profile_image_urls_for_user(request.user, request),
                'discussion_info': self.get_discussion_data(request, course_key),
                'passing_grade': math.ceil(100 * course.lowest_passing_grade),
                'percent_grade': math.ceil(100 * percent_grade),
                'weekly_active_users': weekly_active_users,
                'week_streak': week_streak,
            })

        return render_to_response('learner_analytics/dashboard.html', context)

    def get_grade_data(self, user, course_key, grade_cutoffs):
        """
        Collects and formats the grades data for a particular user and course.

        Args:
            user (User)
            course_key (CourseKey)
            grade_cutoffs: # TODO: LEARNER-3854: Complete docstring if implementing Learner Analytics.
        """
        course_grade = CourseGradeFactory().read(user, course_key=course_key)
        grades = []
        total_earned = 0
        total_possible = 0
        # answered_percent seems to be unused and it does not take into account assignment type weightings
#.........这里部分代码省略.........
开发者ID:cmscom,项目名称:edx-platform,代码行数:101,代码来源:views.py


注:本文中的analyticsclient.client.Client类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。