Example #1
0
    def post(self):
        File.parser.add_argument('registration_type',
                                 type=str,
                                 required=True,
                                 help="This field cannot be blank.")
        data = File.parser.parse_args()
        logger.info("OAuth token is: {}".format(data['oauth_token']))

        # Generate UUID to identify registration request
        uuid_str = str(uuid.uuid4())
        config.UUID = uuid_str
        # Valid registration_type list
        registration_list = ['sl', 'slr']
        if data['registration_type'] not in registration_list:
            logger.error("Registration type is not valid!")
            return {'message': "Registration type is not valid!"}, 400

        if 'file' not in request.files:
            logger.error("No File in the request!")
            return {"message": "No File in the request!"}, 400
        file = request.files['file']

        if file.filename == '':
            logger.error("No File selected!")
            return {'message': "No File selected!"}, 400

        if not File.allowed_file(file.filename):
            logger.error("File type not allowed! Only CSV files are allowed!")
            return {
                'message': "File type not allowed! Only CSV files are allowed!"
            }, 400

        # Validate each field/column of CSV file
        validate_flag, errors, df = File.validate_csv(
            file, data['registration_type'])
        if not validate_flag:
            logger.error("CSV file validation failed!: '{}'".format(errors))
            return {
                'message': "CSV file validation failed!: '{}'".format(errors)
            }, 400

        # Create dictionary for upload_info_store
        upload_info_dict = {
            'uuid':
            uuid_str,
            'userid':
            config.USER_ID,
            'filename':
            file.filename,
            'type':
            data['registration_type'],
            'timestamp':
            datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d %H:%M:%S'),
            'status':
            "csv_file_uploaded"
        }

        # Also set REGISTRATION_NAME as filename in config file
        config.REGISTRATION_NAME = file.filename

        # Create dictionaries for device_store, validation_store, device_status_store
        converted_json, converted_validation_json, converted_status_json = File.csv_to_json(
            df)

        # Enter data into the database store device_store
        if TokensModel.find_by_uuid(uuid_str, "device_store"):
            logger.info("Request with UUID: '{}' already exists.".format(uuid))
            return {
                'message':
                "Request with UUID: '{}' already exists.".format(uuid)
            }, 400

        try:
            TokensModel.insert(uuid_str, converted_json, "device_store")
        except Exception as e:
            print(e)
            logger.error("Data insert operation device_store failed!",
                         exc_info=True)
            return {
                "message": "Data insert operation device_store failed!"
            }, 500

        # Enter data into the database store account_validation
        if TokensModel.find_by_uuid(uuid_str, "validation_store"):
            logger.info("Request with UUID: '{}' already exists.".format(uuid))
            return {
                'message':
                "Request with UUID: '{}' already exists.".format(uuid)
            }, 400

        try:
            TokensModel.insert(uuid_str, converted_validation_json,
                               "validation_store")
        except Exception as e:
            print(e)
            logger.error("Data insert operation validation_store failed!",
                         exc_info=True)
            return {
                "message": "Data insert operation validation_store failed!"
            }, 500

        # Enter data into the database store device_status_store
        if TokensModel.find_by_uuid(uuid_str, "device_status_store"):
            logger.info("Request with UUID: '{}' already exists.".format(uuid))
            return {
                'message':
                "Request with UUID: '{}' already exists.".format(uuid)
            }, 400

        try:
            TokensModel.insert(uuid_str, converted_status_json,
                               "device_status_store")
        except Exception as e:
            print(e)
            logger.error("Data insert operation device_status_store failed!",
                         exc_info=True)
            return {
                "message": "Data insert operation device_status_store failed!"
            }, 500

        try:
            if data['registration_type'] == 'slr':
                TokensModel.insert(uuid_str, converted_json,
                                   "slr_request_code_tbl")
        except Exception as e:
            print(e)
            logger.error("Data insert operation slr_request_code_tbl failed!",
                         exc_info=True)
            return {
                "message": "Data insert operation slr_request_code_tbl failed!"
            }, 500

        # Enter data into the database store upload_info_store
        if TokensModel.find_by_uuid(uuid_str, "upload_info_store"):
            logger.info("Request with UUID: '{}' already exists.".format(uuid))
            return {
                'message':
                "Request with UUID: '{}' already exists.".format(uuid)
            }, 400

        try:
            TokensModel.insert(uuid_str, [upload_info_dict],
                               "upload_info_store")
        except Exception as e:
            print(e)
            logger.error("Data insert operation failed!", exc_info=True)
            return {"message": "Data insert operation failed!"}, 500

        config.NO_OF_DEVICES = len(converted_json)
        config.NO_OF_PAGES = ceil(len(converted_json) / 10)
        new_request = {
            'uuid': uuid_str,
            'totalpages': config.NO_OF_PAGES,
            'message': 'File is uploaded!'
        }

        # For debugging
        logger.info(new_request)
        if TokensModel.find_by_uuid(uuid_str, "validation_store"):
            logger.info("Printed validation_store")
        if TokensModel.find_by_uuid(uuid_str, "device_status_store"):
            logger.info("Printed device_status_store")
        if TokensModel.find_by_uuid(uuid_str, "upload_info_store"):
            logger.info("Printed upload_info_store")
        logger.info(
            "The request has been fulfilled and has resulted in one or more new resources being created"
        )
        return new_request, 201
