Exemple #1
0
def generate_csv(heve_details_id, target_path):
    client = APIClient()
    response = client.get(
        "/gfdrr_det/api/v1/vulnerabilities/{}/".format(heve_details_id),
        {"format": "csv"})
    response_data = response.data.copy()
    response_data["url"] = response_data["url"].replace(
        "testserver",
        Site.objects.get_current().domain)
    renderer = CSVRenderer()
    contents = renderer.render(response_data)
    with open(target_path, "w") as file_handler:
        file_handler.write(contents)
class CourseIndexCSV(AnalyticsV1Mixin, CourseAPIMixin, LoginRequiredMixin,
                     DatetimeCSVResponseMixin, TemplateView):

    csv_filename_suffix = 'course-list'
    # Note: we are not using the DRF "renderer_classes" field here because this is a Django view, not a DRF view.
    # We will call the render function on the renderer directly instead.
    renderer = CSVRenderer()
    exclude_fields = {
        '': ('created', ),
        'enrollment_modes': {
            'audit': ('count_change_7_days', ),
            'credit': ('count_change_7_days', ),
            'honor': ('count_change_7_days', ),
            'professional': ('count_change_7_days', ),
            'verified': ('count_change_7_days', ),
            'masters': ('count_change_7_days', ),
        }
    }

    def get_data(self):
        user = self.request.user
        courses = permissions.get_user_course_permissions(user)
        if not courses and not (user.is_superuser or user.is_staff):
            # The user is probably not a course administrator and should not be using this application.
            raise PermissionDenied

        enable_course_filters = switch_is_active('enable_course_filters')

        presenter = CourseSummariesPresenter(
            analytics_client=self.analytics_client)
        summaries, _ = presenter.get_course_summaries(courses)

        if not summaries:
            # Instead of returning a useless blank CSV, return a 404 error
            raise Http404

        # Exclude specified fields from each summary entry
        summaries = [
            remove_keys(summary, self.exclude_fields) for summary in summaries
        ]

        if enable_course_filters:
            # Add list of associated program IDs to each summary entry
            programs_presenter = ProgramsPresenter(
                analytics_client=self.analytics_client)
            programs = programs_presenter.get_programs(course_ids=courses)
            for summary in summaries:
                summary_programs = [
                    program for program in programs
                    if summary['course_id'] in program['course_ids']
                ]
                summary['program_ids'] = ' | '.join(
                    [program['program_id'] for program in summary_programs])
                summary['program_titles'] = ' | '.join(
                    [program['program_title'] for program in summary_programs])

        summaries_csv = self.renderer.render(summaries)
        return summaries_csv
Exemple #3
0
 def render(self, data, *args, **kwargs):
     if not isinstance(data, list) and self.results_field in data:
         data = data[self.results_field]
     if isinstance(data, list):
         response = super(PaginatedCSVRenderer, self).render(data, *args, **kwargs)
     else:
         response = CSVRenderer.render(self, data, *args, **kwargs)
     request = args[1]['request']
     headers = args[1]['response']._headers
     headers['content-disposition'] = (
         'Content-Disposition', 'attachment; filename="{}.csv"'.format(get_name(request))
     )
     return response
