示例#1
0
文件: views.py 项目: tadgh/KW
 def create(self, request, *args, **kwargs):
     """
     Create a new report, or if an identical report already exists, update the existing one.
     """
     try:
         reading_id = request.data["reading"]
         existing_report = Report.objects.get(
             reading__id=reading_id, created_by=request.user
         )
         logger.info(
             "User {} is updating their report on reading {}".format(
                 request.user.username, request.data["reading"]
             )
         )
         serializer = ReportSerializer(
             existing_report, data=request.data, partial=True
         )
         serializer.is_valid(raise_exception=True)
         serializer.save()
         return Response(serializer.data)
     except Report.DoesNotExist:
         logger.info(
             "User {} is creating report on reading {}".format(
                 request.user.username, request.data["reading"]
             )
         )
         serializer = ReportSerializer(data=request.data)
         serializer.is_valid(raise_exception=True)
         serializer.save(created_by=self.request.user)
         return Response(serializer.data)
示例#2
0
def report_list(request):

    if request.method == 'GET':
        report = Report.objects.order_by('-missing_date')
        serializer = ReportSerializer(report, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ReportSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
示例#3
0
def get_report(request):
    pk = request.data.get('post_id')
    token = Token.objects.get(key=request.auth)
    post_in_process = PostInProcess.objects.get(id=pk)
    report = Report.objects.get(post_in_process=post_in_process)
    report_ser = ReportSerializer(report)
    return Response(report_ser.data)
示例#4
0
def report_name_filter(request, name):

    report = Report.objects.filter(name_subject=name)

    if request.method == 'GET':
        serializer = ReportSerializer(report, many=True)
        return JSONResponse(serializer.data)
示例#5
0
def user_report_detail(request, pk):

    user = User.objects.get(pk=pk)
    report = Report.objects.filter(user_fk=user.pk)

    if request.method == 'GET':
        serializer = ReportSerializer(report, many=True)
        return JSONResponse(serializer.data)
示例#6
0
 def test_carry_over_last_month(self, contract_start_mid_january):
     """
     Testing that the carryover for of the last month, is half the actual debit_worktime if the contract
     started in the middle of the last month.
     :param contract_start_mid_january:
     :return:
     """
     rep = Report.objects.get(
         contract=contract_start_mid_january,
         month_year=contract_start_mid_january.end_date.replace(day=1),
     )
     assert ReportSerializer(rep).data["carry_over_last_month"] == "-10:19"
示例#7
0
 def test_carry_over_next_month(self, contract_start_mid_january):
     """
     Testing that the carryover for the next month is only half the debit worktime for a full
     month.
     :param contract_start_mid_january:
     :return:
     """
     rep = Report.objects.get(
         contract=contract_start_mid_january,
         month_year=contract_start_mid_january.start_date.replace(day=1),
     )
     assert ReportSerializer(rep).data["carry_over_next_month"] == "-10:19"
示例#8
0
 async def save_message_and_ack(self, consumer_record):
     """Save and ack the uploaded kafka message."""
     self.prefix = 'SAVING MESSAGE'
     if consumer_record.topic == QPC_TOPIC:
         try:
             missing_fields = []
             self.upload_message = self.unpack_consumer_record(consumer_record)
             # rh_account is being deprecated so we use it as a backup if
             # account is not there
             rh_account = self.upload_message.get('rh_account')
             request_id = self.upload_message.get('request_id')
             url = self.upload_message.get('url')
             self.account_number = self.upload_message.get('account', rh_account)
             if not self.account_number:
                 missing_fields.append('account')
             if not request_id:
                 missing_fields.append('request_id')
             if not url:
                 missing_fields.append('url')
             if missing_fields:
                 raise QPCKafkaMsgException(
                     format_message(
                         self.prefix,
                         'Message missing required field(s): %s.' % ', '.join(missing_fields)))
             self.check_if_url_expired(url, request_id)
             try:
                 uploaded_report = {
                     'upload_srv_kafka_msg': json.dumps(self.upload_message),
                     'account': self.account_number,
                     'request_id': request_id,
                     'state': Report.NEW,
                     'state_info': json.dumps([Report.NEW]),
                     'last_update_time': datetime.now(pytz.utc),
                     'arrival_time': datetime.now(pytz.utc),
                     'retry_count': 0
                 }
                 report_serializer = ReportSerializer(data=uploaded_report)
                 report_serializer.is_valid(raise_exception=True)
                 report_serializer.save()
                 MSG_UPLOADS.labels(account_number=self.account_number).inc()
                 LOG.info(format_message(
                     self.prefix,
                     'Upload service message saved with request_id: %s. Ready for processing.'
                     % request_id))
                 await self.consumer.commit()
             except Exception as error:  # pylint: disable=broad-except
                 DB_ERRORS.inc()
                 LOG.error(format_message(
                     self.prefix,
                     'The following error occurred while trying to save and '
                     'commit the message: %s' % error))
                 print_error_loop_event()
         except QPCKafkaMsgException as message_error:
             LOG.error(format_message(
                 self.prefix, 'Error processing records.  Message: %s, Error: %s' %
                 (consumer_record, message_error)))
             await self.consumer.commit()
     else:
         LOG.debug(format_message(
             self.prefix, 'Message not on %s topic: %s' % (QPC_TOPIC, consumer_record)))
示例#9
0
def nessus_file(request):

    if request.method == 'POST':
        username = request.user.username
        print(f'username = {username}')

        nes_file = request.FILES['file']
        print(f'nes_file ======{nes_file}')
        if not nes_file:
            return Response({'error': 'No file posted, please try again'},
                            status=HTTP_400_BAD_REQUEST)

        fs = FileSystemStorage()
        filename = fs.save(nes_file.name, nes_file)
        uploaded_file_url = fs.url(filename)       
        abs_path_to_nessus_file = os.path.join(settings.BASE_DIR,'media', filename)
        parse_nes = ParseNessus(abs_path_to_nessus_file)
        report_name, check_count, sev_level_dict, report_list = parse_nes.parse_nessus()
        
        report = Report(username=request.user.username,report_name=report_name,
                scan_date=datetime.datetime.now(),plugin_check_count=check_count,
                severity_level_warning_count=sev_level_dict['1'],
                severity_level_minor_count=sev_level_dict['2'],
                severity_level_major_count=sev_level_dict['3'],
                severity_level_critical_count=sev_level_dict['4']
                )
        report.save()

        for item_report in report_list:
            item =ItemsFound(severity=get_severity(item_report.get('severity')),
                    plugin_id=item_report.get('plugin_id'),
                    plugin_name=item_report.get('plugin_name'),
                    plugin_family=item_report.get('plugin_family'),
                    description=item_report.get('description'),
                    action=item_report.get('action'),
                    report=report)
            item.save()

        report_obj = Report.objects.get(pk=report.id)

        if report_obj is not None:
            serializer = ReportSerializer(report_obj)
            return JsonResponse(serializer.data, safe=True,
            status=HTTP_200_OK)
        else:
            return Response({'error': 'No report found'},
                        status=HTTP_404_NOT_FOUND)

    if request.method == 'GET':
         return Response({
            'bla': 'bla',
        },status=HTTP_200_OK)
示例#10
0
    def test_net_worktime(self, contract_start_mid_january):
        """
        Testing that the net_worktime for the next month after the start in the middle of the month is
        1+(16/31) times the debit_worktime (assuming no shifts in both months).
        :param contract_start_mid_january:
        :return:
        """
        rep = Report.objects.get(
            contract=contract_start_mid_january,
            month_year=contract_start_mid_january.end_date.replace(day=1),
        )

        assert ReportSerializer(rep).data["net_worktime"] == "00:00"
示例#11
0
def report_detail(request, pk):

    try:
        report = Report.objects.get(pk=pk)
    except Report.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ReportSerializer(report)  
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ReportSerializer(report, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        report.delete()
        return HttpResponse(status=204)
示例#12
0
    def construct_json_object(self, user):
        user_data = UserSerializer(user).data
        contract_data = ContractSerializer(Contract.objects.filter(user=user),
                                           many=True).data
        shift_data = ShiftSerializer(Shift.objects.filter(user=user),
                                     many=True).data
        report_data = ReportSerializer(Report.objects.filter(user=user),
                                       many=True).data

        return {
            "user_data": user_data,
            "contracts_data": contract_data,
            "shifts_data": shift_data,
            "reports_data": report_data,
        }
示例#13
0
def report_list(request):

    if request.method == 'GET':
        report = Report.objects.order_by('-missing_date')
        serializer = ReportSerializer(report, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ReportSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
示例#14
0
def report_all_filter(request, year, month, day, status, gender, state,
                      lowerAge, higherAge):

    reports = Report.objects.all()
    if (year != "null" and month != "null" and day != "null"):
        reports = missingdate_filter(reports, year, month, day)
    if (status != "null"):
        reports = reports.filter(status=status)
    if (gender != "null"):
        reports = reports.filter(gender=gender)
    if (state != "null"):
        reports = reports.filter(state=state)
    if (lowerAge != "null"):
        reports = lowerage_filter(reports, lowerAge)
    if (higherAge != "null"):
        reports = highage_filter(reports, higherAge)
    if request.method == 'GET':
        serializer = ReportSerializer(reports, many=True)
        return JSONResponse(serializer.data)
示例#15
0
def report_detail(request, pk):

    try:
        report = Report.objects.get(pk=pk)
    except Report.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ReportSerializer(report)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ReportSerializer(report, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        report.delete()
        return HttpResponse(status=204)
示例#16
0
 def create(self, request, *args, **kwargs):
     """
     Create a new report, or if an identical report already exists, update the existing one.
     """
     try:
         reading_id = request.data["reading"]
         existing_report = Report.objects.get(reading__id=reading_id,
                                              created_by=request.user)
         logger.info(
             f"User {request.user.username} is updating their report on reading {request.data['reading']}"
         )
         serializer = ReportSerializer(existing_report,
                                       data=request.data,
                                       partial=True)
         serializer.is_valid(raise_exception=True)
         serializer.save()
         return Response(serializer.data)
     except Report.DoesNotExist:
         logger.info(
             f"User {request.user.username} is creating report on reading {request.data['reading']}"
         )
         serializer = ReportSerializer(data=request.data)
         serializer.is_valid(raise_exception=True)
         serializer.save(created_by=self.request.user)
         return Response(serializer.data)
示例#17
0
                description='Le encanta la polla al mojo de ajo')
report.save()

imageReport = ImageReport(report_fk=report,
                          image='api/media/default/missing_pic.png')
imageReport.save()

comment = Comment(report_fk=report,
                  comment_date='2014-04-02',
                  content='Me encontre un calcetin mojado')
comment.save()

userSerializer = UserSerializer(user)
userSerializer.data

rs = ReportSerializer(report)
rs.data

irs = ImageReportSerializer(imageReport)
irs.data

cs = CommentSerializer(comment)
cs.data

content = JSONRenderer().render(userSerializer.data)
content

contentReport = JSONRenderer().render(rs.data)
contentReport

contentImageReport = JSONRenderer().render(irs.data)