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


Python models.anonymous_id_for_user函数代码示例

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


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

示例1: handle

    def handle(self, *args, **options):
        course_key = CourseKey.from_string(options['course_id'])

        # Generate the output filename from the course ID.
        # Change slashes to dashes first, and then append .csv extension.
        output_filename = course_key.to_deprecated_string().replace('/', '-') + ".csv"

        # Figure out which students are enrolled in the course
        students = User.objects.filter(courseenrollment__course_id=course_key)
        if len(students) == 0:
            self.stdout.write("No students enrolled in %s" % course_key.to_deprecated_string())
            return

        # Write mapping to output file in CSV format with a simple header
        try:
            with open(output_filename, 'wb') as output_file:
                csv_writer = csv.writer(output_file)
                csv_writer.writerow((
                    "User ID",
                    "Per-Student anonymized user ID",
                    "Per-course anonymized user id"
                ))
                for student in students:
                    csv_writer.writerow((
                        student.id,
                        anonymous_id_for_user(student, None),
                        anonymous_id_for_user(student, course_key)
                    ))
        except IOError:
            raise CommandError("Error writing to file: %s" % output_filename)
开发者ID:auvipy,项目名称:edx-platform,代码行数:30,代码来源:anonymized_id_mapping.py

示例2: test_roundtrip_with_unicode_course_id

 def test_roundtrip_with_unicode_course_id(self):
     course2 = CourseFactory.create(display_name=u"Omega Course Ω")
     CourseEnrollment.enroll(self.user, course2.id)
     anonymous_id = anonymous_id_for_user(self.user, course2.id)
     real_user = user_by_anonymous_id(anonymous_id)
     self.assertEqual(self.user, real_user)
     self.assertEqual(anonymous_id, anonymous_id_for_user(self.user, course2.id, save=False))
开发者ID:Stanford-Online,项目名称:edx-platform,代码行数:7,代码来源:tests.py

示例3: handle

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Usage: unique_id_mapping %s" % " ".join(("<%s>" % arg for arg in Command.args)))

        course_id = args[0]

        # Generate the output filename from the course ID.
        # Change slashes to dashes first, and then append .csv extension.
        output_filename = course_id.replace("/", "-") + ".csv"

        # Figure out which students are enrolled in the course
        students = User.objects.filter(courseenrollment__course_id=course_id)
        if len(students) == 0:
            self.stdout.write("No students enrolled in %s" % course_id)
            return

        # Write mapping to output file in CSV format with a simple header
        try:
            with open(output_filename, "wb") as output_file:
                csv_writer = csv.writer(output_file)
                csv_writer.writerow(("User ID", "Per-Student anonymized user ID", "Per-course anonymized user id"))
                for student in students:
                    csv_writer.writerow(
                        (student.id, anonymous_id_for_user(student, ""), anonymous_id_for_user(student, course_id))
                    )
        except IOError:
            raise CommandError("Error writing to file: %s" % output_filename)
开发者ID:XiaodunServerGroup,项目名称:medicalmooc,代码行数:27,代码来源:anonymized_id_mapping.py

示例4: test_secret_key_changes

 def test_secret_key_changes(self):
     """Test that a new anonymous id is returned when the secret key changes."""
     CourseEnrollment.enroll(self.user, self.course.id)
     anonymous_id = anonymous_id_for_user(self.user, self.course.id)
     with override_settings(SECRET_KEY='some_new_and_totally_secret_key'):
         # Recreate user object to clear cached anonymous id.
         self.user = User.objects.get(pk=self.user.id)
         new_anonymous_id = anonymous_id_for_user(self.user, self.course.id)
         self.assertNotEqual(anonymous_id, new_anonymous_id)
         self.assertEqual(self.user, user_by_anonymous_id(anonymous_id))
         self.assertEqual(self.user, user_by_anonymous_id(new_anonymous_id))
开发者ID:Stanford-Online,项目名称:edx-platform,代码行数:11,代码来源:tests.py

示例5: test_delete_student_state_resets_scores

    def test_delete_student_state_resets_scores(self):
        problem_location = self.course.id.make_usage_key('dummy', 'module')

        # Create a student module for the user
        StudentModule.objects.create(
            student=self.student,
            course_id=self.course.id,
            module_state_key=problem_location,
            state=json.dumps({})
        )

        # Create a submission and score for the student using the submissions API
        student_item = {
            'student_id': anonymous_id_for_user(self.student, self.course.id),
            'course_id': self.course.id.to_deprecated_string(),
            'item_id': problem_location.to_deprecated_string(),
            'item_type': 'openassessment'
        }
        submission = sub_api.create_submission(student_item, 'test answer')
        sub_api.set_score(submission['uuid'], 1, 2)

        # Delete student state using the instructor dash
        url = reverse('instructor_dashboard_legacy', kwargs={'course_id': self.course.id.to_deprecated_string()})
        response = self.client.post(url, {
            'action': 'Delete student state for module',
            'unique_student_identifier': self.student.email,
            'problem_for_student': problem_location.to_deprecated_string(),
        })

        self.assertEqual(response.status_code, 200)

        # Verify that the student's scores have been reset in the submissions API
        score = sub_api.get_score(student_item)
        self.assertIs(score, None)
