Esempio n. 1
0
 def delete(self, request, app, model, id):
     parser_classes = [parsers.JSONParser]
     if id:
         model = apps.get_model(app, model)
         try:
             obj = model.objects.get(id=id)
             if not obj:
                 raise ObjectDoesNotExist
             with transaction.atomic(), reversion.create_revision():
                 obj = model.objects.get(id=id)
                 obj.save()
                 reversion.set_user(request.user)
                 reversion.set_comment(request.method)
                 reversion.set_date_created(
                     date_created=datetime.datetime.now())
             GenericSzl = getGenericSerializer(model)
             serializer = GenericSzl(obj)
             org = serializer.data
             obj.delete()
             updated = None
             audit_log_id(org, updated, request, app, model, id)
             return Response(
                 {
                     "Deleted successfully": "Deleted Successfully!!!",
                     "data": serializer.data
                 },
                 status=status.HTTP_204_NO_CONTENT)
         except ObjectDoesNotExist:
             REQ_LOGS.error("Object Doesnt Exist for DELETE " + " " +
                            str(id) + " " + " by " + str(request.user))
             return Response("The Given Object Doesnt Exist!")
Esempio n. 2
0
    def put(self, request, app, model, id):
        try:

            d = request.data
            # if not d:
            #     raise json.JSONDecodeError("InValid JSON provided",doc=,pos=0)
        except json.JSONDecodeError:
            REQ_LOGS.error("In valid Json provided for POST")
            # return Response("Invalid JSON for the POST")

        model = apps.get_model(app, model)
        obj = model.objects.get(id=id)
        validators_d = {}
        validators_d['validators'] = [CharOnly(), UpperCaseOnly()]
        serializer_org = getGenericSerializer(model)
        serial_org_data = serializer_org(obj)
        serializer = GenericSerializerField(model, validators_d)
        serial_data = serializer(obj, data=d, partial=True)
        if serial_data.is_valid():
            with transaction.atomic(), reversion.create_revision():
                reversion.set_user(request.user)
                reversion.set_comment(request.method)
                reversion.set_date_created(
                    date_created=datetime.datetime.now())
                serial_data.save()
                audit_log_id(serial_org_data.data, serial_data.data, request,
                             app, model, id)

            return Response(serial_data.data)
        return Response(serial_data.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 3
0
    def post(self, request, app, model):
        model = apps.get_model(app, model)
        org = json.loads(request.body.decode('utf8'))
        try:
            d = request.data
            print("###################3 bahar", d)
            if not d:
                print("#########################3333", d)
                REQ_LOGS.error("In valid Json provided for POST")
                raise json.JSONDecodeError("InValid JSON provided",
                                           doc=request.data,
                                           pos=0)
        except json.JSONDecodeError:
            REQ_LOGS.error("In valid Json provided for POST")
            return Response("Invalid JSON for the POST")

        validators_d = {}
        # validators_d['validators'] = [CharOnly(), UpperCaseOnly()]
        serialize = getGenericSerializer(model)
        serial_data = serialize(data=d)
        if serial_data.is_valid():
            with transaction.atomic(), reversion.create_revision():
                reversion.set_user(request.user)
                reversion.set_comment(request.method)
                reversion.set_date_created(
                    date_created=datetime.datetime.now())
                serial_data.save()
            audit_log_list(org, request, app, model)

            return Response(serial_data.data, status=status.HTTP_201_CREATED)
        return Response(serial_data.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 4
0
    def handle(self, *args, **options):
        with open(options['file']) as f:
            reader = csv.reader(f)
            # Skip first row, we expect it to be a header.
            next(reader, None)  # skip the headers
            for row in reader:
                try:
                    # Where possible we're fetching the objects attaChed
                    # to our attributes to verify they already exist.

                    partner_id = row[0]
                    partner = Partner.objects.get(pk=partner_id)

                    # Inconsistent date format on the input files
                    try:
                        datetime_created = datetime.strptime(
                            row[1], '%m/%d/%Y %H:%M')
                    except:
                        datetime_created = datetime.strptime(
                            row[1], '%m/%d/%Y %H:%M:%S')
                    date_created = datetime_created.date()

                    wp_username = row[2]
                    editor = Editor.objects.get(wp_username=wp_username)
                    editor_id = editor.pk

                    specific_stream_id = row[4]
                    stream = Stream.objects.get(pk=specific_stream_id)
                    import_note = 'Imported on ' + str(date.today()) + '.'

                    try:
                        application = Application.objects.get(
                            partner_id=partner_id,
                            date_created=date_created,
                            date_closed=date_created,
                            editor_id=editor_id,
                            specific_stream_id=specific_stream_id,
                            status=4)
                    except Application.DoesNotExist:
                        application = Application(
                            partner_id=partner_id,
                            date_created=date_created,
                            date_closed=date_created,
                            editor_id=editor_id,
                            specific_stream_id=specific_stream_id,
                            comments=import_note,
                            rationale=import_note,
                            imported=True,
                            status=4)
                        with reversion.create_revision():
                            reversion.set_date_created(datetime_created)
                            application.save()
                            logger.info("Application created.")
                except:
                    logger.exception(
                        "Unable to create {wp_username}'s application to {partner_id}."
                        .format(wp_username=row[2], partner_id=row[0]))
                    pass
Esempio n. 5
0
    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        with revisions.create_revision(manage_manually=True):
            self.perform_update(serializer)
            revisions.set_user(request.user)
            revisions.set_comment('Created by API')
            revisions.set_date_created(serializer.instance)

        return response.Response(data=serializers.OrderReadSerializer(
            serializer.instance).data,
                                 status=status.HTTP_200_OK)
Esempio n. 6
0
    def delete(self, request, app, model):
        if request.data:
            dict_mapp = request.data
            model = apps.get_model(app, model)
            objs = model.objects.filter(**dict_mapp)
            with transaction.atomic(), reversion.create_revision():
                [objs[i].save() for i in range(len(objs))]
                reversion.set_user(request.user)
                reversion.set_comment(request.method)
                reversion.set_date_created(
                    date_created=datetime.datetime.now())
            GenericSzl = getGenericSerializer(model)
            serializer = GenericSzl(objs, many=True)
            org = serializer.data
            objs.delete()
            audit_log_list(org, request, app, model)
            return Response({'Received data': request.data})

        else:
            return Response({"return none instead": "return none instead"})
Esempio n. 7
0
    def handle(self, *args, **options):
        with open(options["file"]) as f:
            reader = csv.reader(f)
            # Skip first row, we expect it to be a header.
            next(reader, None)  # skip the headers
            for row in reader:
                try:
                    # If the collections field is empty, make it a list containing an empty string.
                    if row[4] in (None, ""):
                        specific_stream_ids = [""]
                    # Otherwise try to split it on comma
                    else:
                        specific_stream_ids = row[4].split(",")

                    # If the title field is empty, make it a list containing an empty string.
                    if row[5] in (None, ""):
                        specific_titles = [""]
                    # Otherwise try to split it on semicolon
                    else:
                        specific_titles = row[5].split(";")

                    for specific_stream_id in specific_stream_ids:

                        for specific_title in specific_titles:

                            # Where possible we're fetching the objects attached
                            # to our attributes to verify they already exist.

                            partner_id = row[0]
                            partner = Partner.even_not_available.get(pk=partner_id)

                            # Inconsistent date format on the input files
                            # If the date field is empty, set it to the beginning of (Unix) time.
                            if row[1] in (None, ""):
                                datetime_created = datetime.strptime(
                                    "01/01/1970 00:00:00", "%d/%m/%Y %H:%M:%S"
                                )

                            # If we have a date field
                            else:
                                # Try fetching the most precise timestamp
                                try:
                                    datetime_created = datetime.strptime(
                                        row[1], "%d/%m/%Y %H:%M:%S"
                                    )

                                except ValueError:
                                    # If that doesn't work, try getting a less precise timestamp
                                    try:
                                        datetime_created = datetime.strptime(
                                            row[1], "%d/%m/%Y %H:%M"
                                        )

                                    except ValueError:
                                        # If that doesn't work, try getting a date
                                        try:
                                            datetime_created = datetime.strptime(
                                                row[1], "%d/%m/%Y"
                                            )
                                        except:
                                            pass

                            date_created = datetime_created

                            wp_username = self.normalize_wp_username(row[2])
                            editor = Editor.objects.get(wp_username=wp_username)
                            editor_id = editor.pk

                            try:
                                stream = Stream.objects.get(pk=specific_stream_id)
                            except:
                                specific_stream_id = None
                                stream = None

                            import_note = "Imported on " + str(date.today()) + "."

                            try:
                                application = Application.objects.get(
                                    partner_id=partner_id,
                                    date_created=date_created,
                                    date_closed=date_created,
                                    editor_id=editor_id,
                                    specific_stream_id=specific_stream_id,
                                    specific_title=specific_title,
                                    imported=True,
                                    status=Application.SENT,
                                )
                            except Application.DoesNotExist:
                                application = Application(
                                    partner_id=partner_id,
                                    date_created=date_created,
                                    date_closed=date_created,
                                    editor_id=editor_id,
                                    specific_stream_id=specific_stream_id,
                                    specific_title=specific_title,
                                    comments=import_note,
                                    rationale=import_note,
                                    imported=True,
                                    status=Application.SENT,
                                    sent_by=twl_team,
                                )
                                with reversion.create_revision():
                                    reversion.set_date_created(datetime_created)
                                    application.save()
                                    logger.info("Application created.")
                except:
                    logger.exception(
                        "Unable to create {wp_username}'s application to {partner_id}.".format(
                            wp_username=self.normalize_wp_username(row[2]),
                            partner_id=row[0],
                        )
                    )
                    pass