Example #2
0
    def update_req_codes_slr(cls, validated_json):
        # s = slr("", "", "")
        # Start extracting required fields from json
        uuid = validated_json['registration-uuid']
        registration_name = validated_json['registration-name']

        # First check if devices with this UUID already exists
        try:
            rows_slr = TokensModel.find_by_uuid(uuid, "slr_request_code_tbl")
            rows = TokensModel.find_by_uuid(uuid, "device_store")
        except Exception as e:
            print(e)
            return {"message": "Data search operation failed!", 'code': 500}

        if rows_slr:
            # Changed to 200 from 400 on UI Dev team request
            print("==>> UUID already exists in slr_request_code_tbl...")
            return {
                "message":
                "Registration request with this UUID already exists!",
                'code': 200
            }

        if rows:
            # Changed to 200 from 400 on UI Dev team request
            print("==>> UUID already exists in device_store...")
            return {
                "message":
                "Registration request with this UUID already exists!",
                'code': 200
            }

        # Creat update_slr_reqcode_table_dict
        insert_slr_reqcode_table_list = []
        insert_device_store_table_list = []
        insert_upload_info_store_table_list = []

        for device in validated_json['devices']:
            # Traverse through validated_json dictionary and create a list of flat key-value pair dict
            each_device_reqcode_dict = {}
            each_device_store_dict = {}
            each_device_upload_info_store_dict = {}
            # Initialize lic_count_str & lic_ent_tag_str
            lic_count_str, lic_ent_tag_str = "", ""
            # Prepare fields for slr_request_code_tbl
            each_device_reqcode_dict['uuid'] = uuid
            each_device_reqcode_dict['ipaddr'] = device['device-uuid']
            each_device_reqcode_dict['step1'] = device['step1']
            each_device_reqcode_dict['step2'] = "NS"
            each_device_reqcode_dict['step3'] = "NS"
            each_device_reqcode_dict['authz_req_code'] = device['request-code']
            each_device_reqcode_dict['authz_response_code'] = ""
            each_device_reqcode_dict['license'] = ""
            for license in device['licenses']:
                print("\n\n")
                print("**** Printing license sub-json...")
                print(license)
                lic_count_str += license['license-count'] + " "
                lic_ent_tag_str += license['license-entitlement-tag'] + " "
            each_device_reqcode_dict['license_count'] = lic_count_str.strip()
            each_device_reqcode_dict[
                'license_entitlement_tag'] = lic_ent_tag_str.strip()
            print("\n\n")
            print("**** Importing license count...")
            print(each_device_reqcode_dict['license_count'])
            print("**** Importing license cent tag...")
            print(each_device_reqcode_dict['license_entitlement_tag'])
            print("\n\n")
            each_device_reqcode_dict['tftp_server_ip'] = ""
            each_device_reqcode_dict['tftp_server_path'] = ""
            each_device_reqcode_dict['device_uuid'] = device['device-uuid']

            # Prepare fields for device_store
            each_device_store_dict['uuid'] = uuid
            each_device_store_dict['ipaddr'] = device['device-uuid']
            each_device_store_dict['username'] = "******"
            each_device_store_dict['password'] = "******"
            each_device_store_dict['sa_name'] = device['sa-name']
            each_device_store_dict['va_name'] = device['va-name']
            each_device_store_dict['domain'] = device['domain']
            each_device_store_dict['device_uuid'] = device['device-uuid']

            # Prepare fields for upload_info_store
            each_device_upload_info_store_dict['uuid'] = uuid
            each_device_upload_info_store_dict['userid'] = "NA"
            each_device_upload_info_store_dict['filename'] = registration_name
            each_device_upload_info_store_dict['type'] = "slr"
            each_device_upload_info_store_dict[
                'timestamp'] = datetime.datetime.fromtimestamp(
                    time.time()).strftime('%Y-%m-%d %H:%M:%S')
            # each_device_upload_info_store_dict['status'] = "S2c"
            each_device_upload_info_store_dict['status'] = "S2ci"

            # Now add each_device_reqcode_dict to update_slr_reqcode_table_list
            insert_slr_reqcode_table_list.append(each_device_reqcode_dict)

            # Now add each_device_store_dict to update_device_store_table_list
            insert_device_store_table_list.append(each_device_store_dict)

            # Now add each_device_upload_info_store_dict to insert_upload_info_store_table_list
            insert_upload_info_store_table_list.append(
                each_device_upload_info_store_dict)

        # Now print list of flat key-value pair dict - update_slr_reqcode_table_list
        print(
            "==>> Printing update_slr_reqcode_table_list before inserting into slr_request_code_tbl..."
        )
        print(insert_slr_reqcode_table_list)

        # Now print list of flat key-value pair dict - update_device_store_table_list
        print(
            "==>> Printing update_device_store_table_list before inserting into device_store..."
        )
        print(insert_device_store_table_list)

        # Now print list of flat key-value pair dict - insert_upload_info_store_table_list
        print(
            "==>> Printing insert_upload_info_store_table_list before inserting into upload_info_store"
        )
        print(insert_upload_info_store_table_list)

        try:
            TokensModel.insert_slr(uuid, insert_slr_reqcode_table_list,
                                   "slr_request_code_tbl")
            print(
                "==>> Now printing slr_request_code_tbl after updateing request_codes..."
            )
            if TokensModel.find_by_uuid(uuid, "slr_request_code_tbl"):
                print("==>> Done printing slr_request_code_tbl")
        except Exception as e:
            print(
                "==>> Printig exception while inserting data into slr_request_code_tbl..."
            )
            print(e)
            return {
                'message':
                "Data insert operation slr_request_code_tbl failed!",
                'code': 500
            }

        try:
            TokensModel.insert(uuid, insert_device_store_table_list,
                               "device_store")
            print(
                "==>> Now printing device_store after updating sa, va, domain..."
            )
            if TokensModel.find_by_uuid(uuid, "device_store"):
                print("==>> Done printing device_store")
        except Exception as e:
            print(
                "==>> Printig exception while inserting data into device_store..."
            )
            print(e)
            return {
                'message': "Data insert operation device_store failed!",
                'code': 500
            }

        try:
            TokensModel.insert(uuid, insert_upload_info_store_table_list,
                               "upload_info_store")
            print(
                "==>> Now printing upload_info_store after updating registration-name, status..."
            )
            if TokensModel.find_by_uuid(uuid, "upload_info_store"):
                print("==>> Done printing upload_info_store")
        except Exception as e:
            print(
                "==>> Printig exception while inserting data into upload_info_store..."
            )
            print(e)
            return {
                'message': "Data insert operation device_store failed!",
                'code': 500
            }

        # Finally return success - 201
        return {'message': "Tables successfully updated!", 'code': 201}
