Step 4 - Add input validation

In this step, we are going to add our input validation to our main python file. Breaking the problem down into smaller parts is called decomposition. By tackling each element separately makes it easier to solve big problems.

In our code below, we have added our input validation as a function, each of the if-elif-else statements will return True or False boolean values. We have added a call to the input validation function to the for loop in the translate_loop() function.

  • Create a new file called lab_7_step_5_input_validation.py add the following code:
# Standard Imports
import argparse
import json

# 3rd Party Imports
import boto3

# Arguments
parser = argparse.ArgumentParser(description="Provides translation  between one source language and another of the same set of languages.")
parser.add_argument(
    '--file',
    dest='filename',
    help="The path to the input file. The file should be valid json",
    required=True
    )

args = parser.parse_args()

# Functions

# Open the input file to get the json.
def open_input():
    with open(args.filename) as file_object:
        contents = json.load(file_object)
        return contents['Input']

# Boto3 function to use Amazon Translate to translate the text and only return the Translated Text
def translate_text(**kwargs):
    client = boto3.client('translate')
    response = client.translate_text(**kwargs)
    print(response['TranslatedText'])

# Add a Loop to iterate over the json file.
def translate_loop():
    input_text = open_input()
    for item in input_text:
        if input_validation(item) == True:
            translate_text(**item)
        else:
            raise SystemError

# Add our input validation as a function here.
def input_validation(item):
    languages = ["af","sq","am","ar","az","bn","bs","bg","zh","zh-TW","hr","cs","da","fa-AF",
                "nl","en","et","fi","fr","fr-CA","ka","de","el","ha","he","hi","hu","id","it",
                "ja","ko","lv","ms","no","fa","ps","pl","pt","ro","ru","sr","sk","sl","so","es",
                "sw","sv","tl","ta","th","tr","uk","ur","vi"
                ]
    json_input=item
    SourceLanguageCode = json_input['SourceLanguageCode']
    TargetLanguageCode = json_input['TargetLanguageCode']

    if SourceLanguageCode == TargetLanguageCode:
        print("The SourceLanguageCode is the same as the TargetLanguageCode - nothing to do")
        return False
    elif SourceLanguageCode not in languages and TargetLanguageCode not in languages:
        print("Neither the SourceLanguageCode and TargetLanguageCode are valid - stopping")
        return False
    elif SourceLanguageCode not in languages:
        print("The SourceLanguageCode is not valid - stopping")
        return False
    elif TargetLanguageCode not in languages:
        print("The TargetLanguageCode is not valid - stopping")
        return False
    elif SourceLanguageCode in languages and TargetLanguageCode in languages:
        print("The SourceLanguageCode and TargetLanguageCode are valid - proceeding")
        return True
    else:
        print("There is an issue")
        return False

# Main Function - use to call other functions
def main():
    translate_loop()

if __name__ == "__main__":
    main()
  • To run the program, enter the following command in the terminal:

    python lab_7_step_5_input_validation.py --file translate_input.json

  1. When you run the code you will notice that it performs the check on each dictionary in the list before moving on.
  • Try changing the translate_input.json file to generate an error. What happens?
  1. Returning both the translated text and also messages about input validation using the print function is not ideal. As a user, we want the translated text, but we want the input validation messages to be generated but not shown. In the next section, we will look at how we can generate log file information to store these messages.

What did we do?

  1. We have added our if-elif-else statements to an input_validation() function. We have also added that for each statement it should return a boolean True or False value for the statement.
  2. In the translate_loop() function we have used an if statement to check if the input_validation() function is returning True or False. If it returns a True value it will process the request. If it returns a False value it will raise a system error.

What Python did

  1. Python ran through each of the statements to check if it is True or False by comparing it to the if-elif-else statements. If it returns True prints the message that it is true and it translates the sentence, if is False it raises an error.