def get(dereg_id):
        """GET method handler, returns documents."""
        no_error = dereg_id.isdigit() and DeRegDetails.exists(dereg_id)
        if not no_error:
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            documents = DeRegDocuments.get_by_reg_id(dereg_id)
            documents = schema.dump(documents, many=True).data
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            data = {
                "message": [_("Error retrieving results. Please try later.")]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
Beispiel #2
0
    def get(dereg_id=None):
        """GET method handler,
        returns a deregistration request based on request id.
        """
        schema = DeRegDetailsSchema()
        try:
            if dereg_id:
                if dereg_id.isdigit() and DeRegDetails.exists(dereg_id):
                    response = DeRegDetails.get_by_id(dereg_id)
                    response = schema.dump(response).data
                else:
                    response = app.json_encoder.encode(DEREG_NOT_FOUND_MSG)

            else:
                response = DeRegDetails.get_all()
                response = schema.dump(response, many=True).data
            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            error = {
                'message':
                [_('Failed to retrieve response, please try later')]
            }
            return Response(app.json_encoder.encode(error),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Beispiel #3
0
    def get(dereg_id):
        """GET method handler, returns documents."""
        no_error = dereg_id.isdigit() and DeRegDetails.exists(dereg_id)
        if not no_error:
            return Response(json.dumps(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            documents = DeRegDocuments.get_by_reg_id(dereg_id)
            documents = schema.dump(documents, many=True).data
            '''if doc_id:
                if not doc_id.isdigit():
                    documents = DOC_NOT_FOUND_MSG
                else:
                    documents = list(filter(lambda doc: int(doc['id']) == int(doc_id), documents))
                    documents = documents[0] if documents else DOC_NOT_FOUND_MSG
            '''
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:
            app.logger.exception(e)
            data = {"message": "Error retrieving results. Please try later."}

            return Response(json.dumps(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
Beispiel #4
0
    def put():
        """PUT method handler, updates documents."""
        dereg_id = request.form.to_dict().get('dereg_id', None)
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(json.dumps(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsUpdateSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            dereg_details = DeRegDetails.get_by_id(dereg_id)
            if dereg_details:
                args.update({
                    'dereg_details': dereg_details.id,
                    'status': dereg_details.status
                })
            else:
                args.update({'dereg_details': ''})
            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(json.dumps(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            tracking_id = dereg_details.tracking_id
            updated = DeRegDocuments.bulk_update(request.files, dereg_details,
                                                 time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(json.dumps(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if dereg_details.status == Status.get_status_id(
                    'Information Requested'):
                dereg_details.update_status('In Review')
            else:
                dereg_details.update_status('Pending Review')
            response = schema.dump(updated, many=True).data
            db.session.commit()
            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                'request document updation failed, please try again later.'
            }

            return Response(json.dumps(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Beispiel #5
0
    def get(self, **kwargs):
        """GET method handler, return registration report."""
        for key, value in kwargs.items():
            if value is None:
                res = {'error': ['{0} is required'.format(key)]}
                return Response(json.dumps(ErrorResponse().dump(res).data),
                                status=422, mimetype='application/json')
        user_type = kwargs.get('user_type')
        request_type = kwargs.get('request_type')
        request_id = kwargs.get('request_id')
        user_id = kwargs.get('user_id')
        if request_type == 'registration_request':
            if not request_id.isdigit() or not RegDetails.exists(request_id):
                return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = RegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            report_allowed = True if user_type == 'reviewer' or \
                                     (req.user_id == user_id and req.report_allowed) else False
            if report_allowed:
                if user_type == 'reviewer':
                    report_name = req.report
                else:
                    report_name = 'user_report-{}'.format(req.report)
                report = os.path.join(app.config['DRS_UPLOADS'], req.tracking_id, report_name)
                return send_file(report)
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        else:
            if not request_id.isdigit() or not DeRegDetails.exists(request_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = DeRegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            report_allowed = True if user_type == 'reviewer' or \
                                     (req.user_id == user_id and req.report_allowed) else False
            if report_allowed:
                if user_type == 'reviewer':
                    report_name = req.report
                else:
                    report_name = 'user_report-{}'.format(req.report)
                report = os.path.join(app.config['DRS_UPLOADS'], req.tracking_id, report_name)
                return send_file(report)
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
 def post():
     """POST method handler, creates new devices for request."""
     dereg_id = request.form.to_dict().get('dereg_id', None)
     if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
             dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                         status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema_request = DeRegRequestSchema()
         device_schema = DeRegDeviceSchema()
         dereg = DeRegDetails.get_by_id(dereg_id)
         args = request.form.to_dict()
         args = DeRegDevice.curate_args(args, dereg)
         validation_errors = schema_request.validate(args)
         if validation_errors:
             return Response(app.json_encoder.encode(validation_errors),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
         imeis_list = Utilities.extract_imeis(imei_tac_map)
         not_registered_imeis = Utilities.get_not_registered_imeis(
             imeis_list)
         if not_registered_imeis:
             error = {'not_registered_imeis': not_registered_imeis}
             return Response(json.dumps(error),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         else:
             old_devices = list(map(lambda x: x.id, dereg.devices))
             created = DeRegDevice.bulk_create(args, dereg)
             device_id_tac_map = Utilities.get_id_tac_map(created)
             devices = device_schema.dump(created, many=True)
             dereg.update_status('Awaiting Documents')
             db.session.commit()
             DeRegDevice.bulk_insert_imeis(device_id_tac_map, imei_tac_map,
                                           old_devices, imeis_list, dereg)
             response = {'devices': devices.data, 'dreg_id': dereg.id}
             return Response(json.dumps(response),
                             status=CODES.get("OK"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message':
             [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error),
                         status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()
Beispiel #7
0
    def post(dereg_id):
        """POST method handler, restarts processing of a request."""
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            dereg = DeRegDetails.get_by_id(dereg_id)
            # day_passed = (datetime.now() - dereg.updated_at) > timedelta(1)
            failed_status_id = Status.get_status_id('Failed')
            processing_failed = dereg.processing_status in [failed_status_id]
            report_failed = dereg.report_status in [failed_status_id]
            # report_timeout = dereg.report_status == Status.get_status_id('Processing') and day_passed
            processing_required = processing_failed or report_failed
            if processing_required:  # pragma: no cover
                dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg.id)
                dereg_devices_data = DeRegDeviceSchema().dump(dereg_devices,
                                                              many=True).data
                dereg_devices_ids = list(
                    map(lambda x: x['id'], dereg_devices_data))
                args = {'devices': dereg_devices_data}
                imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
                imeis_list = Utilities.extract_imeis(imei_tac_map)
                created = DeRegDevice.bulk_create(args, dereg)
                device_id_tac_map = Utilities.get_id_tac_map(created)
                DeRegDevice.bulk_insert_imeis(device_id_tac_map, imei_tac_map,
                                              dereg_devices_ids, imeis_list,
                                              dereg)
                response = {'message': 'Request performed successfully.'}
            else:
                response = app.json_encoder.encode(
                    {'message': _('This request cannot be processed')})

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {'message': _('failed to restart process')}

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
Beispiel #8
0
    def post(self, **kwargs):
        """Post method handler, set report permissions."""
        for key, value in kwargs.items():
            if value is None:
                res = {'error': ['{0} is required'.format(key)]}
                return Response(json.dumps(ErrorResponse().dump(res).data),
                                status=422, mimetype='application/json')
        user_type = kwargs.get('user_type')
        request_type = kwargs.get('request_type')
        request_id = kwargs.get('request_id')
        user_id = kwargs.get('user_id')
        if request_type == 'registration_request':
            if not request_id.isdigit() or not RegDetails.exists(request_id):
                return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = RegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if user_type == 'reviewer' and req.reviewer_id == user_id:
                response = RegDetails.toggle_permission(req)
                response = {'message': 'The permission to view report is changed', 'value': response}
                return Response(json.dumps(response), status=CODES.get("OK"),
                                 mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        else:
            if not request_id.isdigit() or not DeRegDetails.exists(request_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            req = DeRegDetails.get_by_id(request_id)
            if not req.report:
                return Response(app.json_encoder.encode(REPORT_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if user_type == 'reviewer' and req.reviewer_id == user_id:
                response = DeRegDetails.toggle_permission(req)
                response = {'message': 'The permission to view report is changed', 'value': response}
                return Response(json.dumps(response), status=CODES.get("OK"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                return Response(app.json_encoder.encode(REPORT_NOT_ALLOWED_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
Beispiel #9
0
    def get(dereg_id):
        """GET method handler, to return all section of a request."""
        try:
            if not dereg_id.isdigit() or not DeRegDetails.exists(dereg_id):
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            dereg_details = DeRegDetails.get_by_id(dereg_id)
            dereg_schema = DeRegDetailsSchema()
            doc_schema = DeRegDocumentsSchema()
            device_schema = DeRegDeviceSchema()

            dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg_id)
            dereg_documents = DeRegDocuments.get_by_reg_id(dereg_id)

            deregistration_data = dereg_schema.dump(dereg_details).data
            device_data = device_schema.dump(dereg_devices, many=True).data
            document_data = doc_schema.dump(dereg_documents, many=True).data

            response = {
                'dereg_details': deregistration_data,
                'dereg_device': device_data,
                'dereg_docs': document_data
            }

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            app.logger.exception(e)

            data = {
                'message': [
                    _('De-Registration request failed, check upload path or database connection'
                      )
                ]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
 def get(dereg_id):
     """GET method handler, returns device of a request."""
     if not dereg_id.isdigit() or not DeRegDetails.exists(dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema = DeRegDeviceSchema()
         dereg_devices = DeRegDevice.get_devices_by_dereg_id(dereg_id)
         response = schema.dump(dereg_devices, many=True).data
         return Response(json.dumps(response), status=CODES.get("OK"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message': [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error), status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()
 def put():
     """PUT method handler, updates devices of the request."""
     dereg_id = request.form.to_dict().get('dereg_id', None)
     if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
             dereg_id):
         return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                         status=CODES.get("UNPROCESSABLE_ENTITY"),
                         mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     try:
         schema_request = DeRegRequestUpdateSchema()
         device_schema = DeRegDeviceSchema()
         dereg = DeRegDetails.get_by_id(dereg_id)
         args = request.form.to_dict()
         args = DeRegDevice.curate_args(args, dereg)
         validation_errors = schema_request.validate(args)
         if validation_errors:
             return Response(app.json_encoder.encode(validation_errors),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         imei_tac_map = Utilities.extract_imeis_tac_map(args, dereg)
         imeis_list = Utilities.extract_imeis(imei_tac_map)
         not_registered_imeis = Utilities.get_not_registered_imeis(
             imeis_list)
         if not_registered_imeis:
             error = {'not_registered_imeis': not_registered_imeis}
             return Response(json.dumps(error),
                             status=CODES.get("UNPROCESSABLE_ENTITY"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
         else:
             # day_passed = (datetime.now() - dereg.updated_at) > timedelta(1)
             processing_failed = dereg.processing_status in [
                 Status.get_status_id('Failed'),
                 Status.get_status_id('New Request')
             ]
             report_failed = dereg.report_status == Status.get_status_id(
                 'Failed')
             # report_timeout = dereg.report_status == Status.get_status_id('Processing') and day_passed
             processing_required = processing_failed or report_failed
             if processing_required:
                 old_devices = list(map(lambda x: x.id, dereg.devices))
                 created = DeRegDevice.bulk_create(args, dereg)
                 device_id_tac_map = Utilities.get_id_tac_map(created)
                 devices = device_schema.dump(created, many=True)
                 db.session.commit()
                 DeRegDevice.bulk_insert_imeis(device_id_tac_map,
                                               imei_tac_map, old_devices,
                                               imeis_list, dereg)
                 response = {'devices': devices.data, 'dreg_id': dereg.id}
             else:
                 response = {'devices': [], 'dreg_id': dereg.id}
             return Response(json.dumps(response),
                             status=CODES.get("OK"),
                             mimetype=MIME_TYPES.get("APPLICATION_JSON"))
     except Exception as e:  # pragma: no cover
         app.logger.exception(e)
         error = {
             'message':
             [_('Failed to retrieve response, please try later')]
         }
         return Response(app.json_encoder.encode(error),
                         status=CODES.get('INTERNAL_SERVER_ERROR'),
                         mimetype=MIME_TYPES.get('APPLICATION_JSON'))
     finally:
         db.session.close()
Beispiel #12
0
    def put():
        """PUT method handler,
        updates existing de registration request.
        """
        dereg_id = request.form.to_dict().get('dereg_id', None)
        try:
            schema = DeRegDetailsUpdateSchema()
            if dereg_id and dereg_id.isdigit() and DeRegDetails.exists(
                    dereg_id):
                dreg_details = DeRegDetails.get_by_id(dereg_id)
            else:
                return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            args = DeRegDetails.curate_args(request)
            file = request.files.get('file')
            tracking_id = dreg_details.tracking_id
            if dreg_details:
                args.update({
                    'status': dreg_details.status,
                    'processing_status': dreg_details.processing_status,
                    'report_status': dreg_details.report_status
                })
            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if args.get('close_request', None) == 'True':
                response = DeRegDetails.close(dreg_details)
                if isinstance(response, dict):
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                else:
                    log = EsLog.new_request_serialize(response,
                                                      "Close De-Registration",
                                                      method="Put")
                    EsLog.insert_log(log)
                    response = schema.dump(response, many=False).data
                    return Response(
                        json.dumps(response),
                        status=CODES.get("OK"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if file:
                response = Utilities.store_file(file, tracking_id)
                imeis_list = Utilities.extract_imeis(response)
                if response:
                    return Response(
                        json.dumps(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                filename = file.filename
            elif dreg_details.status == Status.get_status_id('New Request'):
                filename = dreg_details.file
                args.update({'device_count': dreg_details.device_count})
            else:
                filename = None

            if filename:
                response = Utilities.process_de_reg_file(
                    filename, tracking_id, args)
                imeis_list = Utilities.extract_imeis(response)
                errored = 'device_count' in response or 'invalid_imeis' in response or \
                          'duplicate_imeis' in response or 'invalid_format' in response
                if not errored:
                    gsma_response = Utilities.get_device_details_by_tac(
                        response)
                    response = DeRegDetails.update(args,
                                                   dreg_details,
                                                   file=True)
                    response = schema.dump(response, many=False).data
                    log = EsLog.new_request_serialize(response,
                                                      "DeRegistration",
                                                      imeis=imeis_list,
                                                      dereg=True,
                                                      method="Put")
                    EsLog.insert_log(log)
                    response = {'request': response, 'devices': gsma_response}
                    return Response(
                        json.dumps(response),
                        status=CODES.get("OK"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
                else:
                    return Response(
                        app.json_encoder.encode(response),
                        status=CODES.get("UNPROCESSABLE_ENTITY"),
                        mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            else:
                response = DeRegDetails.update(args, dreg_details, file=False)
                response = schema.dump(response, many=False).data
                log = EsLog.new_request_serialize(response,
                                                  "DeRegistration",
                                                  dereg=True,
                                                  method="Put")
                EsLog.insert_log(log)
                return Response(json.dumps(response),
                                status=CODES.get("OK"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message': [
                    _('Registration request failed, check upload path or database connection'
                      )
                ]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Beispiel #13
0
    def post():
        """POST method handler, creates documents."""
        dereg_id = request.form.to_dict().get('dereg_id', None)
        if not dereg_id or not dereg_id.isdigit() or not DeRegDetails.exists(
                dereg_id):
            return Response(app.json_encoder.encode(DEREG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = DeRegDocumentsSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            dereg_details = DeRegDetails.get_by_id(dereg_id)
            if dereg_details:
                args.update({
                    'dereg_details': dereg_details.id,
                    'status': dereg_details.status
                })
            else:
                args.update({'dereg_details': ''})

            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            tracking_id = dereg_details.tracking_id
            created = DeRegDocuments.bulk_create(request.files, dereg_details,
                                                 time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(app.json_encoder.encode(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            dereg_details.update_status('Pending Review')
            message = schema.dump(created, many=True).data
            log = EsLog.new_doc_serialize(message,
                                          request_type="De-Registration",
                                          regdetails=dereg_details,
                                          reg_status="Pending Review",
                                          method='Post',
                                          request='De-Registration')
            db.session.commit()
            EsLog.insert_log(log)
            return Response(json.dumps(message),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                _('request document addition failed, check for valid formats.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()