class CourseIndexCSV(CourseAPIMixin, LoginRequiredMixin, DatetimeCSVResponseMixin, TemplateView):

    csv_filename_suffix = 'course-list'
    # Note: we are not using the DRF "renderer_classes" field here because this is a Django view, not a DRF view.
    # We will call the render function on the renderer directly instead.
    renderer = CSVRenderer()

    def get_data(self):
        courses = permissions.get_user_course_permissions(self.request.user)
        if not courses:
            # The user is probably not a course administrator and should not be using this application.
            raise PermissionDenied

        presenter = CourseSummariesPresenter()
        summaries, _ = presenter.get_course_summaries(courses)
        if not summaries:
            # Instead of returning a useless blank CSV, return a 404 error
            raise Http404
        summaries_csv = self.renderer.render(summaries)
        return summaries_csv
    def csv(self, request, subscription_uuid):  # pylint: disable=unused-argument
        """
        Returns license data for a given subscription in CSV format.

        Only includes licenses with a status of ACTIVATED, ASSIGNED, or REVOKED.
        """
        subscription = self._get_subscription_plan()
        enterprise_slug = subscription.customer_agreement.enterprise_customer_slug
        licenses = subscription.licenses.filter(status__in=[
            constants.ACTIVATED, constants.ASSIGNED, constants.REVOKED
        ], ).values('status', 'user_email', 'activation_date',
                    'last_remind_date', 'activation_key')
        for lic in licenses:
            # We want to expose the full activation link rather than just the activation key
            lic['activation_link'] = get_license_activation_link(
                enterprise_slug, lic['activation_key'])
            lic.pop('activation_key', None)
        csv_data = CSVRenderer().render(list(licenses))
        return Response(csv_data,
                        status=status.HTTP_200_OK,
                        content_type='text/csv')
    def test_get_returns_csv_info(self):
        user_email = "*****@*****.**"
        experiment1 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="a")
        experiment2 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="b")

        response = self.client.get(
            reverse("experiments-api-csv"),
            **{settings.OPENIDC_EMAIL_HEADER: user_email},
        )

        self.assertEqual(response.status_code, 200)

        csv_data = response.content
        expected_csv_data = CSVRenderer().render(
            ExperimentCSVSerializer([experiment1, experiment2],
                                    many=True).data,
            renderer_context={"header": ExperimentCSVSerializer.Meta.fields},
        )
        self.assertEqual(csv_data, expected_csv_data)
    def test_view_filters_by_project(self):
        user_email = "*****@*****.**"
        project = ProjectFactory.create()
        experiment1 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="a", projects=[project])
        experiment2 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="b", projects=[project])
        ExperimentFactory.create_with_variants()

        url = reverse("experiments-api-csv")
        response = self.client.get(
            f"{url}?projects={project.id}",
            **{settings.OPENIDC_EMAIL_HEADER: user_email})

        self.assertEqual(response.status_code, 200)

        csv_data = response.content
        expected_csv_data = CSVRenderer().render(
            ExperimentCSVSerializer([experiment1, experiment2],
                                    many=True).data,
            renderer_context={"header": ExperimentCSVSerializer.Meta.fields},
        )
        self.assertEqual(csv_data, expected_csv_data)
    def test_view_filters_by_subscriber(self):
        user = UserFactory(email="*****@*****.**")
        experiment1 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="a")
        experiment1.subscribers.add(user)
        experiment2 = ExperimentFactory.create_with_status(
            Experiment.STATUS_DRAFT, name="b")
        experiment2.subscribers.add(user)
        ExperimentFactory.create_with_variants()

        url = reverse("experiments-api-csv")
        response = self.client.get(
            f"{url}?subscribed=on",
            **{settings.OPENIDC_EMAIL_HEADER: user.email})

        self.assertEqual(response.status_code, 200)

        csv_data = response.content
        expected_csv_data = CSVRenderer().render(
            ExperimentCSVSerializer([experiment1, experiment2],
                                    many=True).data,
            renderer_context={"header": ExperimentCSVSerializer.Meta.fields},
        )
        self.assertEqual(csv_data, expected_csv_data)
class CourseIndexCSV(CourseAPIMixin, LoginRequiredMixin,
                     DatetimeCSVResponseMixin, TemplateView):

    csv_filename_suffix = 'course-list'
    # Note: we are not using the DRF "renderer_classes" field here because this is a Django view, not a DRF view.
    # We will call the render function on the renderer directly instead.
    renderer = CSVRenderer()
    exclude_fields = {
        '': ('created', ),
        'enrollment_modes': {
            'audit': ('count_change_7_days', ),
            'credit': ('count_change_7_days', ),
            'honor': ('count_change_7_days', ),
            'professional': ('count_change_7_days', ),
            'verified': ('count_change_7_days', ),
        }
    }

    def get_data(self):
        courses = permissions.get_user_course_permissions(self.request.user)
        if not courses:
            # The user is probably not a course administrator and should not be using this application.
            raise PermissionDenied

        presenter = CourseSummariesPresenter()
        summaries, _ = presenter.get_course_summaries(courses)
        if not summaries:
            # Instead of returning a useless blank CSV, return a 404 error
            raise Http404

        # Exclude specified fields from each summary entry and render them to a CSV
        summaries = [
            remove_keys(summary, self.exclude_fields) for summary in summaries
        ]
        summaries_csv = self.renderer.render(summaries)
        return summaries_csv
Exemple #10
0
    def __init__(self, data, **kwargs):
        content = CSVRenderer().render(data)

        kwargs['content_type'] = 'text/csv'
        super(CSVResponse, self).__init__(content, **kwargs)