Example #3
0
    def post(self):
        File.parser.add_argument('registration_type',
                                 type=str,
                                 required=True,
                                 help="This field cannot be blank."
                                 )
        data = File.parser.parse_args()
        print("OAuth token is:", data['oauth_token'])

        # Generate UUID to identify registration request
        uuid_str = str(uuid.uuid4())

        if 'file' not in request.files:
            return {"message": "No File in the request!"}, 400
        file = request.files['file']

        if file.filename == '':
            return {'message': "No File selected!"}, 400

        if not File.allowed_file(file.filename):
            return {'message': "File type not allowed! Only CSV files are allowed!"}, 400

        # Create dictionary for upload_info_store
        upload_info_dict = {}
        upload_info_dict['uuid'] = uuid_str
        upload_info_dict['userid'] = config.USER_ID
        upload_info_dict['filename'] = file.filename
        upload_info_dict['type'] = data['registration_type']
        upload_info_dict['timestamp'] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        upload_info_dict['status'] = "csv_file_uploaded"

        # Also set REGISTRATION_NAME as filename in config file
        config.REGISTRATION_NAME = file.filename

        # Create dictionaries for device_store, validation_store, device_status_store
        converted_json, converted_validation_json, converted_status_json = File.csv_to_json(file)

        # Enter data into the database store device_store
        if TokensModel.find_by_uuid(uuid_str, "device_store"):
            return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400

        try:
            TokensModel.insert(uuid_str, converted_json, "device_store")
        except Exception as e:
            print(e)
            return {"message": "Data insert operation device_store failed!"}, 500

        # Enter data into the database store account_validation
        if TokensModel.find_by_uuid(uuid_str, "validation_store"):
            return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400

        try:
            TokensModel.insert(uuid_str, converted_validation_json, "validation_store")
        except Exception as e:
            print(e)
            return {"message": "Data insert operation validation_store failed!"}, 500

        # Enter data into the database store device_status_store
        if TokensModel.find_by_uuid(uuid_str, "device_status_store"):
            return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400

        try:
            TokensModel.insert(uuid_str, converted_status_json, "device_status_store")
        except Exception as e:
            print(e)
            return {"message": "Data insert operation device_status_store failed!"}, 500

        try:
            if data['registration_type'] == 'slr':
                TokensModel.insert(uuid_str, converted_json, "slr_request_code_tbl")
        except Exception as e:
            print (e)
            return {"message": "Data insert operation slr_request_code_tbl failed!"}, 500

        # Enter data into the database store upload_info_store
        if TokensModel.find_by_uuid(uuid_str, "upload_info_store"):
            return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400

        try:
            TokensModel.insert(uuid_str, [upload_info_dict], "upload_info_store")
        except Exception as e:
            print(e)
            return {"message": "Data insert operation failed!"}, 500

        config.NO_OF_DEVICES = len(converted_json)
        config.NO_OF_PAGES = ceil(len(converted_json)/10)
        new_request = {
                'uuid': uuid_str,
                'totalpages': config.NO_OF_PAGES,
                'message': 'File is uploaded!'
        }

        # For debugging
        print(new_request)
        if TokensModel.find_by_uuid(uuid_str, "validation_store"):
            print("Printed validation_store")
        if TokensModel.find_by_uuid(uuid_str, "device_status_store"):
            print("Printed device_status_store")
        if TokensModel.find_by_uuid(uuid_str, "upload_info_store"):
            print("Printed upload_info_store")

        return new_request, 201