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()
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 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()
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 get(reg_id): """GET method handler, returns device details.""" 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")) 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: # 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 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()
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( json.dumps(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: 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 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 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()
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 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 post(): """POST method handler, Create/Submit a new De-Registration details. """ tracking_id = uuid.uuid4() try: schema = DeRegDetailsSchema() args = DeRegDetails.curate_args(request) 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")) 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_de_reg_file( file.filename.split("/")[-1], tracking_id, args) 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.create(args, tracking_id) db.session.commit() response = schema.dump(response, many=False).data 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")) except Exception as e: # pragma: no cover db.session.rollback() 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 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()
def get(self): argv = request.args.to_dict() scenario = self.case_search(int(argv['case'])) argv['scenario'] = str(scenario) argv['msisdn'] = self.validate_msisdn(argv['msisdn']) if scenario == "registration": resp = self.registration(argv) elif scenario == "track_record": resp = self.tracking(argv) elif scenario == "delete_record": resp = self.delete_record(argv) elif scenario == "count_records": resp = self.count_records(argv) else: print("API not found") return False """GET method handler.""" if resp: content = (resp.content).decode() else: content = {"Invalid data passed"} print(content) return Response(content, status=CODES.get('OK'), mimetype=MIME_TYPES.get('APPLICATION_JSON'))
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 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(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'))
def not_found_handler(error): """Custom error handler for 404.""" data = {'message': MESSAGES.get('RESOURCE_NOT_FOUND')} response = Response(json.dumps(data), status=CODES.get('NOT_FOUND'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response
def not_found(error=None): """handle app's 404 error.""" resp = Response(json.dumps({ "message": MESSAGES.get('NOT_FOUND'), "status_code": RESPONSES.get('NOT_FOUND') }), status=RESPONSES.get('NOT_FOUND'), mimetype=MIME_TYPES.get('JSON')) return resp
def bad_request(error=None): """handle app's 400 error""" resp = Response(json.dumps({ "message": MESSAGES.get('BAD_REQUEST'), "status_code": RESPONSES.get('BAD_REQUEST') }), status=RESPONSES.get('BAD_REQUEST'), mimetype=MIME_TYPES.get('JSON')) return resp
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(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(json.dumps(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: app.logger.exception(e) data = { 'message': [ 'Registration request failed, check upload path or database connection' ] } return Response(json.dumps(data), status=CODES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('APPLICATION_JSON')) finally: db.session.close()
def internal_error(error=None): """handle app's 500 error""" resp = Response(json.dumps({ "message": MESSAGES.get('INTERNAL_SERVER_ERROR'), "status_code": RESPONSES.get('INTERNAL_SERVER_ERROR') }), status=RESPONSES.get('INTERNAL_SERVER_ERROR'), mimetype=MIME_TYPES.get('JSON')) return resp
def method_not_allowed(error=None): """handle app's 405 error""" resp = Response(json.dumps({ "message": MESSAGES.get('METHOD_NOT_ALLOWED'), "status_code": RESPONSES.get('METHOD_NOT_ALLOWED') }), status=RESPONSES.get('METHOD_NOT_ALLOWED'), mimetype=MIME_TYPES.get('JSON')) return resp
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(json.dumps(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: 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 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 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.""" args = request.get_json() data = { "start": args.get('start', 1), "previous": "", "next": "", "requests": [], "count": 0, "limit": args.get('limit', 2), "message": "" } if args.get("search_specs") is not None: request_data = args.get("search_specs") if 'group' not in request_data or 'request_type' \ not in request_data \ or 'user_id' not in request_data: data['message'] = 'Search Specs attributes missing!' response = Response( json.dumps(data), status=CODES.get("NOT_FOUND"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response try: if request_data['group'] == 'importer': if request_data['request_type'] == 1: return SearchRegistraion.get_result( request, request_data['group']) else: data['message'] = "Request type not found!" response = Response( json.dumps(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response elif request_data['group'] == 'exporter': if request_data['request_type'] == 2: return SearchDeregistration.get_result( request, request_data['group']) else: data['message'] = "Request type not found!" response = Response( json.dumps(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response elif request_data['group'] == 'individual': if request_data['request_type'] == 1: return SearchRegistraion.get_result( request, request_data['group']) else: data['message'] = "Request type not found!" response = Response( json.dumps(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response elif request_data['group'] == 'reviewer': if request_data['request_type'] == 1: return SearchRegistraion.get_result( request, request_data['group']) elif request_data['request_type'] == 2: return SearchDeregistration.get_result( request, request_data['group']) else: data['message'] = "Request type not found!" response = Response( json.dumps(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response else: data['message'].append("No Data Found") response = Response( json.dumps(data), status=CODES.get("OK"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response except Exception as ex: app.logger.exception(ex) data['message'] = "No data found" response = Response(json.dumps(data), status=CODES.get("NOT_FOUND"), mimetype=MIME_TYPES.get('APPLICATION_JSON')) return response
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()
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()