开发者ID:hongsly,项目名称:edx-platform,代码行数:34,代码来源:test_legacy_reset.py

示例6: _create_response_row

 def _create_response_row(self):
     user_profile = UserProfile.objects.get(user__username=self.username)
     response_row = [unicode(x) for x in [anonymize_username(user_profile.user.username),
                                          anonymous_id_for_user(user_profile.user, self.course.id),
                                          user_profile.gender, user_profile.year_of_birth,
                                          user_profile.level_of_education]] + [OPTION_1, OPTION_2]
     return response_row
开发者ID:jgrynber,项目名称:fun-apps,代码行数:7,代码来源:test_tasks.py

示例7: build_token

    def build_token(self, scopes, expires_in, aud=None):
        """Returns a JWT access token.

        Arguments:
            scopes (list): Scopes controlling which optional claims are included in the token.
            expires_in (int): Time to token expiry, specified in seconds.

        Keyword Arguments:
            aud (string): Overrides configured JWT audience claim.
        """
        now = int(time())
        payload = {
            'aud': aud if aud else self.jwt_auth['JWT_AUDIENCE'],
            'exp': now + expires_in,
            'iat': now,
            'iss': self.jwt_auth['JWT_ISSUER'],
            'preferred_username': self.user.username,
            'scopes': scopes,
            'sub': anonymous_id_for_user(self.user, None),
        }

        for scope in scopes:
            handler = self.claim_handlers.get(scope)

            if handler:
                handler(payload)

        return self.encode(payload)
开发者ID:CraftAcademy,项目名称:edx-platform,代码行数:28,代码来源:token_utils.py

示例8: test_delete_submission_scores

    def test_delete_submission_scores(self):
        user = UserFactory()
        course_id = 'ora2/1/1'
        item_id = 'i4x://ora2/1/openassessment/b3dce2586c9c4876b73e7f390e42ef8f'

        # Create a student module for the user
        StudentModule.objects.create(
            student=user, course_id=course_id, module_state_key=item_id, state=json.dumps({})
        )

        # Create a submission and score for the student using the submissions API
        student_item = {
            'student_id': anonymous_id_for_user(user, course_id),
            'course_id': course_id,
            'item_id': item_id,
            'item_type': 'openassessment'
        }
        submission = sub_api.create_submission(student_item, 'test answer')
        sub_api.set_score(submission['uuid'], 1, 2)

        # Delete student state using the instructor dash
        reset_student_attempts(course_id, user, item_id, delete_module=True)

        # Verify that the student's scores have been reset in the submissions API
        score = sub_api.get_score(student_item)
        self.assertIs(score, None)
开发者ID:DazzaGreenwood,项目名称:edx-platform,代码行数:26,代码来源:test_enrollment.py

示例9: test_post_submission_for_student_on_accessing

    def test_post_submission_for_student_on_accessing(self):
        course = get_course_with_access(self.student_on_accessing, self.course_id, "load")

        dry_run_result = post_submission_for_student(
            self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=True
        )
        self.assertFalse(dry_run_result)

        with patch("capa.xqueue_interface.XQueueInterface.send_to_queue") as mock_send_to_queue:
            mock_send_to_queue.return_value = (0, "Successfully queued")

            module = get_module_for_student(self.student_on_accessing, course, self.problem_location)
            task = module.child_module.get_task_number(self.open_ended_task_number)

            qtime = datetime.strftime(datetime.now(UTC), xqueue_interface.dateformat)
            student_info = {
                "anonymous_student_id": anonymous_id_for_user(self.student_on_accessing, ""),
                "submission_time": qtime,
            }

            contents = task.payload.copy()
            contents.update(
                {"max_score": 2, "student_info": json.dumps(student_info), "student_response": "Here is an answer."}
            )

            result = post_submission_for_student(
                self.student_on_accessing, course, self.problem_location, self.open_ended_task_number, dry_run=False
            )
            self.assertTrue(result)
            mock_send_to_queue.assert_called_with(body=json.dumps(contents), header=ANY)
开发者ID:neozhangthe1,项目名称:edx-platform,代码行数:30,代码来源:test_openended_commands.py

示例10: __init__

 def __init__(self, user, gea_xblock):
     self.submission_id = {"item_id": gea_xblock.location,
                           "item_type": 'gea',
                           "course_id": gea_xblock.course_id,
                           "student_id": anonymous_id_for_user(user,
                                                               gea_xblock.course_id)}
     """dict: Used to determine which course, student, and location a submission belongs to."""
开发者ID:openfun,项目名称:edx-gea,代码行数:7,代码来源:gea_assessment.py

示例11: delete_all_notes_for_user

