Skip to content

query

validate_input

validate_input(prompt: str, response: Iterable[str]) -> str

Following a provided prompt, validate that the user input is a valid response then return the response outcome

Parameters:

  • prompt (str) –

    The desired prompt

  • response (Iterable[str]) –

    The response values to accept as keys and the resulting data to return as values

Returns: The data matching the chosen response key

Source code in symdesign/utils/query.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def validate_input(prompt: str, response: Iterable[str]) -> str:
    """Following a provided prompt, validate that the user input is a valid response then return the response outcome

    Args:
        prompt: The desired prompt
        response: The response values to accept as keys and the resulting data to return as values
    Returns:
        The data matching the chosen response key
    """
    _input = input(f'{prompt}\nChoose from [{", ".join(response)}]{input_string}')
    while _input not in response:
        _input = input(f"'Invalid input... '{_input}' isn't a valid response. Try again{input_string}'")

    return _input

validate_type

validate_type(value: Any, dtype: Callable = str) -> bool

Provide a user prompt to ensure the user input is what is desired

Returns:

  • bool

    A True value indicates the user wants to proceed. False indicates we should get input again.

Source code in symdesign/utils/query.py
39
40
41
42
43
44
45
46
47
48
49
50
def validate_type(value: Any, dtype: Callable = str) -> bool:
    """Provide a user prompt to ensure the user input is what is desired

    Returns:
        A True value indicates the user wants to proceed. False indicates we should get input again.
    """
    try:
        dtype(value)
        return True
    except ValueError:
        print(f"The value '{value}' can't be converted to the type {type(dtype).__name__}. Try again...")
        return False

boolean_choice

boolean_choice() -> bool

Retrieve user input from a boolean confirmation prompt "Please specify [y/n] Input: " to control program flow

Returns:

  • bool

    A True value indicates the user wants to proceed. False indicates they do not

Source code in symdesign/utils/query.py
53
54
55
56
57
58
59
60
61
62
63
def boolean_choice() -> bool:
    """Retrieve user input from a boolean confirmation prompt "Please specify [y/n] Input: " to control program flow

    Returns:
        A True value indicates the user wants to proceed. False indicates they do not
    """
    confirm = input(boolean_input_string).lower()
    while confirm not in bool_d:
        confirm = input(f"'{confirm}' isn't a valid choice. Chose either [y/n]{input_string}").lower()

    return bool_d[confirm]

verify_choice

verify_choice() -> bool

Provide a verification prompt (If this is correct, indicate y, if not n, and you can re-input) to ensure a prior input was desired

Returns:

  • bool

    A True value indicates the user wants to proceed. False indicates we should get input again.

Source code in symdesign/utils/query.py
66
67
68
69
70
71
72
73
74
75
76
77
def verify_choice() -> bool:
    """Provide a verification prompt (If this is correct, indicate y, if not n, and you can re-input) to ensure a prior
    input was desired

    Returns:
        A True value indicates the user wants to proceed. False indicates we should get input again.
    """
    confirm = input(confirmation_string).lower()
    while confirm not in bool_d:
        confirm = input(f"'{confirm}' isn't a valid choice. Chose either [y/n]{input_string}").lower()

    return bool_d[confirm]

connection_exception_handler

connection_exception_handler(url: str, max_attempts: int = 2) -> Response | None

Wrap requests GET commands in an exception handler which attempts to aqcuire the data multiple times if the connection is refused due to a high volume of requests

Parameters:

  • url (str) –

    The url to GET information from

  • max_attempts (int, default: 2 ) –

    The number of queries that should be attempts without successful return

Returns: The json formatted response to the url GET or None

Source code in symdesign/utils/query.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def connection_exception_handler(url: str, max_attempts: int = 2) -> requests.Response | None:
    """Wrap requests GET commands in an exception handler which attempts to aqcuire the data multiple times if the
    connection is refused due to a high volume of requests

    Args:
        url: The url to GET information from
        max_attempts: The number of queries that should be attempts without successful return
    Returns:
        The json formatted response to the url GET or None
    """
    global MAX_RESOURCE_ATTEMPTS
    iteration = 1
    while True:
        try:  # Todo change data retrieval to POST
            query_response = requests.get(url)
        except requests.exceptions.ConnectionError:
            logger.debug('Requests ran into a connection error. Sleeping, then retrying')
            time.sleep(1)
            iteration += 1
        else:
            try:
                if query_response.status_code == 200:
                    return query_response
                elif query_response.status_code == 204:
                    logger.warning('No response was returned. Your query likely found no matches!')
                elif query_response.status_code == 429:
                    logger.debug('Too many requests, pausing momentarily')
                    time.sleep(2)
                else:
                    logger.debug(f'Your query returned an unrecognized status code ({query_response.status_code})')
                    time.sleep(1)
                    iteration += 1
            except ValueError as error:  # The json response was bad...
                logger.error(f"A json response was missing or corrupted from '{url}' Error: {error}")
                break

        if MAX_RESOURCE_ATTEMPTS > 2:
            # Quit this loop. We probably have no internet connection
            break
        elif iteration == max_attempts:
            time.sleep(5)  # Try one long sleep then go once more
        elif iteration > max_attempts:
            MAX_RESOURCE_ATTEMPTS += 1
            logger.error('The maximum number of resource fetch attempts was made with no resolution. '
                         f"Offending request '{url}'")
            break

    return

format_input

format_input(prompt: str) -> str

Format the builtin input() using program specific formatting

Parameters:

  • prompt (str) –

    The desired prompt

Returns: The input

Source code in symdesign/utils/query.py
130
131
132
133
134
135
136
137
138
def format_input(prompt: str) -> str:
    """Format the builtin input() using program specific formatting

    Args:
        prompt: The desired prompt
    Returns:
        The input
    """
    return input(f'{prompt}{input_string}')

confirm_input_action

confirm_input_action(input_message: str) -> bool

Given a prompt, query the user to verify their input is desired

Parameters:

  • input_message (str) –

    A message specifying the program will take a course of action upon user consent

Returns: True if the user wants to proceed with the described input_message otherwise False

Source code in symdesign/utils/query.py
141
142
143
144
145
146
147
148
149
150
151
152
153
def confirm_input_action(input_message: str) -> bool:
    """Given a prompt, query the user to verify their input is desired

    Args:
        input_message: A message specifying the program will take a course of action upon user consent
    Returns:
        True if the user wants to proceed with the described input_message otherwise False
    """
    confirm = input(f'{input_message}\n{confirmation_string}').lower()
    while confirm not in bool_d:
        confirm = input(f"{confirm} isn't a valid choice, please try again{input_string}")

    return bool_d[confirm]

validate_input_return_response_value

validate_input_return_response_value(prompt: str, response: dict[str, Any]) -> Any

Following a provided prompt, validate that the user input is a valid response then return the response outcome

Parameters:

  • prompt (str) –

    The desired prompt

  • response (dict[str, Any]) –

    The response values to accept as keys and the resulting data to return as values

Returns: The data matching the chosen response key

Source code in symdesign/utils/query.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def validate_input_return_response_value(prompt: str, response: dict[str, Any]) -> Any:
    """Following a provided prompt, validate that the user input is a valid response then return the response outcome

    Args:
        prompt: The desired prompt
        response: The response values to accept as keys and the resulting data to return as values
    Returns:
        The data matching the chosen response key
    """
    choice = input(f'{prompt}\nChoose from [{", ".join(response)}]{input_string}')
    while choice not in response:
        choice = input(f"{choice} isn't a valid choice, please try again{input_string}")

    return response[choice]