Best Python code snippet using lisa_python
device.py
Source:device.py  
...8def create_new_device(app, user):9    device_schema = DeviceSchema()10    user_device_schema = UserDeviceSchema()11    device_data = {12        'device_id': generate_random_chars(16),13        'secret': generate_random_chars(16),14        'type': DeviceType.unknown.value15    }16    device = Device()17    user_device = UserDevice()18    device, errors = device_schema.load(device_data)19    if errors:20        app.session.rollback()21        return False22    else:23        try:24            app.session.add(device)25            app.session.commit()26            logging.getLogger().info("Saved device {}".format(device))27            user_device_data = {28                'device_id': device.id,29                'user_id': user.id30            }31            user_device, errors = user_device_schema.load(user_device_data)32            app.session.add(user_device)33            app.session.commit()34            logging.getLogger().info("Saved UserDevice {}".format(user_device))35        except Exception as e:36            logging.getLogger().info("Exception saving service provider{}".format(e))37            app.session.rollback()38def create_device_on_registration(app, user):39    device_schema = DeviceSchema()40    user_device_schema = UserDeviceSchema()41    device = app.session.query(Device). \42        options(43            Load(Device).load_only("id","secret","registration_status","deleted_at")44        ). \45        filter(Device.deleted_at == None). \46        join(UserDevice).\47        filter(UserDevice.user_id == user.id).\48        one_or_none()49    if device:50        logging.getLogger().warn("User already has a registered device.")51    else:52        device_data = {53            'device_id': generate_random_chars(16),54            'secret': generate_random_chars(16),55            'type': DeviceType.unknown.value56        }57        device = Device()58        user_device = UserDevice()59        device, errors = device_schema.load(device_data)60        if errors:61            app.session.rollback()62            return False63        else:64            try:65                app.session.add(device)66                app.session.commit()67                logging.getLogger().info("Saved device {}".format(device))68                user_device_data = {69                    'device_id': device.id,70                    'user_id': user.id71                }72                user_device, errors = user_device_schema.load(user_device_data)73                app.session.add(user_device)74                app.session.commit()75                logging.getLogger().info("Saved UserDevice {}".format(user_device))76            except Exception as e:77                logging.getLogger().info("Exception saving service provider{}".format(e))78                app.session.rollback()79        return device80def create_desktop_device(app, user, data):81    device_schema = DeviceSchema()82    user_device_schema = UserDeviceSchema()83    device_type = data['push_notification_class']84    try:85        config_environment = os.environ['APP_CONFIG_FILE']86    except Exception:87        config_environment = "local.py"88    environment = re.sub(r'\.py', '', config_environment)89    logging.getLogger().info("Environment {}".format(environment))90    if environment in ["dev", "local"]:91        if device_type == DeviceType.macos.value:92            push_notification_certificate_id = 693        elif device_type == DeviceType.windows.value:94            push_notification_certificate_id = 895    elif environment in ["prod", "stage"]:96        if device_type == DeviceType.macos.value:97            push_notification_certificate_id = 598        elif device_type == DeviceType.windows.value:99            push_notification_certificate_id = 7100    logging.getLogger().info("push_notification_certificate_id {}".format(push_notification_certificate_id))101    device_data = {102        'device_id': generate_random_chars(16),103        'secret': generate_random_chars(16),104        'push_notification_token': data['notification_token'],105        'type': device_type,106        'push_notification_certificate_id': push_notification_certificate_id107    }108    device = Device()109    user_device = UserDevice()110    device, errors = device_schema.load(device_data)111    device.registration_status = RegistrationStatus.completed.name112    if errors:113        app.session.rollback()114        return False115    else:116        try:117            app.session.add(device)...random_pw_generator.py
Source:random_pw_generator.py  
...27        str(char_types[2]): numbers28    }29def random_char(char_set):30    return char_set[random.randint(0, len(char_set) - 1)]31def generate_random_chars(char_set, num_of_needed_chars):32    # create string of random chars33    # of length specified by the user.34    chars = ""35    for ch in range(0, num_of_needed_chars):36        chars += random_char(char_set)37    return chars38def generate_password_template(length):39    # hepler function:40    # create array with length of len(user_input["total_length"]).41    # fill with unique numbers from 0 to (len(password) - 1).42    # these numbers will be used as indexes in randomize funcion43    # to point to chars in password variable.44    password_template = []45    while len(password_template) != length:46        num = random.randint(0, length - 1)47        if num in password_template:48            continue49        else:50            password_template.append(num)51    return password_template52def randomize(non_randomized_string, template):53    # use each member of 'template'54    # as an index of a char in non_randomized_password55    # to simulate randomization.56    randomized_password = ""57    for index in range(0, len(template)):58        char_index = int(template[index])59        randomized_password += non_randomized_string[char_index]60    return randomized_password61def generate_randomized_password(user_input):62    print(user_input)63    char_types = generate_char_types()64    chars = generate_chars()65    # append random chars in order.66    password = ""67    password += generate_random_chars(68        chars[char_types[0]],69        user_input[char_types[0]]70    )71    password += generate_random_chars(72        chars[char_types[1]],73        user_input[char_types[1]]74    )75    password += generate_random_chars(76        chars[char_types[2]],77        user_input[char_types[2]]78    )79    # randomise orderded string using 'password_template' helper.80    password_template = generate_password_template(user_input["total_length"])81    randomized_password = randomize(password, password_template)82    return randomized_password83def execute():84    print("Welcome to the PyPassword Generator!")85    print(f"Your password is: {generate_randomized_password(user_input())}")...main.py
Source:main.py  
...5           'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']6numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']7symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']8# METHODS9def generate_random_chars(count, chars):10    return [random.choice(chars) for _ in range(count)]11def flatten_list(nested_list):12    return [item for sublist in nested_list for item in sublist]13# MAIN14print("Welcome to the PyPassword Generator")15char_count = int(input("How many characters would you like in your password?\n"))16letter_count = random.randint(0, char_count)17char_count -= letter_count18number_count = random.randint(0, char_count)19char_count -= number_count20symbol_count = char_count21password = generate_random_chars(letter_count, letters)22password.append(generate_random_chars(number_count, numbers))23password.append(generate_random_chars(symbol_count, symbols))24password = flatten_list(password)25random.shuffle(password)26password = ''.join(password)27print("Your new password is:")...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