def delete_all_notes_for_user(user):
    """
    helper method to delete all notes for a user, as part of GDPR compliance

    :param user: The user object associated with the deleted notes
    :return: response (requests) object

    Raises:
        EdxNotesServiceUnavailable - when notes api is not found/misconfigured.
    """
    url = get_internal_endpoint('retire_annotations')
    headers = {
        "x-annotator-auth-token": get_edxnotes_id_token(user),
    }
    data = {
        "user": anonymous_id_for_user(user, None)
    }
    try:
        response = requests.post(
            url=url,
            headers=headers,
            data=data,
            timeout=(settings.EDXNOTES_CONNECT_TIMEOUT, settings.EDXNOTES_READ_TIMEOUT)
        )
    except RequestException:
        log.error(u"Failed to connect to edx-notes-api: url=%s, params=%s", url, str(headers))
        raise EdxNotesServiceUnavailable(_("EdxNotes Service is unavailable. Please try again in a few minutes."))

    return response
开发者ID:edx,项目名称:edx-platform,代码行数:29,代码来源:helpers.py

示例12: user_id_sub

    def user_id_sub(user, course):
        """
        Gives the anonymous id for the given user

        For compatibility with the existing anon_ids, return anon_id without course_id
        """
        return anonymous_id_for_user(user, None)
开发者ID:Taxellool,项目名称:edx-platform,代码行数:7,代码来源:startup.py

示例13: get_id_token

def get_id_token(user):
    """
    Return a JWT for `user`, suitable for use with the course discovery service.

    Arguments:
        user (User): User for whom to generate the JWT.

    Returns:
        str: The JWT.
    """
    try:
        # Service users may not have user profiles.
        full_name = UserProfile.objects.get(user=user).name
    except UserProfile.DoesNotExist:
        full_name = None

    now = datetime.datetime.utcnow()
    expires_in = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)

    payload = {
        'preferred_username': user.username,
        'name': full_name,
        'email': user.email,
        'administrator': user.is_staff,
        'iss': configuration_helpers.get_value('OAUTH_OIDC_ISSUER', settings.OAUTH_OIDC_ISSUER),
        'exp': now + datetime.timedelta(seconds=expires_in),
        'iat': now,
        'aud': configuration_helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_AUDIENCE'],
        'sub': anonymous_id_for_user(user, None),
    }
    secret_key = configuration_helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']

    return jwt.encode(payload, secret_key).decode('utf-8')
开发者ID:edx-solutions,项目名称:edx-platform,代码行数:33,代码来源:utils.py

示例14: test_delete_submission_scores

    def test_delete_submission_scores(self, _lti_mock):
        user = UserFactory()
        problem_location = self.course_key.make_usage_key("dummy", "module")

        # Create a student module for the user
        StudentModule.objects.create(
            student=user, course_id=self.course_key, module_state_key=problem_location, state=json.dumps({})
        )

        # Create a submission and score for the student using the submissions API
        student_item = {
            "student_id": anonymous_id_for_user(user, self.course_key),
            "course_id": self.course_key.to_deprecated_string(),
            "item_id": problem_location.to_deprecated_string(),
            "item_type": "openassessment",
        }
        submission = sub_api.create_submission(student_item, "test answer")
        sub_api.set_score(submission["uuid"], 1, 2)

        # Delete student state using the instructor dash
        reset_student_attempts(self.course_key, user, problem_location, requesting_user=user, delete_module=True)

        # Verify that the student's scores have been reset in the submissions API
        score = sub_api.get_score(student_item)
        self.assertIs(score, None)
开发者ID:longmen21,项目名称:edx-platform,代码行数:25,代码来源:test_enrollment.py

示例15: get_anon_ids

def get_anon_ids(request, course_id):  # pylint: disable=W0613
    """
    Respond with 2-column CSV output of user-id, anonymized-user-id
    """
    # TODO: the User.objects query and CSV generation here could be
    # centralized into analytics. Currently analytics has similar functionality
    # but not quite what's needed.
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    def csv_response(filename, header, rows):
        """Returns a CSV http response for the given header and rows (excel/utf-8)."""
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
        writer = csv.writer(response, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL)
        # In practice, there should not be non-ascii data in this query,
        # but trying to do the right thing anyway.
        encoded = [unicode(s).encode('utf-8') for s in header]
        writer.writerow(encoded)
        for row in rows:
            encoded = [unicode(s).encode('utf-8') for s in row]
            writer.writerow(encoded)
        return response

    students = User.objects.filter(
        courseenrollment__course_id=course_id,
    ).order_by('id')
    header = ['User ID', 'Anonymized user ID', 'Course Specific Anonymized user ID']
    rows = [[s.id, unique_id_for_user(s), anonymous_id_for_user(s, course_id)] for s in students]
    return csv_response(course_id.to_deprecated_string().replace('/', '-') + '-anon-ids.csv', header, rows)
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:28,代码来源:api.py


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