def get(self, **kwargs): """GET method handler for dashboard reports.""" 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_id = kwargs.get('user_id') user_type = kwargs.get('user_type') response_data = {"user_id": user_id, "user_type": user_type} if user_type == UserTypes.REVIEWER.value: registraton_info = RegDetails.get_dashboard_report( user_id, user_type) de_registraton_info = DeRegDetails.get_dashboard_report( user_id, user_type) response_data['registration'] = registraton_info response_data['de-registration'] = de_registraton_info elif user_type in [ UserTypes.IMPORTER.value, UserTypes.INDIVIDUAL.value ]: registraton_info = RegDetails.get_dashboard_report( user_id, user_type) response_data['registration'] = registraton_info elif user_type == UserTypes.EXPORTER.value: de_registraton_info = DeRegDetails.get_dashboard_report( user_id, user_type) response_data['de-registration'] = de_registraton_info response = Response(json.dumps(response_data), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) return response
def get(reg_id=None): """GET method handler, returns registration requests.""" try: schema = RegistrationDetailsSchema() if reg_id: if not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response( app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) response = RegDetails.get_by_id(reg_id) response = schema.dump(response).data else: response = RegDetails.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()
def post(reg_id): """POST method handler, restarts processing of a request.""" if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: reg_details = RegDetails.get_by_id(reg_id) # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1) failed_status_id = Status.get_status_id('Failed') processing_failed = reg_details.processing_status in [failed_status_id] report_failed = reg_details.report_status in [failed_status_id] # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed processing_required = processing_failed or report_failed if processing_required: # pragma: no cover reg_device = RegDevice.get_device_by_registration_id(reg_details.id) Device.create(reg_details, reg_device.id) 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'))
def put(): """PUT method handler, updates a device.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: args = request.form.to_dict() schema = DeviceDetailsUpdateSchema() reg_details = RegDetails.get_by_id(reg_id) reg_device = RegDevice.get_device_by_registration_id(reg_id) if reg_details: args.update({ 'reg_details_id': reg_details.id, 'status': reg_details.status }) else: args.update({'reg_details_id': ''}) 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")) # day_passed = (datetime.now() - reg_details.updated_at) > timedelta(1) processing_failed = reg_details.processing_status in [ Status.get_status_id('Failed'), Status.get_status_id('New Request') ] report_failed = reg_details.report_status == Status.get_status_id( 'Failed') # report_timeout = reg_details.report_status == Status.get_status_id('Processing') and day_passed processing_required = processing_failed or report_failed reg_device = RegDevice.update(reg_device, args) response = schema.dump(reg_device, many=False).data response['reg_details_id'] = reg_details.id if processing_required: Device.create(reg_details, reg_device.id) 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': _('request device addition failed')} return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def index_reg_details(self, conn): """Method to index the Registration Details.""" try: RegDetails.create_index(conn) return "Registration Details indexed successfully" except SQLAlchemyError as e: raise e
def post(): """POST method handler, creates registration requests.""" tracking_id = uuid.uuid4() try: args = RegDetails.curate_args(request) schema = RegistrationDetailsSchema() file = request.files.get('file') 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 file: file_name = file.filename.split("/")[-1] response = Utilities.store_file(file, tracking_id) if response: return Response( json.dumps(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) response = Utilities.process_reg_file(file_name, tracking_id, args) if isinstance(response, list): response = RegDetails.create(args, tracking_id) else: return Response( app.json_encoder.encode(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: Utilities.create_directory(tracking_id) response = RegDetails.create(args, tracking_id) db.session.commit() response = schema.dump(response, many=False).data 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) Utilities.remove_directory(tracking_id) 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()
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 registration documents.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: schema = RegistrationDocumentsSchema() time = datetime.now().strftime('%Y%m%d%H%M%S') args = request.form.to_dict() args = Utilities.update_args_with_file(request.files, args) reg_details = RegDetails.get_by_id(reg_id) if reg_details: args.update({ 'reg_details_id': reg_details.id, 'status': reg_details.status }) else: args.update({'reg_details_id': ''}) 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 = reg_details.tracking_id created = RegDocuments.bulk_create(request.files, reg_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")) reg_details.update_status('Pending Review') message = schema.dump(created, many=True).data db.session.commit() 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()
def get(reg_id): """GET method handler, returns request documents.""" if not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: schema = RegistrationDocumentsSchema() documents = RegDocuments.get_by_reg_id(reg_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: # 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()
def create_dummy_devices(data, request_type, request, db=None, file_path=None, file_content=None): """Helper method to create a dummy request with devices and assign it to a dummy reviewer. based on request_type. """ if request_type == 'Registration': data.update({'reg_details_id': request.id}) device = RegDevice.create(data) device.technologies = DeviceTechnology.create(device.id, data.get('technologies')) Device.create(RegDetails.get_by_id(request.id), device.id) else: # De-registration # creating sample file if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) with open(file_path, 'w') as f: for content in file_content: f.write(content) f.write('\n') data = DeRegDevice.curate_args(data, request) imei_tac_map = Utilities.extract_imeis_tac_map(data, request) created = DeRegDevice.bulk_create(data, request) device_id_tac_map = Utilities.get_id_tac_map(created) for device in device_id_tac_map: device_imeis = imei_tac_map.get(device.get('tac')) dereg_imei_list = DeRegImei.get_deregimei_list( device.get('id'), device_imeis) db.session.execute(DeRegImei.__table__.insert(), dereg_imei_list) return request
def post(): """POST method handler, creates a new device.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(json.dumps(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: args = request.form.to_dict() schema = DeviceDetailsSchema() reg_details = RegDetails.get_by_id(reg_id) if reg_details: args.update({'reg_details_id': reg_details.id}) else: args.update({'reg_details_id': ''}) validation_errors = schema.validate(args) if validation_errors: response = Response( json.dumps(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) return response reg_device = RegDevice.create(args) reg_device.technologies = DeviceTechnology.create( reg_device.id, args.get('technologies')) response = schema.dump(reg_device, many=False).data response['reg_details_id'] = reg_details.id reg_details.update_status('Awaiting Documents') db.session.commit() Device.create(reg_details, reg_device.id) 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 device addition failed'} return Response(json.dumps(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
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"))
def check_reg_id(self, data): """Validates request id.""" reg_details_id = data['reg_details_id'] reg_details = RegDetails.get_by_id(reg_details_id) if 'user_id' in data and data['user_id'] != reg_details.user_id: raise ValidationError('Permission denied for this request', field_names=['user_id']) if not reg_details: raise ValidationError('The request id provided is invalid', field_names=['reg_id'])
def test_review_sections_registration(flask_app, db): # pylint: disable=unused-argument """Verify that the api returns correct information of sections.""" # registration request data = { 'device_count': 2, 'imei_per_device': 1, 'imeis': "[['86834403015010', '86834403015011']]", 'm_location': 'local', 'user_name': 'section rev user 1', 'user_id': 'section-rev-user-1' } reviewer_id = 'section-rev-1' reviewer_name = 'section rev' section = 'device_quota' status = 6 comment = 'this is a test comment' request = create_assigned_dummy_request(data, 'Registration', reviewer_id, reviewer_name) assert request request_id = request.id RegDetails.add_comment(section, comment, reviewer_id, reviewer_name, status, request_id) rv = flask_app.get( '{0}?request_id={1}&request_type=registration_request'.format( SECTIONS_API, request_id)) assert rv.status_code == 200 data = json.loads(rv.data.decode('utf-8'))['sections'] for sect in data: if sect.get('comments'): assert sect.get('section_type') == section assert sect.get('section_status') == status sect_comment = sect.get('comments')[0] assert sect_comment.get('user_name') == reviewer_name assert sect_comment.get('user_id') == reviewer_id assert sect_comment.get('comment') == comment assert sect_comment.get('datetime') else: assert sect.get('section_type') in [ 'device_description', 'imei_classification', 'imei_registration', 'approval_documents' ] assert sect.get('comments') is None assert sect.get('section_status') is None
def get(reg_id): """GET method handler, return registration sections.""" if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: reg_details = RegDetails.get_by_id(reg_id) reg_schema = RegistrationDetailsSchema() doc_schema = RegistrationDocumentsSchema() device_schema = DeviceDetailsSchema() reg_device = RegDevice.get_device_by_registration_id(reg_id) reg_documents = RegDocuments.get_by_reg_id(reg_id) registration_data = reg_schema.dump(reg_details).data device_data = device_schema.dump( reg_device).data if reg_device else {} document_data = doc_schema.dump(reg_documents, many=True).data response = { 'reg_details': registration_data, 'reg_device': device_data, 'reg_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': [ _('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_document_label(self, data): """Returns appropriate document label.""" reg_details = RegDetails.get_by_id(data.reg_details_id) upload_dir_path = GLOBAL_CONF['upload_directory'] document = Documents.get_document_by_id(data.document_id) data.label = document.label data.required = Documents.required data.link = '{server_dir}/{local_dir}/{file_name}'.format( server_dir=upload_dir_path, local_dir=reg_details.tracking_id, file_name=data.filename)
def check_reg_id(self, data): """Validates request id.""" reg_details_id = data['reg_details_id'] reg_details = RegDetails.get_by_id(reg_details_id) if 'user_id' in data and reg_details.user_id != data['user_id']: raise ValidationError('Permission denied for this request', field_names=['user_id']) if not reg_details: raise ValidationError('The request id provided is invalid', field_names=['reg_id']) else: status = Status.get_status_type(reg_details.status) if status != 'New Request': raise ValidationError(_('This step can only be performed for New Request'), field_names=['status'])
def check_permissions(self, data): """Validates user permissions.""" reg_details = RegDetails.get_by_id(data['reg_id']) request_user = reg_details.user_id if 'user_id' in data and data['user_id'] != request_user: raise ValidationError('Permission denied for this request.', field_names=['user_id']) if 'imeis' in data: if not reg_details.imeis or reg_details.imeis == 'None': raise ValidationError('Input type cannot be updated, Require file', field_names=['file'] ) elif 'file' in data: if not reg_details.file or reg_details.file == 'None': raise ValidationError('Input type cannot be updated, Require Imeis', field_names=['imeis'] )
def get(reg_id): """GET method handler, returns device details.""" if not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(json.dumps(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) schema = DeviceDetailsSchema() try: reg_device = RegDevice.get_device_by_registration_id(reg_id) response = schema.dump(reg_device).data if reg_device else {} return Response(json.dumps(response), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) except Exception as e: app.logger.exception(e) error = { 'message': ['Failed to retrieve response, please try later'] } return Response(json.dumps(error), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def put(): """PUT method handler, updates documents.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) try: schema = RegistrationDocumentsUpdateSchema() time = datetime.now().strftime('%Y%m%d%H%M%S') args = request.form.to_dict() args = Utilities.update_args_with_file(request.files, args) reg_details = RegDetails.get_by_id(reg_id) if reg_details: args.update({ 'reg_details_id': reg_details.id, 'status': reg_details.status }) else: args.update({'reg_details_id': ''}) 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 = reg_details.tracking_id updated = RegDocuments.bulk_update(request.files, reg_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 reg_details.status == Status.get_status_id( 'Information Requested'): reg_details.update_status('In Review') message = 'The request {id} has been updated.'.format( id=reg_details.id) notification = Notification(reg_details.reviewer_id, reg_details.id, 'registration_request', reg_details.status, message) notification.add() else: reg_details.update_status('Pending Review') response = schema.dump(updated, many=True).data message = schema.dump(updated, many=True).data log = EsLog.new_doc_serialize( message, request_type="Update Registration Documents", regdetails=reg_details, reg_status="Pending Review", method='Put', request='Registration') db.session.commit() 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': _('request document updation failed, please try again later.') } return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def put(self): """PUT method handler, updates existing registration request. """ try: # get the posted data args = RegDetails.curate_args(request) # create Marshmallow object schema = UssdDeleteSchema() # validate posted data validation_errors = schema.validate(args) if validation_errors: for key, value in validation_errors.items(): messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': key + ':' + value[0] } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: dereg_id = args['device_id'] if dereg_id and dereg_id.isdigit() and RegDetails.exists(dereg_id): # if record matches with the passed MSISDN device_info = UssdModel.get_by_id(dereg_id) if device_info.msisdn != args['msisdn']: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "Your MSISDN does not match with the record." } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_("Your MSISDN does not match with the record.")]} return Response(app.json_encoder.encode(data), status=CODES.get("RECORD_MISMATCH"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: dreg_details = RegDetails.get_by_id(dereg_id) else: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': 'Delete Request not found.' } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Printing the jasmin send response") print(jasmin_send_response) if jasmin_send_response: print("Jasmin API response: " + str(jasmin_send_response.status_code)) else: print("Jasmin API response: " + str(jasmin_send_response)) return Response(app.json_encoder.encode({'message': [_('Delete Request not found.')]}), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) if dreg_details: normalized_imeis = Ussd_helper.get_normalized_imeis(dreg_details.imeis) Utilities.de_register_imeis(normalized_imeis) 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: for key, value in validation_errors.items(): messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': key + ':' + value[0] } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) 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): # let the user know about the deregistration messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': str(response['message']) } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) print(str(response['message'])) return Response(app.json_encoder.encode(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: log = EsLog.new_request_serialize(dreg_details, 'USSD De-Registration', method='Put') EsLog.insert_log(log) response = schema.dump(response, many=False).data # let the user know about the deregistration messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': str("Device with ID: " + str(dereg_id) + " has been DeRegistered") } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) response['response'] = messages['content'] return Response(json.dumps(response), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) response = DeRegDetails.update(args, dreg_details, file=False) response = schema.dump(response, many=False).data # let the user know about the deregistration messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': str(response['message']) } jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) self.messages_list.append(messages.copy()) print("Jasmin API response: " + str(jasmin_send_response.status_code)) 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()
def auto_approve(task_id, reg_details, flatten_imeis, app): from app.api.v1.resources.reviewer import SubmitReview from app.api.v1.models.devicequota import DeviceQuota as DeviceQuotaModel from app.api.v1.models.eslog import EsLog from app.api.v1.models.status import Status import json sr = SubmitReview() try: result = Utilities.check_request_status(task_id) duplicate_imeis = RegDetails.get_duplicate_imeis(reg_details) res = RegDetails.get_imeis_count(reg_details.user_id) sections_comment = "Auto" section_status = 6 auto_approved_sections = [ 'device_quota', 'device_description', 'imei_classification', 'imei_registration' ] if result: flatten_imeis = Utilities.bulk_normalize(flatten_imeis) if result['non_compliant'] != 0 or result['stolen'] != 0 or result['compliant_active'] != 0 \ or result['provisional_non_compliant'] != 0 or result['provisional_compliant'] != 0: sections_comment = sections_comment + ' Rejected, Device/Devices found in Non-Compliant States' status = 'Rejected' section_status = 7 message = 'Your request {id} has been rejected'.format( id=reg_details.id) else: sections_comment = sections_comment + ' Approved' status = 'Approved' message = 'Your request {id} has been Approved'.format( id=reg_details.id) if duplicate_imeis: res.update({ 'duplicated': len(RegDetails.get_duplicate_imeis(reg_details)) }) Utilities.generate_imeis_file(duplicate_imeis, reg_details.tracking_id, 'duplicated_imeis') reg_details.duplicate_imeis_file = '{upload_dir}/{tracking_id}/{file}'.format( upload_dir=app.config['DRS_UPLOADS'], tracking_id=reg_details.tracking_id, file='duplicated_imeis.txt') sections_comment = "Auto" status = 'Rejected' sections_comment = sections_comment + ' Rejected, Duplicate IMEIS Found, Please check duplicate file' section_status = 7 message = 'Your request {id} has been rejected because duplicate imeis found!'.format( id=reg_details.id) if status == 'Approved': # checkout device quota imeis = RegDetails.get_normalized_imeis(reg_details) user_quota = DeviceQuotaModel.get(reg_details.user_id) current_quota = user_quota.reg_quota user_quota.reg_quota = current_quota - len(imeis) DeviceQuotaModel.commit_quota_changes(user_quota) sr._SubmitReview__update_to_approved_imeis(flatten_imeis) else: sr._SubmitReview__change_rejected_imeis_status( flatten_imeis) for section in auto_approved_sections: RegDetails.add_comment(section, sections_comment, reg_details.user_id, 'Auto Reviewed', section_status, reg_details.id) reg_details.summary = json.dumps({'summary': result}) reg_details.report = result.get('compliant_report_name') reg_details.update_report_status('Processed') reg_details.report_allowed = True reg_details.update_status(status) sr._SubmitReview__generate_notification( user_id=reg_details.user_id, request_id=reg_details.id, request_type='registration', request_status=section_status, message=message) reg_details.save() db.session.commit() # create log log = EsLog.auto_review(reg_details, "Registration Request", 'Post', status) EsLog.insert_log(log) except Exception as e: # pragma: no cover db.session.rollback() reg_details.update_processing_status('Failed') reg_details.update_status('Failed') message = 'Your request {id} has failed please re-initiate device request'.format( id=reg_details.id) sr._SubmitReview__generate_notification( user_id=reg_details.user_id, request_id=reg_details.id, request_type='registration', request_status=7, message=message) db.session.commit() app.logger.exception(e) # create log log = EsLog.auto_review(reg_details, "Registration Request", 'Post', Status.get_status_type(reg_details.status)) EsLog.insert_log(log) return True
def create_registration(data, tracking_id): """ Helper method to create a registration request""" return RegDetails.create(data, tracking_id)
def post(self): """POST method handler, track USSD based Registered devices.""" try: # get the posted data args = RegDetails.curate_args(request) # create Marshmallow object schema = UssdTrackingSchema() # validate posted data validation_errors = schema.validate(args) if validation_errors: for key, value in validation_errors.items(): messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': key + ':' + value[0] } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: # check device record dev_result = UssdModel.exists(args['device_id']) if dev_result == True: # if record matches with the passed MSISDN device_info = UssdModel.get_by_id(args['device_id']) if device_info.msisdn != args['msisdn']: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "Your MSISDN does not match with the record." } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_("Your MSISDN does not match with the record.")]} return Response(app.json_encoder.encode(data), status=CODES.get("RECORD_MISMATCH"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: msg_string = Ussd_helper.set_record_info(device_info, True) print(msg_string) messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': str(msg_string) } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) print("printing the jasmin send response code in track") print(jasmin_send_response.status_code) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_(msg_string)]} return Response(app.json_encoder.encode(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': 'No record found with that Device ID' } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_('No record found with that ID')]} return Response(app.json_encoder.encode(data), status=CODES.get("RECORD_NOT_FOUND"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) except Exception as e: # pragma: no cover db.session.rollback() app.logger.exception(e) data = { 'message': [_('Something went wrong. Please try again later.')] } return Response(app.json_encoder.encode(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def post(self): """POST method handler, Get all user's registered devices and statuses""" try: # get the posted data args = RegDetails.curate_args(request) # create Marshmallow object schema = UssdCountSchema() # validate posted data validation_errors = schema.validate(args) if validation_errors: for key, value in validation_errors.items(): messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': key + ':' + value[0] } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: total_count = RegDetails.get_count(msisdn=args['msisdn']) if total_count['count_with_msisdn'] > 0: msisdn_all_counts = RegDetails.get_all_counts(msisdn=args['msisdn']) msisdn_all_counts.update({"count_with_msisdn": total_count['count_with_msisdn']}) message = Ussd_helper.set_count_message(msisdn_all_counts) messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': str(message) } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_(str(message))]} else: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "No records found with that number." } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) print("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': [_("No records found with that number.")]} return Response(app.json_encoder.encode(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) except Exception as e: 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()
def post(self): """POST method handler, creates registration requests.""" tracking_id = uuid.uuid4() try: # get the posted data args = RegDetails.curate_args(request) # create Marshmallow object schema = RegistrationDetailsSchema() # validate CNIC number if not args['cnic'] or not args['cnic'].isdigit(): messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "CNIC number is mandatory and must be digits only." } self.messages_list.append(messages.copy()) print("Printing the jasmin message") print(messages) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) return Response(app.json_encoder.encode({"message": "CNIC number is mandatory and must be digits only."}), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) # Multi SIM Validation response = ast.literal_eval(args['imeis']) message = DeviceDetailsRoutes.multi_sim_validate(response) if message is True: pass elif message is False: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "Something went wrong, please try again later" } self.messages_list.append(messages.copy()) print("Printing the jasmin message") print(self.messages_list) jasmin_send_response = Jasmin.send_batch(self.messages_list, network=args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': "Something went wrong while checking multi sim check please try again later!"} return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) else: # create messages for user if any changed_msgs = [] for key1, val1 in message.items(): for key2, val2 in val1.items(): val2 = Ussd_helper.check_forbidden_string(val2) changed_dict = {key2:val2} changed_msgs.append(changed_dict) messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': val2 } self.messages_list.append(messages.copy()) # message = changed_msgs print("Printing the jasmin message") print(self.messages_list) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': changed_msgs} return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) # validate posted data validation_errors = schema.validate(args) if validation_errors: for key, value in validation_errors.items(): str_val = '' if key == "imeis": if isinstance(value[0], dict): for k_i, v_i in value[0].items(): str_val = str_val + str(v_i[0] + ' ' + args['imeis'][0][k_i])+". " else: print(validation_errors) str_val = str_val + str(value[0]) else: if key == "msisdn": if isinstance(value, list): str_val = str_val + str(value[0]) messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': key +':' + str(value[0]) if not dict else str(str_val) } self.messages_list.append(messages.copy()) print("Printing the jasmin messages") print(self.messages_list) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) return Response(app.json_encoder.encode(validation_errors), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: # call KeyCloak for admin Token admin_token_data = Key_cloak.get_admin_token() # call KeyCloak with token for user_data = Key_cloak.check_user_get_data(args, admin_token_data) # if user is created, a password is set for it arguments = Ussd_helper.set_args_dict_for_regdetails(args, user_data) reg_response = RegDetails.create(arguments, tracking_id) db.session.commit() # get GSMA information and make device call. we get the device id if reg_response.id: schema2 = rdSchema() response = schema2.dump(reg_response, many=False).data # Todo: add logging here or below after condition check log = EsLog.new_request_serialize(response, 'USSD Registration', method='Post', imeis=arguments['imeis']) EsLog.insert_log(log) # get the tac from an imei in the dict and search for GSMA record tac = arguments['imeis'][0][0][0:8] gsma_url = str(app.config['CORE_BASE_URL']+app.config['API_VERSION'])+str('/tac/'+tac) # get GSMA record against each TAC and match them with IMEIs count given in list gsma_response = requests.get(gsma_url).json() if gsma_response["gsma"] is None: # GSMA record not found for the said TAC messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "No record found for TAC:" + str(tac) } self.messages_list.append(messages.copy()) print("Printing the jasmin messages") print(self.messages_list) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) data = {'message': messages['content']} return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) else: # set device data args device_arguments = Ussd_helper.set_args_dict_for_devicedetails(reg_response, arguments, gsma_response) reg_details = RegDetails.get_by_id(reg_response.id) if reg_details: device_arguments.update({'reg_details_id': reg_details.id}) else: device_arguments.update({'reg_details_id': ''}) device_arguments.update({'device_type': 'Smartphone'}) reg_device = RegDevice.create(device_arguments) reg_device.technologies = DeviceTechnology.create( reg_device.id, device_arguments.get('technologies'), True) device_status = 'Pending Review' reg_details.update_status(device_status) DeviceQuotaModel.get_or_create(reg_response.user_id, 'ussd') Utilities.create_directory(tracking_id) db.session.commit() device_schema = DeviceDetailsSchema() device_serialize_data = device_schema.dump(reg_device, many=False).data log = EsLog.new_device_serialize(device_serialize_data, request_type="USSD Device Registration", regdetails=reg_details, reg_status=device_status, method='Post') EsLog.insert_log(log) Device.create(reg_details, reg_device.id, ussd=True) # delay the process 5 seconds to complete the process time.sleep(5) # get the device details reg_details = RegDetails.get_by_id(reg_response.id) status_msg = Ussd_helper.set_message_for_user_info(reg_details.status) # if reg_details.status == 6: status_msg = status_msg + " Your device tracking id is: " + str(reg_details.id) # send user a details about device messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': status_msg } self.messages_list.append(messages.copy()) # send username and password to the new user if 'password' in user_data: messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "New user credentials are, username: "******" and password: "******"Jasmin API response: " + str(jasmin_send_response.status_code)) app.logger.info("Printing the message array in CLI mode.") app.logger.info(self.messages_list) response = { 'message': 'Device registration has been processed successfully.' } if status_msg: response['status_response'] = status_msg return Response(json.dumps(response), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: # error in regdetails messages = { 'from': 'DRS-USSD', 'to': args['msisdn'], 'content': "Registration request failed, check upload path or database connection" } self.messages_list.append(messages.copy()) jasmin_send_response = Jasmin.send_batch(self.messages_list, network = args['network']) app.logger.info("Jasmin API response: " + str(jasmin_send_response.status_code)) # response = schema.dump(response, many=False).data data = {'message': [_('Device undergone the process. Please hold your breath.')]} return Response(app.json_encoder.encode(data), status=CODES.get('UNPROCESSABLE_ENTITY'), 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()
def put(): """PUT method handler, updates registration requests.""" reg_id = request.form.to_dict().get('reg_id', None) if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id): return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) args = RegDetails.curate_args(request) schema = RegistrationDetailsUpdateSchema() file = request.files.get('file') reg_details = RegDetails.get_by_id(reg_id) try: tracking_id = reg_details.tracking_id if reg_details: args.update({ 'status': reg_details.status, 'reg_id': reg_details.id, 'processing_status': reg_details.processing_status, 'report_status': reg_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 = RegDetails.close(reg_details) if isinstance(response, dict): return Response( app.json_encoder.encode(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: response = schema.dump(response, many=False).data return Response( json.dumps(response), status=CODES.get("OK"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) if file: Utilities.remove_file(reg_details.file, tracking_id) response = Utilities.store_file(file, tracking_id) if response: return Response( json.dumps(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) response = Utilities.process_reg_file(file.filename, tracking_id, args) if isinstance(response, list): response = RegDetails.update(args, reg_details, True) else: return Response( app.json_encoder.encode(response), status=CODES.get("UNPROCESSABLE_ENTITY"), mimetype=MIME_TYPES.get("APPLICATION_JSON")) else: response = RegDetails.update(args, reg_details, False) db.session.commit() response = schema.dump(response, many=False).data 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 update 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()